@smile/strapi-content-type-to-ts
Version:
A script to generate TypeScript types (intended to be used for API calls) from Strapi content types schemas
270 lines (269 loc) • 17 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var glob_1 = require("glob");
var commander_1 = require("commander");
commander_1.program
.addHelpText('before', 'Script that will generate TypeScript types (intended to be used for API calls) from Strapi content types schemas.')
.option('-s, --strapi-root-directory <path>', 'Path to Strapi root directory', '.')
.option('-e, --custom-fields-extension-directory <directory>', 'Path to the directory containing custom fields extensions', 'custom-field')
.option('-o, --out <file>', 'Output file in which TypeScript types will be written. If not set, prints on stdout.')
.parse();
var options = commander_1.program.opts();
var srcPath = getSrcPath();
var customFieldsExtensionDirectory = options.customFieldsExtensionDirectory;
var outFile = options.out ? fs.createWriteStream(options.out) : undefined;
var apiFiles = getApiFiles();
var componentsFiles = getComponentsFiles();
var PARENTS_INTERFACES = {
DraftAndPublish: "interface DraftAndPublish {\n /**\n * If set to a date, content will be published, at creation, with the corresponding publication date.\n * If not set (undefined), content will be published, at creation, with the date corresponding to the content creation date.\n * If set to null, content will be created in Draft.\n **/\n publishedAt?: Date | null;\n}\n\n"
};
(function () { return __awaiter(void 0, void 0, void 0, function () {
var interfaces, usedParentInterfacesCode, interfacesToExportCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, computeInterfaces()];
case 1:
interfaces = _a.sent();
usedParentInterfacesCode = Array.from(new Set(interfaces.flatMap(function (i) { return i.implementedInterfaces; }))).map(function (ii) { return PARENTS_INTERFACES[ii]; });
interfacesToExportCode = interfaces
.filter(function (i) { return i.interfaceName; })
.sort(function (i1, i2) { return i1.interfaceName.localeCompare(i2.interfaceName); })
.map(function (i) {
return "export interface ".concat(i.interfaceName).concat(i.implementedInterfaces.length ? " extends ".concat(i.implementedInterfaces.join(', ')) : '', " {\n").concat(i.properties.map(function (p) { return " ".concat(p.name).concat(p.required ? '' : '?', ": ").concat(p.type, ";"); }).join('\n'), "\n}\n\n");
});
__spreadArray(__spreadArray([], usedParentInterfacesCode, true), interfacesToExportCode, true).forEach(function (code) {
outFile ? outFile.write(code) : process.stdout.write(code);
});
return [2 /*return*/];
}
});
}); })();
function computeInterfaces() {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], apiFiles, true), componentsFiles, true).map(function (file) { return __awaiter(_this, void 0, void 0, function () {
var schema, _a, _, strapiComponentCategory, strapiComponentName, isComponent, interfaceName, properties, implementedInterfaces;
var _this = this;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
schema = JSON.parse(fs.readFileSync(file).toString());
_a = /components\/([^\/]*)\/(.*)\.json/.exec(file) || [], _ = _a[0], strapiComponentCategory = _a[1], strapiComponentName = _a[2];
isComponent = strapiComponentCategory && strapiComponentName;
interfaceName = schema.info.singularName
? toComponentType(schema.info.singularName)
: isComponent
? "".concat(capitalizeFirstLetter(strapiComponentCategory)).concat(toComponentType(strapiComponentName))
: (function () {
console.error("Unexpected schema: ".concat(file));
return '';
})();
return [4 /*yield*/, Promise.all(Object.entries(schema.attributes).map(function (_a) {
var propertyName = _a[0], schemaAttribute = _a[1];
return __awaiter(_this, void 0, void 0, function () {
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_b = {
name: propertyName,
required: schemaAttribute['required']
};
return [4 /*yield*/, getPropertyType(schemaAttribute)];
case 1: return [2 /*return*/, (_b.type = (_c.sent()),
_b)];
}
});
});
}))];
case 1:
properties = (_c.sent());
implementedInterfaces = [];
if (!!((_b = schema.options) === null || _b === void 0 ? void 0 : _b.draftAndPublish)) {
implementedInterfaces.push('DraftAndPublish');
}
return [2 /*return*/, {
interfaceName: interfaceName,
implementedInterfaces: implementedInterfaces,
properties: properties
}];
}
});
}); }))];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
}
/**
* Computes the property type from the Strapi schema attribute.
* It handles every native types and can handle custom fields by developing extensions.
* @param schemaAttribute
*/
function getPropertyType(schemaAttribute) {
return __awaiter(this, void 0, void 0, function () {
var _a, valueEnum, enumValues, valueRelation, many, valueMedia, multiple, valueComponent, componentType, repeatable, valueDynamicZone, components, valueCustomField, customField, options_1, customFieldPluginPath, e_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = schemaAttribute.type;
switch (_a) {
case 'integer': return [3 /*break*/, 1];
case 'decimal': return [3 /*break*/, 1];
case 'biginteger': return [3 /*break*/, 1];
case 'float': return [3 /*break*/, 1];
case 'string': return [3 /*break*/, 2];
case 'text': return [3 /*break*/, 2];
case 'email': return [3 /*break*/, 2];
case 'richtext': return [3 /*break*/, 2];
case 'password': return [3 /*break*/, 2];
case 'uid': return [3 /*break*/, 2];
case 'date': return [3 /*break*/, 2];
case 'time': return [3 /*break*/, 2];
case 'datetime': return [3 /*break*/, 3];
case 'boolean': return [3 /*break*/, 4];
case 'enumeration': return [3 /*break*/, 5];
case 'relation': return [3 /*break*/, 6];
case 'media': return [3 /*break*/, 7];
case 'component': return [3 /*break*/, 8];
case 'json': return [3 /*break*/, 9];
case 'dynamiczone': return [3 /*break*/, 10];
case 'customField': return [3 /*break*/, 11];
}
return [3 /*break*/, 15];
case 1: return [2 /*return*/, 'number'];
case 2: // A time should be of the form 'HH:mm:ss.SSS'
return [2 /*return*/, 'string'];
case 3: return [2 /*return*/, 'Date'];
case 4: return [2 /*return*/, 'boolean'];
case 5:
valueEnum = schemaAttribute;
enumValues = valueEnum.enum;
return [2 /*return*/, "(".concat(enumValues.map(function (v) { return "`".concat(v, "`"); }).join(' | '), ")")];
case 6:
valueRelation = schemaAttribute;
many = ['oneToMany', 'manyToMany'].includes(valueRelation.relation);
return [2 /*return*/, many
? "number[] | { set: number[] | { id: number }[] } | { disconnect?: number[] | { id: number }[], connect?: number[] | { id: number, position?: { before?: number, after?: number, start?: boolean, end?: boolean } }[] }"
: "number | { set: [number] | [{ id: number }] } | { disconnect?: [number] | [{ id: number }], connect?: [number] | [{ id: number, position?: { before?: number, after?: number, start?: boolean, end?: boolean } }] }"];
case 7:
valueMedia = schemaAttribute;
multiple = valueMedia.multiple;
return [2 /*return*/, multiple ? '{ id: number }[]' : 'number'];
case 8:
valueComponent = schemaAttribute;
componentType = toComponentType(valueComponent.component);
repeatable = valueComponent.repeatable;
return [2 /*return*/, "".concat(componentType).concat(repeatable ? '[]' : '')];
case 9: return [2 /*return*/, 'any'];
case 10:
valueDynamicZone = schemaAttribute;
components = valueDynamicZone.components;
return [2 /*return*/, "(".concat(components.map(function (component) { return toComponentType(component); }).join(' | '), ")[]")];
case 11:
valueCustomField = schemaAttribute;
customField = valueCustomField.customField.replace(/^plugin::/, '');
options_1 = valueCustomField.options;
customFieldPluginPath = path.resolve(path.isAbsolute(customFieldsExtensionDirectory) ? customFieldsExtensionDirectory : path.resolve(process.cwd(), "./".concat(customFieldsExtensionDirectory)), "".concat(customField, ".js"));
_b.label = 12;
case 12:
_b.trys.push([12, 14, , 15]);
return [4 /*yield*/, Promise.resolve("".concat(customFieldPluginPath)).then(function (s) { return require(s); })];
case 13: return [2 /*return*/, (_b.sent())(options_1)];
case 14:
e_1 = _b.sent();
console.error("Missing custom field plugin for ".concat(customField, ".\nCreate a ").concat(customFieldPluginPath, " file with the following signature:\nmodule.exports = function (options) {\n return '...';\n}\n "));
return [2 /*return*/, "any //FIXME: missing custom field plugin for ".concat(customField)];
case 15:
console.error("Type not handled: ".concat(schemaAttribute.type));
return [2 /*return*/, 'any'];
}
});
});
}
function notStrapiRootDirectoryError(e) {
console.error("Directory ".concat(path.resolve(options.strapiRootDirectory), " doesn't look like a Strapi root directory. Try to configure it with --strapi-root-directory <path>"), e);
return process.exit(1);
}
function getSrcPath() {
var srcPath = path.join(options.strapiRootDirectory, '/src');
if (!fs.existsSync(srcPath) || !fs.lstatSync(srcPath).isDirectory()) {
return notStrapiRootDirectoryError();
}
return srcPath;
}
function getApiFiles() {
try {
var apiDir = path.resolve(path.join(srcPath, 'api'));
return (0, glob_1.globSync)('**/schema.json', { cwd: apiDir, absolute: true });
}
catch (e) {
return notStrapiRootDirectoryError(e);
}
}
function getComponentsFiles() {
try {
var componentsDir = path.resolve(path.join(srcPath, 'components'));
return (0, glob_1.globSync)('**/*.json', { cwd: componentsDir, absolute: true });
}
catch (e) {
return notStrapiRootDirectoryError(e);
}
}
function capitalizeFirstLetter(string) {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : string;
}
function toComponentType(componentName) {
var _a, _b;
return componentName ? (_b = (_a = componentName.split(/[.-]/)) === null || _a === void 0 ? void 0 : _a.map(function (v) { return capitalizeFirstLetter(v); })) === null || _b === void 0 ? void 0 : _b.join('') : componentName;
}