@platform/cell.typesystem
Version:
The 'strongly typed sheets' system of the CellOS.
86 lines (85 loc) • 3.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var common_1 = require("../common");
var TypeBuilderNs_1 = require("./TypeBuilderNs");
var TypeSystem_core_1 = require("../TypeSystem.core");
var TypeBuilder = (function () {
function TypeBuilder() {
this.builders = [];
}
TypeBuilder.prototype.toObject = function () {
var _this = this;
return this.builders.reduce(function (acc, builder) {
var ns = builder.uri.toString();
acc[ns] = _this.toDef(builder);
return acc;
}, {});
};
TypeBuilder.prototype.ns = function (uri) {
uri = common_1.Uri.ns(uri);
var exists = this.builders.some(function (ns) { return ns.uri.toString() === uri.toString(); });
if (exists) {
var err = "The namespace '" + uri.toString() + "' already exists";
throw new Error(err);
}
var ns = TypeBuilderNs_1.TypeBuilderNs.create({ uri: uri });
this.builders.push(ns);
return ns;
};
TypeBuilder.prototype.type = function (typename, options) {
var ns = common_1.Uri.create.ns(common_1.Uri.cuid());
return this.ns(ns).type(typename, options);
};
TypeBuilder.prototype.formatType = function (value) {
value = (value || '').trim();
if (value.startsWith('/')) {
var typename = value.replace(/^\/*/, '');
var singular_1 = TypeSystem_core_1.TypeValue.trimArray(typename);
var match = this.builders.find(function (ns) { return ns.types.find(function (type) { return type.typename === singular_1; }); });
if (!match) {
var err = "Failed to prefix type '" + value + "' with namespace. The typename '" + typename + "' was not found in any of the available namespaces.";
throw new Error(err);
}
value = match.uri.toString() + "/" + typename;
}
return value;
};
TypeBuilder.prototype.toDef = function (ns) {
var _this = this;
var columns = {};
var getOrCreateObject = function (target, key) {
return target[key] ? target[key] : (target[key] = {});
};
var attachDef = function (def, column) {
var props = getOrCreateObject(column, 'props');
if (!props.def) {
props.def = def;
}
else {
if (!Array.isArray(props.def)) {
props.def = [props.def];
}
props.def.push(def);
}
};
ns.types.forEach(function (type) {
var typename = type.typename;
type.props
.map(function (prop) { return prop.toObject(); })
.forEach(function (prop) {
var def = common_1.value.deleteUndefined({
prop: typename + "." + prop.name,
type: _this.formatType(prop.type),
target: prop.target,
default: prop.default,
});
var column = getOrCreateObject(columns, prop.column);
attachDef(def, column);
});
});
return { columns: columns };
};
TypeBuilder.create = function () { return new TypeBuilder(); };
return TypeBuilder;
}());
exports.TypeBuilder = TypeBuilder;