@strapi/typescript-utils 0.0.0-next.e9bb5ccdc459f4c6b6717a2d5d86359b7a47d47d → 0.0.0-next.ee56af7ae29770097422de95c0d5500908dce15c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ const { factory } = require('typescript');
4
+
5
+ const { models } = require('../common');
6
+ const { emitDefinitions, format, generateSharedExtensionDefinition } = require('../utils');
7
+
8
+ const NO_COMPONENT_PLACEHOLDER_COMMENT = `/*
9
+ * The app doesn't have any components yet.
10
+ */
11
+ `;
12
+
13
+ /**
14
+ * Generate type definitions for Strapi Components
15
+ *
16
+ * @param {object} [options]
17
+ * @param {object} options.strapi
18
+ * @param {object} options.logger
19
+ * @param {string} options.pwd
20
+ */
21
+ const generateComponentsDefinitions = async (options = {}) => {
22
+ const { strapi } = options;
23
+
24
+ const { components } = strapi;
25
+
26
+ const componentsDefinitions = Object.values(components).map((contentType) => ({
27
+ uid: contentType.uid,
28
+ definition: models.schema.generateSchemaDefinition(contentType),
29
+ }));
30
+
31
+ options.logger.debug(`Found ${componentsDefinitions.length} components.`);
32
+
33
+ if (componentsDefinitions.length === 0) {
34
+ return { output: NO_COMPONENT_PLACEHOLDER_COMMENT, stats: {} };
35
+ }
36
+
37
+ const formattedSchemasDefinitions = componentsDefinitions.reduce((acc, def) => {
38
+ acc.push(
39
+ // Definition
40
+ def.definition,
41
+
42
+ // Add a newline between each interface declaration
43
+ factory.createIdentifier('\n')
44
+ );
45
+
46
+ return acc;
47
+ }, []);
48
+
49
+ const allDefinitions = [
50
+ // Imports
51
+ ...models.imports.generateImportDefinition(),
52
+
53
+ // Add a newline after the import statement
54
+ factory.createIdentifier('\n'),
55
+
56
+ // Schemas
57
+ ...formattedSchemasDefinitions,
58
+
59
+ // Global
60
+ generateSharedExtensionDefinition('ComponentSchemas', componentsDefinitions),
61
+ ];
62
+
63
+ const output = emitDefinitions(allDefinitions);
64
+ const formattedOutput = await format(output);
65
+
66
+ return { output: formattedOutput, stats: {} };
67
+ };
68
+
69
+ module.exports = generateComponentsDefinitions;
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ const TYPES_ROOT_DIR = 'types';
4
+ const GENERATED_OUT_DIR = 'generated';
5
+
6
+ module.exports = { GENERATED_OUT_DIR, TYPES_ROOT_DIR };
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ const { factory } = require('typescript');
4
+
5
+ const { models } = require('../common');
6
+ const { emitDefinitions, format, generateSharedExtensionDefinition } = require('../utils');
7
+
8
+ const NO_CONTENT_TYPE_PLACEHOLDER_COMMENT = `/*
9
+ * The app doesn't have any content-types yet.
10
+ */
11
+ `;
12
+
13
+ /**
14
+ * Generate type definitions for Strapi Content-Types
15
+ *
16
+ * @param {object} [options]
17
+ * @param {object} options.strapi
18
+ * @param {object} options.logger
19
+ * @param {string} options.pwd
20
+ */
21
+ const generateContentTypesDefinitions = async (options = {}) => {
22
+ const { strapi } = options;
23
+
24
+ const { contentTypes } = strapi;
25
+
26
+ const contentTypesDefinitions = Object.values(contentTypes).map((contentType) => ({
27
+ uid: contentType.uid,
28
+ definition: models.schema.generateSchemaDefinition(contentType),
29
+ }));
30
+
31
+ options.logger.debug(`Found ${contentTypesDefinitions.length} content-types.`);
32
+
33
+ if (contentTypesDefinitions.length === 0) {
34
+ return { output: NO_CONTENT_TYPE_PLACEHOLDER_COMMENT, stats: {} };
35
+ }
36
+
37
+ const formattedSchemasDefinitions = contentTypesDefinitions.reduce((acc, def) => {
38
+ acc.push(
39
+ // Definition
40
+ def.definition,
41
+
42
+ // Add a newline between each interface declaration
43
+ factory.createIdentifier('\n')
44
+ );
45
+
46
+ return acc;
47
+ }, []);
48
+
49
+ const allDefinitions = [
50
+ // Imports
51
+ ...models.imports.generateImportDefinition(),
52
+
53
+ // Add a newline after the import statement
54
+ factory.createIdentifier('\n'),
55
+
56
+ // Schemas
57
+ ...formattedSchemasDefinitions,
58
+
59
+ // Global
60
+ generateSharedExtensionDefinition('ContentTypeSchemas', contentTypesDefinitions),
61
+ ];
62
+
63
+ const output = emitDefinitions(allDefinitions);
64
+ const formattedOutput = await format(output);
65
+
66
+ return { output: formattedOutput, stats: {} };
67
+ };
68
+
69
+ module.exports = generateContentTypesDefinitions;
@@ -1,7 +1,122 @@
1
1
  'use strict';
2
2
 
3
- const generateSchemasDefinitions = require('./schemas');
3
+ const path = require('path');
4
+ const chalk = require('chalk');
4
5
 
5
- module.exports = {
6
- generateSchemasDefinitions,
6
+ const { TYPES_ROOT_DIR, GENERATED_OUT_DIR } = require('./constants');
7
+ const { saveDefinitionToFileSystem, createLogger, timer } = require('./utils');
8
+ const generateContentTypesDefinitions = require('./content-types');
9
+ const generateComponentsDefinitions = require('./components');
10
+
11
+ const GENERATORS = {
12
+ contentTypes: generateContentTypesDefinitions,
13
+ components: generateComponentsDefinitions,
7
14
  };
15
+
16
+ /**
17
+ * @typedef GenerateConfig
18
+ *
19
+ * @property {object} strapi
20
+ * @property {boolean} pwd
21
+ * @property {object} [artifacts]
22
+ * @property {boolean} [artifacts.contentTypes]
23
+ * @property {boolean} [artifacts.components]
24
+ * @property {boolean} [artifacts.services]
25
+ * @property {boolean} [artifacts.controllers]
26
+ * @property {boolean} [artifacts.policies]
27
+ * @property {boolean} [artifacts.middlewares]
28
+ * @property {object} [logger]
29
+ * @property {boolean} [logger.silent]
30
+ * @property {boolean} [logger.debug]
31
+ * @property {boolean} [logger.verbose]
32
+ */
33
+
34
+ /**
35
+ * Generate types definitions based on the given configuration
36
+ *
37
+ * @param {GenerateConfig} [config]
38
+ */
39
+ const generate = async (config = {}) => {
40
+ const { pwd, rootDir = TYPES_ROOT_DIR, strapi, artifacts = {}, logger: loggerConfig } = config;
41
+ const reports = {};
42
+ const logger = createLogger(loggerConfig);
43
+ const psTimer = timer().start();
44
+
45
+ const registryPwd = path.join(pwd, rootDir, GENERATED_OUT_DIR);
46
+ const generatorConfig = { strapi, pwd: registryPwd, logger };
47
+
48
+ const returnWithMessage = () => {
49
+ const nbWarnings = chalk.yellow(`${logger.warnings} warning(s)`);
50
+ const nbErrors = chalk.red(`${logger.errors} error(s)`);
51
+
52
+ const status = logger.errors > 0 ? chalk.red('errored') : chalk.green('completed successfully');
53
+
54
+ psTimer.end();
55
+
56
+ logger.info(`The task ${status} with ${nbWarnings} and ${nbErrors} in ${psTimer.duration}s.`);
57
+
58
+ return reports;
59
+ };
60
+
61
+ const enabledArtifacts = Object.keys(artifacts).filter((p) => artifacts[p] === true);
62
+
63
+ logger.info('Starting the type generation process');
64
+ logger.debug(`Enabled artifacts: ${enabledArtifacts.join(', ')}`);
65
+
66
+ for (const artifact of enabledArtifacts) {
67
+ const boldArtifact = chalk.bold(artifact); // used for log messages
68
+
69
+ logger.info(`Generating types for ${boldArtifact}`);
70
+
71
+ if (artifact in GENERATORS) {
72
+ const generator = GENERATORS[artifact];
73
+
74
+ try {
75
+ const artifactGenTimer = timer().start();
76
+
77
+ reports[artifact] = await generator(generatorConfig);
78
+
79
+ artifactGenTimer.end();
80
+
81
+ logger.debug(`Generated ${boldArtifact} in ${artifactGenTimer.duration}s`);
82
+ } catch (e) {
83
+ logger.error(
84
+ `Failed to generate types for ${boldArtifact}: ${e.message ?? e.toString()}. Exiting`
85
+ );
86
+ return returnWithMessage();
87
+ }
88
+ } else {
89
+ logger.warn(`The types generator for ${boldArtifact} is not implemented, skipping`);
90
+ }
91
+ }
92
+
93
+ for (const artifact of Object.keys(reports)) {
94
+ const boldArtifact = chalk.bold(artifact); // used for log messages
95
+
96
+ const artifactFsTimer = timer().start();
97
+
98
+ const report = reports[artifact];
99
+ const filename = `${artifact}.d.ts`;
100
+
101
+ try {
102
+ const outPath = await saveDefinitionToFileSystem(registryPwd, filename, report.output);
103
+ const relativeOutPath = path.relative(process.cwd(), outPath);
104
+
105
+ artifactFsTimer.end();
106
+
107
+ logger.info(`Saved ${boldArtifact} types in ${chalk.bold(relativeOutPath)}`);
108
+ logger.debug(`Saved ${boldArtifact} in ${artifactFsTimer.duration}s`);
109
+ } catch (e) {
110
+ logger.error(
111
+ `An error occurred while saving ${boldArtifact} types to the filesystem: ${
112
+ e.message ?? e.toString()
113
+ }. Exiting`
114
+ );
115
+ return returnWithMessage();
116
+ }
117
+ }
118
+
119
+ return returnWithMessage();
120
+ };
121
+
122
+ module.exports = { generate };
@@ -0,0 +1,216 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const assert = require('assert');
5
+ const ts = require('typescript');
6
+ const fse = require('fs-extra');
7
+ const chalk = require('chalk');
8
+
9
+ const { factory } = ts;
10
+
11
+ const MODULE_DECLARATION = '@strapi/strapi';
12
+ const PUBLIC_NAMESPACE = 'Public';
13
+
14
+ /**
15
+ * Aggregate the given TypeScript nodes into a single string
16
+ *
17
+ * @param {ts.Node[]} definitions
18
+ * @return {string}
19
+ */
20
+ const emitDefinitions = (definitions) => {
21
+ const nodeArray = factory.createNodeArray(definitions);
22
+
23
+ const sourceFile = ts.createSourceFile(
24
+ 'placeholder.ts',
25
+ '',
26
+ ts.ScriptTarget.ESNext,
27
+ true,
28
+ ts.ScriptKind.TS
29
+ );
30
+
31
+ const printer = ts.createPrinter({ omitTrailingSemicolon: true });
32
+
33
+ return printer.printList(ts.ListFormat.MultiLine, nodeArray, sourceFile);
34
+ };
35
+
36
+ /**
37
+ * Save the given string representation of TS nodes in a file
38
+ * If the given directory doesn't exist, it'll be created automatically
39
+ *
40
+ * @param {string} dir
41
+ * @param {string} file
42
+ * @param {string} content
43
+ *
44
+ * @return {Promise<string>} The path of the created file
45
+ */
46
+ const saveDefinitionToFileSystem = async (dir, file, content) => {
47
+ const filepath = path.join(dir, file);
48
+
49
+ fse.ensureDirSync(dir);
50
+ await fse.writeFile(filepath, content);
51
+
52
+ return filepath;
53
+ };
54
+
55
+ /**
56
+ * Format the given definitions.
57
+ * Uses the existing config if one is defined in the project.
58
+ *
59
+ * @param {string} content
60
+ * @returns {Promise<string>}
61
+ */
62
+ const format = async (content) => {
63
+ // eslint-disable-next-line node/no-unsupported-features/es-syntax
64
+ const prettier = await import('prettier'); // ESM-only
65
+
66
+ const configFile = await prettier.resolveConfigFile();
67
+ const config = configFile
68
+ ? await prettier.resolveConfig(configFile)
69
+ : // Default config
70
+ {
71
+ singleQuote: true,
72
+ useTabs: false,
73
+ tabWidth: 2,
74
+ };
75
+
76
+ Object.assign(config, { parser: 'typescript' });
77
+
78
+ return prettier.format(content, config);
79
+ };
80
+
81
+ /**
82
+ * Generate the extension block for a shared component from strapi/strapi
83
+ *
84
+ * @param {string} registry The registry to extend
85
+ * @param {Array<{ uid: string; definition: ts.TypeNode }>} definitions
86
+ * @returns {ts.ModuleDeclaration}
87
+ */
88
+ const generateSharedExtensionDefinition = (registry, definitions) => {
89
+ const properties = definitions.map(({ uid, definition }) =>
90
+ factory.createPropertySignature(
91
+ undefined,
92
+ factory.createStringLiteral(uid, true),
93
+ undefined,
94
+ factory.createTypeReferenceNode(factory.createIdentifier(definition.name.escapedText))
95
+ )
96
+ );
97
+
98
+ return factory.createModuleDeclaration(
99
+ [factory.createModifier(ts.SyntaxKind.DeclareKeyword)],
100
+ factory.createStringLiteral(MODULE_DECLARATION, true),
101
+ factory.createModuleBlock([
102
+ factory.createModuleDeclaration(
103
+ [factory.createModifier(ts.SyntaxKind.ExportKeyword)],
104
+ factory.createIdentifier(PUBLIC_NAMESPACE),
105
+ factory.createModuleBlock(
106
+ properties.length > 0
107
+ ? [
108
+ factory.createInterfaceDeclaration(
109
+ [factory.createModifier(ts.SyntaxKind.ExportKeyword)],
110
+ factory.createIdentifier(registry),
111
+ undefined,
112
+ undefined,
113
+ properties
114
+ ),
115
+ ]
116
+ : []
117
+ )
118
+ ),
119
+ ]),
120
+ ts.NodeFlags.ExportContext
121
+ );
122
+ };
123
+
124
+ const createLogger = (options = {}) => {
125
+ const { silent = false, debug = false } = options;
126
+
127
+ const state = { errors: 0, warning: 0 };
128
+
129
+ return {
130
+ get warnings() {
131
+ return state.warning;
132
+ },
133
+
134
+ get errors() {
135
+ return state.errors;
136
+ },
137
+
138
+ debug(...args) {
139
+ if (silent || !debug) {
140
+ return;
141
+ }
142
+
143
+ console.log(chalk.cyan(`[DEBUG]\t[${new Date().toISOString()}] (Typegen)`), ...args);
144
+ },
145
+
146
+ info(...args) {
147
+ if (silent) {
148
+ return;
149
+ }
150
+
151
+ console.info(chalk.blue(`[INFO]\t[${new Date().toISOString()}] (Typegen)`), ...args);
152
+ },
153
+
154
+ warn(...args) {
155
+ state.warning += 1;
156
+
157
+ if (silent) {
158
+ return;
159
+ }
160
+
161
+ console.warn(chalk.yellow(`[WARN]\t[${new Date().toISOString()}] (Typegen)`), ...args);
162
+ },
163
+
164
+ error(...args) {
165
+ state.errors += 1;
166
+
167
+ if (silent) {
168
+ return;
169
+ }
170
+
171
+ console.error(chalk.red(`[ERROR]\t[${new Date().toISOString()}] (Typegen)`), ...args);
172
+ },
173
+ };
174
+ };
175
+
176
+ const timer = () => {
177
+ const state = {
178
+ start: null,
179
+ end: null,
180
+ };
181
+
182
+ return {
183
+ start() {
184
+ assert(state.start === null, 'The timer has already been started');
185
+ assert(state.end === null, 'The timer has already been ended');
186
+
187
+ state.start = Date.now();
188
+
189
+ return this;
190
+ },
191
+
192
+ end() {
193
+ assert(state.start !== null, 'The timer needs to be started before ending it');
194
+ assert(state.end === null, 'The timer has already been ended');
195
+
196
+ state.end = Date.now();
197
+
198
+ return this;
199
+ },
200
+
201
+ get duration() {
202
+ assert(state.start !== null, 'The timer has not been started');
203
+
204
+ return ((state.end ?? Date.now) - state.start) / 1000;
205
+ },
206
+ };
207
+ };
208
+
209
+ module.exports = {
210
+ emitDefinitions,
211
+ saveDefinitionToFileSystem,
212
+ format,
213
+ generateSharedExtensionDefinition,
214
+ createLogger,
215
+ timer,
216
+ };
package/lib/index.js CHANGED
@@ -2,15 +2,12 @@
2
2
 
3
3
  const compile = require('./compile');
4
4
  const compilers = require('./compilers');
5
- const admin = require('./admin');
6
5
  const utils = require('./utils');
7
6
  const generators = require('./generators');
8
7
 
9
8
  module.exports = {
10
9
  compile,
11
10
  compilers,
12
- admin,
13
11
  generators,
14
-
15
12
  ...utils,
16
13
  };
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "@strapi/typescript-utils",
3
- "version": "0.0.0-next.e9bb5ccdc459f4c6b6717a2d5d86359b7a47d47d",
3
+ "version": "0.0.0-next.ee56af7ae29770097422de95c0d5500908dce15c",
4
4
  "description": "Typescript support for Strapi",
5
5
  "keywords": [
6
6
  "strapi",
7
7
  "generators"
8
8
  ],
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git://github.com/strapi/strapi.git",
12
+ "directory": "packages/utils/typescript"
13
+ },
9
14
  "license": "SEE LICENSE IN LICENSE",
10
15
  "author": {
11
16
  "name": "Strapi Solutions SAS",
@@ -31,15 +36,18 @@
31
36
  },
32
37
  "dependencies": {
33
38
  "chalk": "4.1.2",
34
- "cli-table3": "0.6.2",
35
- "fs-extra": "10.0.1",
39
+ "cli-table3": "0.6.5",
40
+ "fs-extra": "11.2.0",
36
41
  "lodash": "4.17.21",
37
- "prettier": "2.8.4",
38
- "typescript": "5.0.4"
42
+ "prettier": "3.3.3",
43
+ "typescript": "5.3.2"
44
+ },
45
+ "devDependencies": {
46
+ "@types/fs-extra": "11.0.4"
39
47
  },
40
48
  "engines": {
41
- "node": ">=14.19.1 <=18.x.x",
49
+ "node": ">=18.0.0 <=22.x.x",
42
50
  "npm": ">=6.0.0"
43
51
  },
44
- "gitHead": "e9bb5ccdc459f4c6b6717a2d5d86359b7a47d47d"
52
+ "gitHead": "ee56af7ae29770097422de95c0d5500908dce15c"
45
53
  }
@@ -1,20 +1,19 @@
1
1
  {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
-
4
- "compilerOptions": {
5
- "module": "ES2020",
6
- "moduleResolution": "node",
7
- "lib": ["ES2020", "DOM"],
8
- "target": "ES5",
9
-
10
- "jsx": "react",
11
- "sourceMap": true,
12
- "incremental": true,
13
-
14
- "allowJs": true,
15
- "allowSyntheticDefaultImports": true,
16
- "resolveJsonModule": true,
17
- "noEmit": true,
18
- "skipLibCheck": true
19
- }
20
- }
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "compilerOptions": {
4
+ "target": "ESNext",
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "useDefineForClassFields": true,
8
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
9
+ "allowJs": false,
10
+ "skipLibCheck": true,
11
+ "esModuleInterop": true,
12
+ "allowSyntheticDefaultImports": true,
13
+ "strict": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "resolveJsonModule": true,
16
+ "noEmit": true,
17
+ "jsx": "react-jsx"
18
+ }
19
+ }
@@ -1,19 +1,21 @@
1
1
  {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
-
4
- "compilerOptions": {
5
- "module": "CommonJS",
6
- "moduleResolution": "Node",
7
- "lib": ["ES2020"],
8
- "target": "ES2019",
2
+ "$schema": "https://json.schemastore.org/tsconfig",
9
3
 
10
- "strict": false,
11
- "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true,
4
+ "compilerOptions": {
5
+ "module": "CommonJS",
6
+ "moduleResolution": "Node",
7
+ "lib": ["ES2020"],
8
+ "target": "ES2019",
13
9
 
14
- "incremental": true,
15
- "esModuleInterop": true,
16
- "resolveJsonModule": true,
17
- "noEmitOnError": true
18
- }
19
- }
10
+ "strict": false,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+
14
+ "tsBuildInfoFile": "./.tsbuildinfo",
15
+ "incremental": true,
16
+ "esModuleInterop": true,
17
+ "resolveJsonModule": true,
18
+ "noEmitOnError": true,
19
+ "noImplicitThis": true
20
+ }
21
+ }