strapi-typed-client 2.3.2 → 2.4.1

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.
Files changed (76) hide show
  1. package/README.md +5 -0
  2. package/dist/cjs/plugin/server/src/services/endpoints.js +122 -0
  3. package/dist/cjs/shared/json-schema-to-ts.js +155 -0
  4. package/dist/cli/commands/generate.d.ts +5 -1
  5. package/dist/cli/commands/generate.d.ts.map +1 -1
  6. package/dist/cli/commands/generate.js +34 -7
  7. package/dist/cli/commands/generate.js.map +1 -1
  8. package/dist/cli/commands/watch.d.ts +1 -0
  9. package/dist/cli/commands/watch.d.ts.map +1 -1
  10. package/dist/cli/commands/watch.js +13 -0
  11. package/dist/cli/commands/watch.js.map +1 -1
  12. package/dist/core/endpoint-converter.d.ts +1 -0
  13. package/dist/core/endpoint-converter.d.ts.map +1 -1
  14. package/dist/core/endpoint-converter.js +22 -0
  15. package/dist/core/endpoint-converter.js.map +1 -1
  16. package/dist/core/schema-transformer.js +6 -0
  17. package/dist/core/schema-transformer.js.map +1 -1
  18. package/dist/generator/auth-api-generator.d.ts.map +1 -1
  19. package/dist/generator/auth-api-generator.js +16 -5
  20. package/dist/generator/auth-api-generator.js.map +1 -1
  21. package/dist/generator/client-generator.d.ts +3 -0
  22. package/dist/generator/client-generator.d.ts.map +1 -1
  23. package/dist/generator/client-generator.js +278 -41
  24. package/dist/generator/client-generator.js.map +1 -1
  25. package/dist/generator/custom-api-generator.d.ts +1 -6
  26. package/dist/generator/custom-api-generator.d.ts.map +1 -1
  27. package/dist/generator/custom-api-generator.js +26 -57
  28. package/dist/generator/custom-api-generator.js.map +1 -1
  29. package/dist/generator/index.d.ts +5 -2
  30. package/dist/generator/index.d.ts.map +1 -1
  31. package/dist/generator/index.js +94 -19
  32. package/dist/generator/index.js.map +1 -1
  33. package/dist/generator/input-fields.d.ts +2 -1
  34. package/dist/generator/input-fields.d.ts.map +1 -1
  35. package/dist/generator/input-fields.js +6 -1
  36. package/dist/generator/input-fields.js.map +1 -1
  37. package/dist/generator/plugin-routes-generator.d.ts +30 -0
  38. package/dist/generator/plugin-routes-generator.d.ts.map +1 -0
  39. package/dist/generator/plugin-routes-generator.js +145 -0
  40. package/dist/generator/plugin-routes-generator.js.map +1 -0
  41. package/dist/generator/types-generator.d.ts +10 -0
  42. package/dist/generator/types-generator.d.ts.map +1 -1
  43. package/dist/generator/types-generator.js +189 -40
  44. package/dist/generator/types-generator.js.map +1 -1
  45. package/dist/generator/validation-generator.d.ts.map +1 -1
  46. package/dist/generator/validation-generator.js +22 -1
  47. package/dist/generator/validation-generator.js.map +1 -1
  48. package/dist/next/index.d.ts +2 -0
  49. package/dist/next/index.d.ts.map +1 -1
  50. package/dist/next/index.js +13 -4
  51. package/dist/next/index.js.map +1 -1
  52. package/dist/plugin/server/src/index.d.ts +1 -0
  53. package/dist/plugin/server/src/index.d.ts.map +1 -1
  54. package/dist/plugin/server/src/services/endpoints.d.ts +7 -0
  55. package/dist/plugin/server/src/services/endpoints.d.ts.map +1 -1
  56. package/dist/plugin/server/src/services/endpoints.js +122 -0
  57. package/dist/plugin/server/src/services/endpoints.js.map +1 -1
  58. package/dist/shared/client-header.d.ts +8 -0
  59. package/dist/shared/client-header.d.ts.map +1 -1
  60. package/dist/shared/client-header.js +17 -0
  61. package/dist/shared/client-header.js.map +1 -1
  62. package/dist/shared/custom-types.d.ts +2 -0
  63. package/dist/shared/custom-types.d.ts.map +1 -1
  64. package/dist/shared/index.d.ts +1 -1
  65. package/dist/shared/index.d.ts.map +1 -1
  66. package/dist/shared/index.js +1 -1
  67. package/dist/shared/index.js.map +1 -1
  68. package/dist/shared/json-schema-to-ts.d.ts +9 -0
  69. package/dist/shared/json-schema-to-ts.d.ts.map +1 -0
  70. package/dist/shared/json-schema-to-ts.js +152 -0
  71. package/dist/shared/json-schema-to-ts.js.map +1 -0
  72. package/dist/shared/string-utils.d.ts +1 -0
  73. package/dist/shared/string-utils.d.ts.map +1 -1
  74. package/dist/shared/string-utils.js +7 -2
  75. package/dist/shared/string-utils.js.map +1 -1
  76. package/package.json +1 -1
@@ -0,0 +1,145 @@
1
+ import { extractPathParams, toCamelCase, toIdentifier, toPascalCase, } from '../shared/string-utils.js';
2
+ import { buildMethodParams, buildRequestCall } from './method-signature.js';
3
+ /**
4
+ * Content-API routes of third-party plugins (navigation, comments, …), one
5
+ * class per plugin on `client.<plugin>`. users-permissions keeps its own
6
+ * controller-based classes; upload and i18n come from the plugin registry.
7
+ */
8
+ export function isOtherPluginEndpoint(endpoint) {
9
+ return !!endpoint.pluginName && endpoint.pluginName !== 'users-permissions';
10
+ }
11
+ // A plugin action named like one of these would override BaseAPI's own member
12
+ const BASE_API_MEMBERS = new Set([
13
+ 'constructor',
14
+ 'config',
15
+ 'request',
16
+ 'parseResponse',
17
+ 'buildQueryString',
18
+ 'splitWriteArgs',
19
+ 'getErrorHint',
20
+ ]);
21
+ const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);
22
+ export class PluginRoutesGenerator {
23
+ /**
24
+ * Group the routes by plugin and settle every name up front, so the class
25
+ * emission and the StrapiClient wiring agree. `takenProps` are the
26
+ * StrapiClient members already spoken for.
27
+ */
28
+ plan(endpoints, takenProps) {
29
+ const byPlugin = new Map();
30
+ for (const endpoint of endpoints) {
31
+ // Regex paths such as `/connect/(.*)` have no URL a client can build
32
+ if (!endpoint.pluginName || /[(*]/.test(endpoint.path))
33
+ continue;
34
+ const list = byPlugin.get(endpoint.pluginName) ?? [];
35
+ list.push(endpoint);
36
+ byPlugin.set(endpoint.pluginName, list);
37
+ }
38
+ const props = new Set(takenProps);
39
+ return [...byPlugin.keys()].sort().map(pluginName => {
40
+ const base = toIdentifier(toCamelCase(pluginName));
41
+ const propName = props.has(base) ? `${base}Plugin` : base;
42
+ props.add(propName);
43
+ return {
44
+ pluginName,
45
+ className: `${toIdentifier(toPascalCase(pluginName))}PluginAPI`,
46
+ propName,
47
+ methods: this.nameMethods(byPlugin.get(pluginName)),
48
+ };
49
+ });
50
+ }
51
+ generateClasses(apis) {
52
+ if (apis.length === 0)
53
+ return '';
54
+ const base = `// Plugin routes may answer with XML or plain text (a sitemap, a health check), not only JSON
55
+ class PluginRoutesAPI extends BaseAPI {
56
+ protected override parseResponse<R>(response: Response): Promise<R> {
57
+ const type = response.headers.get('content-type') ?? ''
58
+ return (type === '' || /json/i.test(type) ? response.json() : response.text()) as Promise<R>
59
+ }
60
+ }`;
61
+ return [base, ...apis.map(api => this.generateClass(api))].join('\n\n');
62
+ }
63
+ // Action name when unique in the plugin, else prefixed with its controller
64
+ nameMethods(endpoints) {
65
+ const sorted = [...endpoints].sort((a, b) => a.path.localeCompare(b.path) ||
66
+ a.method.localeCompare(b.method));
67
+ const counts = new Map();
68
+ for (const e of sorted) {
69
+ const name = toIdentifier(toCamelCase(e.action));
70
+ counts.set(name, (counts.get(name) ?? 0) + 1);
71
+ }
72
+ const used = new Set();
73
+ return sorted.map(endpoint => {
74
+ const action = toIdentifier(toCamelCase(endpoint.action));
75
+ let name = counts.get(action) > 1 || BASE_API_MEMBERS.has(action)
76
+ ? toIdentifier(toCamelCase(endpoint.controller)) +
77
+ toPascalCase(endpoint.action)
78
+ : action;
79
+ if (used.has(name) || BASE_API_MEMBERS.has(name)) {
80
+ let n = 2;
81
+ while (used.has(`${name}${n}`))
82
+ n++;
83
+ name = `${name}${n}`;
84
+ }
85
+ used.add(name);
86
+ return { name, endpoint };
87
+ });
88
+ }
89
+ generateClass(api) {
90
+ const typeAliases = [];
91
+ const methods = api.methods.map(({ name, endpoint }) => {
92
+ const typeName = toPascalCase(name);
93
+ const types = endpoint.types;
94
+ const ref = (suffix, type) => {
95
+ if (!type)
96
+ return undefined;
97
+ typeAliases.push(` export type ${typeName}${suffix} = ${type}`);
98
+ return `${api.className}.${typeName}${suffix}`;
99
+ };
100
+ const query = ref('Query', types?.query);
101
+ const body = ref('Body', types?.body);
102
+ const response = ref('Response', types?.response);
103
+ return this.generateMethod(name, endpoint, {
104
+ query,
105
+ body,
106
+ response,
107
+ });
108
+ });
109
+ const namespace = typeAliases.length > 0
110
+ ? `\n\nexport namespace ${api.className} {\n${typeAliases.join('\n')}\n}`
111
+ : '';
112
+ return `/** Content-API routes of the \`${api.pluginName}\` plugin. */
113
+ export class ${api.className} extends PluginRoutesAPI {
114
+ ${methods.join('\n\n')}
115
+ }${namespace}`;
116
+ }
117
+ generateMethod(name, endpoint, types) {
118
+ const hasBody = BODY_METHODS.has(endpoint.method);
119
+ const responseType = types.response ?? 'T';
120
+ const params = buildMethodParams({
121
+ pathParams: extractPathParams(endpoint.path),
122
+ ...(hasBody && {
123
+ data: types.body
124
+ ? { type: `${types.body} | FormData`, optional: false }
125
+ : { type: 'unknown' },
126
+ }),
127
+ query: { type: types.query ?? 'Record<string, unknown>' },
128
+ });
129
+ const path = endpoint.path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, '${encodeURIComponent($1)}');
130
+ const init = hasBody
131
+ ? `{ method: '${endpoint.method}', body: data instanceof FormData ? data : data === undefined ? undefined : JSON.stringify(data) }`
132
+ : endpoint.method === 'GET'
133
+ ? undefined
134
+ : `{ method: '${endpoint.method}' }`;
135
+ return ` /**
136
+ * ${endpoint.method} ${endpoint.path}
137
+ * Handler: ${endpoint.handler}${types.response ? '' : '\n * Response type is not declared by the plugin — pass it as the type argument.'}
138
+ */
139
+ async ${name}${types.response ? '' : '<T = unknown>'}(${params}): Promise<${responseType}> {
140
+ const url = \`\${this.config.baseURL}/api${path}\${this.buildQueryString(params)}\`
141
+ return ${buildRequestCall({ responseType, ...(init && { init }) })}
142
+ }`;
143
+ }
144
+ }
145
+ //# sourceMappingURL=plugin-routes-generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-routes-generator.js","sourceRoot":"","sources":["../../src/generator/plugin-routes-generator.ts"],"names":[],"mappings":"AACA,OAAO,EACH,iBAAiB,EACjB,WAAW,EACX,YAAY,EACZ,YAAY,GACf,MAAM,2BAA2B,CAAA;AACl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();
6
6
  generate(schema: ParsedSchema): string;
7
+ /**
8
+ * Same declarations as `generate`, spread over one file per content type
9
+ * and one per component category, plus `base.ts` for the shared blocks and
10
+ * a `types.ts` barrel so `./types` keeps resolving. Keys are paths relative
11
+ * to the output dir, with `.js` import specifiers like the rest of the
12
+ * generated tree.
13
+ */
14
+ generateSplit(schema: ParsedSchema): Record<string, string>;
15
+ private importsFor;
16
+ private build;
7
17
  private generateBaseTypes;
8
18
  private generateHelperTypes;
9
19
  private docsFor;
@@ -1 +1 @@
1
- {"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../../src/generator/types-generator.ts"],"names":[],"mappings":"AAMA,OAAO,EACH,YAAY,EAIf,MAAM,oBAAoB,CAAA;AAqB3B,qBAAa,cAAc;IACvB,OAAO,CAAC,WAAW,CAAiB;IACpC,OAAO,CAAC,MAAM,CAAC,CAAc;;IAM7B,QAAQ,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM;IAkHtC,OAAO,CAAC,iBAAiB;IAkQzB,OAAO,CAAC,mBAAmB;IAW3B,OAAO,CAAC,OAAO;IASf,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,qBAAqB;IAoB7B,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,0BAA0B;IAalC,OAAO,CAAC,2BAA2B;IAcnC,OAAO,CAAC,oBAAoB;IAkB5B,OAAO,CAAC,cAAc;IA+BtB,OAAO,CAAC,uBAAuB;IAiC/B,OAAO,CAAC,sBAAsB;IAc9B,OAAO,CAAC,iBAAiB;IAgCzB,OAAO,CAAC,0BAA0B;IAsElC,OAAO,CAAC,sBAAsB;IAyB9B,OAAO,CAAC,mBAAmB;IA6B3B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAyC/B;;OAEG;IACH,OAAO,CAAC,yBAAyB;IA6CjC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA0E7B,OAAO,CAAC,uBAAuB;IAS/B;;OAEG;IACH,OAAO,CAAC,oBAAoB;CAqB/B"}
1
+ {"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../../src/generator/types-generator.ts"],"names":[],"mappings":"AASA,OAAO,EACH,YAAY,EAIf,MAAM,oBAAoB,CAAA;AAyC3B,qBAAa,cAAc;IACvB,OAAO,CAAC,WAAW,CAAiB;IACpC,OAAO,CAAC,MAAM,CAAC,CAAc;;IAM7B,QAAQ,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM;IAkBtC;;;;;;OAMG;IACH,aAAa,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAqF3D,OAAO,CAAC,UAAU;IA2BlB,OAAO,CAAC,KAAK;IA0Hb,OAAO,CAAC,iBAAiB;IA6RzB,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,OAAO;IASf,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,qBAAqB;IAoB7B,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,0BAA0B;IAalC,OAAO,CAAC,2BAA2B;IAcnC,OAAO,CAAC,oBAAoB;IAkB5B,OAAO,CAAC,cAAc;IA+BtB,OAAO,CAAC,uBAAuB;IAiC/B,OAAO,CAAC,sBAAsB;IAc9B,OAAO,CAAC,iBAAiB;IAgCzB,OAAO,CAAC,0BAA0B;IAsElC,OAAO,CAAC,sBAAsB;IAiC9B,OAAO,CAAC,mBAAmB;IA6B3B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAyC/B;;OAEG;IACH,OAAO,CAAC,yBAAyB;IA6CjC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA0E7B,OAAO,CAAC,uBAAuB;IAS/B;;OAEG;IACH,OAAO,CAAC,oBAAoB;CAqB/B"}
@@ -1,12 +1,22 @@
1
- import { Project, } from 'ts-morph';
1
+ import * as path from 'path';
2
+ import { Project, SyntaxKind, } from 'ts-morph';
2
3
  import { TypeTransformer } from '../transformer/index.js';
3
4
  import { buildConstraintDocs } from './constraint-docs.js';
5
+ import { toKebabCase } from '../shared/string-utils.js';
6
+ import { SPLIT_TYPES_MARKER } from '../shared/client-header.js';
4
7
  import { dzComponentUids as collectDzComponentUids, inputFields, } from './input-fields.js';
5
8
  import { generateFilterUtilityTypes, generateEntityFilters, generateComponentFilters, generateTypedQueryParams, } from '../core/generator/filters-generator.js';
6
9
  // Object-literal key: bare when a valid identifier, quoted otherwise.
7
10
  function safeKey(name) {
8
11
  return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
9
12
  }
13
+ const TYPES_HEADER = [
14
+ '/* eslint-disable */',
15
+ '// Auto-generated TypeScript types from Strapi schema',
16
+ '// Do not edit manually',
17
+ ];
18
+ // Shared by the split files but kept out of the `types` barrel, so both layouts export the same names
19
+ const INTERNAL_TYPES_FILE = 'collections/_internal.ts';
10
20
  export class TypesGenerator {
11
21
  transformer;
12
22
  schema;
@@ -14,22 +24,124 @@ export class TypesGenerator {
14
24
  this.transformer = new TypeTransformer();
15
25
  }
16
26
  generate(schema) {
17
- this.schema = schema;
18
27
  const project = new Project({ useInMemoryFileSystem: true });
19
28
  const sf = project.createSourceFile('types.ts');
20
29
  // Header comments
21
- sf.addStatements([
22
- '/* eslint-disable */',
23
- '// Auto-generated TypeScript types from Strapi schema',
24
- '// Do not edit manually',
30
+ sf.addStatements(TYPES_HEADER);
31
+ this.build(schema, {
32
+ base: sf,
33
+ contentType: () => sf,
34
+ component: () => sf,
35
+ helpers: sf,
36
+ exportHelpers: false,
37
+ });
38
+ return sf.getFullText();
39
+ }
40
+ /**
41
+ * Same declarations as `generate`, spread over one file per content type
42
+ * and one per component category, plus `base.ts` for the shared blocks and
43
+ * a `types.ts` barrel so `./types` keeps resolving. Keys are paths relative
44
+ * to the output dir, with `.js` import specifiers like the rest of the
45
+ * generated tree.
46
+ */
47
+ generateSplit(schema) {
48
+ const project = new Project({ useInMemoryFileSystem: true });
49
+ const used = new Set([
50
+ 'base.ts',
51
+ 'types.ts',
52
+ INTERNAL_TYPES_FILE,
25
53
  ]);
54
+ const files = new Map();
55
+ const owners = new Map();
56
+ const fileFor = (ownerKey, dir, stem) => {
57
+ const known = owners.get(ownerKey);
58
+ if (known)
59
+ return known;
60
+ const safe = toKebabCase(stem).replace(/[^a-z0-9_-]+/g, '-') || 'type';
61
+ let candidate = `${dir}/${safe}.ts`;
62
+ for (let n = 2; used.has(candidate.toLowerCase()); n++) {
63
+ candidate = `${dir}/${safe}-${n}.ts`;
64
+ }
65
+ used.add(candidate.toLowerCase());
66
+ const sf = project.createSourceFile(candidate);
67
+ files.set(candidate, sf);
68
+ owners.set(ownerKey, sf);
69
+ return sf;
70
+ };
71
+ const base = project.createSourceFile('base.ts');
72
+ files.set('base.ts', base);
73
+ const helpers = project.createSourceFile(INTERNAL_TYPES_FILE);
74
+ files.set(INTERNAL_TYPES_FILE, helpers);
75
+ this.build(schema, {
76
+ base,
77
+ contentType: ct => fileFor(`ct:${ct.name}`, 'collections', ct.cleanName),
78
+ component: c => fileFor(`cat:${c.category}`, 'collections/components', c.category),
79
+ helpers,
80
+ exportHelpers: true,
81
+ });
82
+ // Which file declares each exported name, to turn references into imports
83
+ const declaredIn = new Map();
84
+ for (const [file, sf] of files) {
85
+ for (const name of sf.getExportedDeclarations().keys()) {
86
+ declaredIn.set(name, file);
87
+ }
88
+ }
89
+ const out = {};
90
+ const sorted = [...files.keys()].sort((a, b) => a === 'base.ts' ? -1 : b === 'base.ts' ? 1 : a.localeCompare(b));
91
+ for (const file of sorted) {
92
+ const sf = files.get(file);
93
+ out[file] =
94
+ [TYPES_HEADER.join('\n'), this.importsFor(file, sf, declaredIn)]
95
+ .filter(Boolean)
96
+ .join('\n') +
97
+ '\n\n' +
98
+ sf.getFullText().trimStart();
99
+ }
100
+ const barrel = [
101
+ ...TYPES_HEADER,
102
+ SPLIT_TYPES_MARKER,
103
+ ...sorted
104
+ .filter(file => file !== INTERNAL_TYPES_FILE)
105
+ .map(file => `export * from './${file.replace(/\.ts$/, '.js')}'`),
106
+ '',
107
+ ].join('\n');
108
+ return { 'types.ts': barrel, ...out };
109
+ }
110
+ // `import type` lines for every name a file uses but another file declares
111
+ importsFor(file, sf, declaredIn) {
112
+ const byFile = new Map();
113
+ for (const id of sf.getDescendantsOfKind(SyntaxKind.Identifier)) {
114
+ const parent = id.getParent();
115
+ const nameNode = parent?.getNameNode?.();
116
+ if (nameNode === id)
117
+ continue;
118
+ const from = declaredIn.get(id.getText());
119
+ if (!from || from === file)
120
+ continue;
121
+ if (!byFile.has(from))
122
+ byFile.set(from, new Set());
123
+ byFile.get(from).add(id.getText());
124
+ }
125
+ return [...byFile.entries()]
126
+ .sort(([a], [b]) => a.localeCompare(b))
127
+ .map(([from, names]) => {
128
+ let rel = path.posix.relative(path.posix.dirname(file), from);
129
+ if (!rel.startsWith('.'))
130
+ rel = `./${rel}`;
131
+ return `import type { ${[...names].sort().join(', ')} } from '${rel.replace(/\.ts$/, '.js')}'`;
132
+ })
133
+ .join('\n');
134
+ }
135
+ build(schema, sinks) {
136
+ this.schema = schema;
137
+ const { base } = sinks;
26
138
  // Base types (static block)
27
- sf.addStatements(this.generateBaseTypes());
139
+ base.addStatements(this.generateBaseTypes());
28
140
  // Helper types (static block)
29
- sf.addStatements(this.generateHelperTypes());
141
+ sinks.helpers.addStatements(this.generateHelperTypes(sinks.exportHelpers));
30
142
  // Component interfaces
31
143
  for (const component of schema.components) {
32
- this.addComponentInterface(sf, component);
144
+ this.addComponentInterface(sinks.component(component), component);
33
145
  }
34
146
  // Dynamic-zone variants of component interfaces (with __component
35
147
  // discriminator). Generated only for components actually used in
@@ -39,59 +151,62 @@ export class TypesGenerator {
39
151
  const dzComponentUids = collectDzComponentUids(schema);
40
152
  for (const component of schema.components) {
41
153
  if (dzComponentUids.has(component.uid)) {
42
- this.addComponentDzAlias(sf, component);
154
+ this.addComponentDzAlias(sinks.component(component), component);
43
155
  }
44
156
  }
45
157
  // Component Create/Update Input interfaces
46
158
  for (const component of schema.components) {
47
- this.addComponentInputInterfaces(sf, component);
159
+ this.addComponentInputInterfaces(sinks.component(component), component);
48
160
  }
49
161
  // Dynamic-zone Input variants
50
162
  for (const component of schema.components) {
51
163
  if (dzComponentUids.has(component.uid)) {
52
- this.addComponentDzInputAliases(sf, component);
164
+ this.addComponentDzInputAliases(sinks.component(component), component);
53
165
  }
54
166
  }
55
167
  // Content type interfaces
56
168
  for (const contentType of schema.contentTypes) {
57
- this.addContentTypeInterface(sf, contentType);
169
+ this.addContentTypeInterface(sinks.contentType(contentType), contentType);
58
170
  }
59
171
  // Create/Update Input type interfaces
60
172
  for (const contentType of schema.contentTypes) {
61
- this.addInputTypeInterfaces(sf, contentType);
173
+ this.addInputTypeInterfaces(sinks.contentType(contentType), contentType);
62
174
  }
63
175
  // *Defaults consts (emitted only for entities that declare defaults)
64
176
  for (const contentType of schema.contentTypes) {
65
- this.addDefaultsConst(sf, `${contentType.cleanName}Defaults`, `${contentType.cleanName}CreateInput`, contentType.attributes);
177
+ this.addDefaultsConst(sinks.contentType(contentType), `${contentType.cleanName}Defaults`, `${contentType.cleanName}CreateInput`, contentType.attributes);
66
178
  }
67
179
  for (const component of schema.components) {
68
- this.addDefaultsConst(sf, `${component.cleanName}Defaults`, `${component.cleanName}CreateInput`, component.attributes);
180
+ this.addDefaultsConst(sinks.component(component), `${component.cleanName}Defaults`, `${component.cleanName}CreateInput`, component.attributes);
69
181
  }
70
182
  // Dynamic-zone form carries the __component discriminator; emitted only
71
183
  // for components actually used in a dynamic zone (matches the *DzInput
72
184
  // aliases). Always includes __component, even without attribute defaults.
73
185
  for (const component of schema.components) {
74
186
  if (dzComponentUids.has(component.uid)) {
75
- this.addDefaultsConst(sf, `${component.cleanName}DzDefaults`, `${component.cleanName}DzCreateInput`, component.attributes, [`__component: ${JSON.stringify(component.uid)}`]);
187
+ this.addDefaultsConst(sinks.component(component), `${component.cleanName}DzDefaults`, `${component.cleanName}DzCreateInput`, component.attributes, [`__component: ${JSON.stringify(component.uid)}`]);
76
188
  }
77
189
  }
78
190
  // PopulateParam types
79
- this.addPopulateParams(sf, schema);
191
+ this.addPopulateParams(sinks, schema);
80
192
  // Payload utility types
81
- this.addPayloadUtilityTypes(sf, schema);
193
+ this.addPayloadUtilityTypes(sinks, schema);
82
194
  // Filter utility types (static block)
83
- sf.addStatements(generateFilterUtilityTypes());
195
+ base.addStatements(generateFilterUtilityTypes());
84
196
  // Typed query params (static block)
85
- sf.addStatements(generateTypedQueryParams());
197
+ base.addStatements(generateTypedQueryParams());
86
198
  // Component filters
87
199
  for (const component of schema.components) {
88
- sf.addStatements(generateComponentFilters(component));
200
+ sinks
201
+ .component(component)
202
+ .addStatements(generateComponentFilters(component));
89
203
  }
90
204
  // Entity-specific filters
91
205
  for (const contentType of schema.contentTypes) {
92
- sf.addStatements(generateEntityFilters(contentType));
206
+ sinks
207
+ .contentType(contentType)
208
+ .addStatements(generateEntityFilters(contentType));
93
209
  }
94
- return sf.getFullText();
95
210
  }
96
211
  generateBaseTypes() {
97
212
  return `// Base types
@@ -135,11 +250,38 @@ export interface RelationOperations {
135
250
  }
136
251
 
137
252
  /**
138
- * Input value for a relation field in create/update payloads.
139
- * Accepts an id or reference, an array of them, or the explicit { connect | disconnect | set } form.
253
+ * A single relation target: an id, a documentId or a reference object.
254
+ */
255
+ export type RelationTarget = StrapiID | RelationRef
256
+
257
+ /**
258
+ * Relation operations on a to-one field. Strapi keeps one entry in a to-one
259
+ * relation, so \`connect\` and \`set\` take at most one target.
260
+ */
261
+ export interface ToOneRelationOperations {
262
+ connect?: [] | [RelationTarget] | undefined
263
+ disconnect?: RelationTarget[] | undefined
264
+ set?: [] | [RelationTarget] | undefined
265
+ }
266
+
267
+ /**
268
+ * Cardinality of a relation field, as seen from the field being written.
269
+ * \`oneToMany\` and \`manyToOne\` are opposite sides of the same relationship, so the
270
+ * input type follows the kind of the field itself, not of the relationship.
271
+ */
272
+ export type RelationKind = 'oneToOne' | 'oneToMany' | 'manyToOne' | 'manyToMany'
273
+
274
+ /**
275
+ * Input value for a relation field in create/update payloads, shaped by its cardinality:
276
+ * - to-one (\`oneToOne\`, \`manyToOne\`): one id or reference, at most one in a list or in connect/set, or null to clear.
277
+ * Strapi silently keeps only the last entry when a to-one gets more than one, so the types reject that.
278
+ * - to-many (\`oneToMany\`, \`manyToMany\`): an id or reference (shorthand for a one-element set), an array of them, the explicit { connect | disconnect | set } form, or null to clear.
140
279
  * Passing a plain id or array is equivalent to 'set' — it overwrites existing relations.
280
+ * Without a type argument it accepts every shape, for hand-written helpers that handle any relation.
141
281
  */
142
- export type RelationInput = StrapiID | RelationRef | (StrapiID | RelationRef)[] | RelationOperations | null
282
+ export type RelationInput<K extends RelationKind = RelationKind> = K extends 'oneToOne' | 'manyToOne'
283
+ ? RelationTarget | [] | [RelationTarget] | ToOneRelationOperations | null
284
+ : RelationTarget | RelationTarget[] | RelationOperations | null
143
285
 
144
286
  /**
145
287
  * Input value for a single media file field. Accepts a documentId (string) or
@@ -350,13 +492,15 @@ export interface LinkInline {
350
492
  children: TextNode[]
351
493
  }`;
352
494
  }
353
- generateHelperTypes() {
495
+ generateHelperTypes(exported) {
496
+ // Split mode shares these across files, so they have to be exported
497
+ const ex = exported ? 'export ' : '';
354
498
  return `// Helper types for field and sort options in populate
355
- type _EntityField<T> = Exclude<keyof T & string, '__typename'>
356
- type _SortValue<T> = _EntityField<T> | \`\${_EntityField<T>}:\${"asc" | "desc"}\`
499
+ ${ex}type _EntityField<T> = Exclude<keyof T & string, '__typename'>
500
+ ${ex}type _SortValue<T> = _EntityField<T> | \`\${_EntityField<T>}:\${"asc" | "desc"}\`
357
501
 
358
502
  // Apply fields narrowing from populate entry (e.g. populate: { item: { fields: ["title"] } })
359
- type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry extends { fields: readonly (infer F extends string)[] } ? Pick<TBase, Extract<F | 'id' | 'documentId', keyof TBase>> & Omit<TFull, keyof TBase> : TFull`;
503
+ ${ex}type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry extends { fields: readonly (infer F extends string)[] } ? Pick<TBase, Extract<F | 'id' | 'documentId', keyof TBase>> & Omit<TFull, keyof TBase> : TFull`;
360
504
  }
361
505
  // Constraint/default JSDoc for a property, as a spreadable ts-morph
362
506
  // structure fragment ({} when the attribute declares nothing).
@@ -446,7 +590,7 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
446
590
  case 'media':
447
591
  return field.multiple ? 'MultiMediaInput' : 'MediaInput';
448
592
  case 'relation':
449
- return 'RelationInput';
593
+ return `RelationInput<'${field.relationType}'>`;
450
594
  case 'component': {
451
595
  const inner = `${field.componentType}${mode}Input`;
452
596
  if (field.repeatable)
@@ -499,8 +643,8 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
499
643
  });
500
644
  }
501
645
  }
502
- addPopulateParams(sf, schema) {
503
- sf.addStatements([
646
+ addPopulateParams(sinks, schema) {
647
+ sinks.base.addStatements([
504
648
  '// ============================================',
505
649
  '// PopulateParam types for type-safe populate',
506
650
  '// ============================================',
@@ -509,7 +653,7 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
509
653
  for (const component of schema.components) {
510
654
  const typeBody = this.buildPopulateParamTypeBody(component);
511
655
  if (typeBody) {
512
- sf.addTypeAlias({
656
+ sinks.component(component).addTypeAlias({
513
657
  name: `${component.cleanName}PopulateParam`,
514
658
  isExported: true,
515
659
  type: typeBody,
@@ -520,7 +664,7 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
520
664
  for (const contentType of schema.contentTypes) {
521
665
  const typeBody = this.buildPopulateParamTypeBody(contentType);
522
666
  if (typeBody) {
523
- sf.addTypeAlias({
667
+ sinks.contentType(contentType).addTypeAlias({
524
668
  name: `${contentType.cleanName}PopulateParam`,
525
669
  isExported: true,
526
670
  type: typeBody,
@@ -578,8 +722,9 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
578
722
  return null;
579
723
  return `{\n${fields.join('\n')}\n}`;
580
724
  }
581
- addPayloadUtilityTypes(sf, schema) {
582
- sf.addStatements(`// Prisma-like Payload types for populate support
725
+ addPayloadUtilityTypes(sinks, schema) {
726
+ sinks.base
727
+ .addStatements(`// Prisma-like Payload types for populate support
583
728
  // These types allow type-safe population of relations
584
729
  //
585
730
  // Usage example:
@@ -590,13 +735,17 @@ type _ApplyFields<TFull, TBase, TEntry> = TEntry extends true ? TFull : TEntry e
590
735
  // Generate GetPayload type for each component with populatable fields
591
736
  for (const component of schema.components) {
592
737
  if (this.hasAnyPopulatableFields(component)) {
593
- sf.addStatements(this.buildGetPayloadType(component));
738
+ sinks
739
+ .component(component)
740
+ .addStatements(this.buildGetPayloadType(component));
594
741
  }
595
742
  }
596
743
  // Generate GetPayload type for each content type with populatable fields
597
744
  for (const contentType of schema.contentTypes) {
598
745
  if (this.hasAnyPopulatableFields(contentType)) {
599
- sf.addStatements(this.buildGetPayloadType(contentType));
746
+ sinks
747
+ .contentType(contentType)
748
+ .addStatements(this.buildGetPayloadType(contentType));
600
749
  }
601
750
  }
602
751
  }