polyapi 0.25.28 → 0.26.0

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 (43) hide show
  1. package/LICENSE +1 -1
  2. package/build/api.d.ts +4 -4
  3. package/build/api.d.ts.map +1 -1
  4. package/build/api.js +3 -1
  5. package/build/api.js.map +1 -1
  6. package/build/cli.js +10 -3
  7. package/build/cli.js.map +1 -1
  8. package/build/commands/function.d.ts.map +1 -1
  9. package/build/commands/function.js +13 -3
  10. package/build/commands/function.js.map +1 -1
  11. package/build/commands/generate/index.d.ts.map +1 -1
  12. package/build/commands/generate/index.js.map +1 -1
  13. package/build/commands/generate/schemaTypes.d.ts.map +1 -1
  14. package/build/commands/generate/schemaTypes.js +8 -8
  15. package/build/commands/generate/schemaTypes.js.map +1 -1
  16. package/build/commands/generate/table.d.ts.map +1 -1
  17. package/build/commands/generate/table.js +11 -3
  18. package/build/commands/generate/table.js.map +1 -1
  19. package/build/commands/generate/types.js.map +1 -1
  20. package/build/commands/model/generate.d.ts.map +1 -1
  21. package/build/commands/model/generate.js.map +1 -1
  22. package/build/commands/prepare.d.ts.map +1 -1
  23. package/build/commands/prepare.js +9 -4
  24. package/build/commands/prepare.js.map +1 -1
  25. package/build/commands/sync.d.ts.map +1 -1
  26. package/build/commands/sync.js +5 -3
  27. package/build/commands/sync.js.map +1 -1
  28. package/build/deployables.d.ts.map +1 -1
  29. package/build/deployables.js +1 -4
  30. package/build/deployables.js.map +1 -1
  31. package/build/transpiler.d.ts +12 -2
  32. package/build/transpiler.d.ts.map +1 -1
  33. package/build/transpiler.js +246 -86
  34. package/build/transpiler.js.map +1 -1
  35. package/build/tsconfig.build.tsbuildinfo +1 -1
  36. package/build/utils.d.ts.map +1 -1
  37. package/build/utils.js +1 -1
  38. package/build/utils.js.map +1 -1
  39. package/build/version.d.ts +1 -1
  40. package/build/version.d.ts.map +1 -1
  41. package/build/version.js +12 -7
  42. package/build/version.js.map +1 -1
  43. package/package.json +1 -1
@@ -10,11 +10,11 @@ const shelljs_1 = __importDefault(require("shelljs"));
10
10
  const typescript_1 = __importDefault(require("typescript"));
11
11
  const path_1 = __importDefault(require("path"));
12
12
  const ts_json_schema_generator_1 = require("ts-json-schema-generator");
13
+ const helper_string_1 = require("@guanghechen/helper-string");
13
14
  const deployables_1 = require("./deployables");
14
15
  const utils_1 = require("./utils");
15
16
  const constants_1 = require("./constants");
16
17
  const api_1 = require("./api");
17
- const helper_string_1 = require("@guanghechen/helper-string");
18
18
  const EXCLUDED_REQUIREMENTS = [
19
19
  'assert',
20
20
  'buffer',
@@ -83,12 +83,30 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
83
83
  const getPropertyPath = (expr) => {
84
84
  const parts = [];
85
85
  let current = expr;
86
- while (typescript_1.default.isPropertyAccessExpression(current)) {
87
- parts.unshift(current.name.text);
88
- current = current.expression;
89
- }
90
- if (typescript_1.default.isIdentifier(current)) {
91
- parts.unshift(current.text);
86
+ while (true) {
87
+ if (typescript_1.default.isPropertyAccessExpression(current)) {
88
+ parts.unshift(current.name.text);
89
+ current = current.expression;
90
+ continue;
91
+ }
92
+ if (typescript_1.default.isElementAccessExpression(current)) {
93
+ const arg = current.argumentExpression;
94
+ if (arg && typescript_1.default.isStringLiteral(arg)) {
95
+ parts.unshift(arg.text);
96
+ }
97
+ else if (arg && typescript_1.default.isNumericLiteral(arg)) {
98
+ parts.unshift(arg.text);
99
+ }
100
+ else {
101
+ parts.unshift('*');
102
+ }
103
+ current = current.expression;
104
+ continue;
105
+ }
106
+ if (typescript_1.default.isIdentifier(current)) {
107
+ parts.unshift(current.text);
108
+ }
109
+ break;
92
110
  }
93
111
  return parts.join('.');
94
112
  };
@@ -125,25 +143,30 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
125
143
  return (sourceFile) => {
126
144
  const visitor = (node) => {
127
145
  if (typescript_1.default.isImportDeclaration(node)) {
128
- const moduleName = node.moduleSpecifier.text;
129
- if (!ignoreDependencies && moduleName === "polyapi" && node.importClause) {
146
+ const moduleName = node.moduleSpecifier
147
+ .text;
148
+ if (moduleName === 'polyapi' && node.importClause) {
130
149
  if (node.importClause.name) {
131
150
  polyImportIdentifier = `${node.importClause.name.text}.`;
132
151
  lookForInternalDependencies = true;
133
152
  }
134
- if (node.importClause.namedBindings && typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
135
- for (const element of node.importClause.namedBindings.elements) {
136
- const imported = element.propertyName ? element.propertyName.text : element.name.text;
153
+ if (node.importClause.namedBindings &&
154
+ typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
155
+ for (const element of node.importClause.namedBindings
156
+ .elements) {
157
+ const imported = element.propertyName
158
+ ? element.propertyName.text
159
+ : element.name.text;
137
160
  const local = element.name.text;
138
- if (imported === "vari") {
161
+ if (imported === 'vari') {
139
162
  variImportIdentifier = `${local}.`;
140
163
  lookForInternalDependencies = true;
141
164
  }
142
- else if (imported === "tabi") {
165
+ else if (imported === 'tabi') {
143
166
  tabiImportIdentifier = `${local}.`;
144
167
  lookForInternalDependencies = true;
145
168
  }
146
- else if (imported === "schemas") {
169
+ else if (imported === 'schemas') {
147
170
  schemasImportIdentifier = `${local}.`;
148
171
  lookForInternalDependencies = true;
149
172
  }
@@ -167,15 +190,20 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
167
190
  }
168
191
  return node;
169
192
  }
170
- if (!ignoreDependencies && lookForInternalDependencies) {
193
+ if (lookForInternalDependencies) {
171
194
  if (typescript_1.default.isVariableDeclaration(node) && node.initializer) {
172
195
  const initializer = unwrapExpression(node.initializer);
173
- if (typescript_1.default.isIdentifier(node.name) && typescript_1.default.isPropertyAccessExpression(initializer)) {
196
+ if (typescript_1.default.isIdentifier(node.name) &&
197
+ typescript_1.default.isPropertyAccessExpression(initializer)) {
174
198
  const path = getPropertyPath(initializer);
175
- if ((polyImportIdentifier && path.startsWith(polyImportIdentifier)) ||
176
- (variImportIdentifier && path.startsWith(variImportIdentifier)) ||
177
- (tabiImportIdentifier && path.startsWith(tabiImportIdentifier)) ||
178
- (otherImportIdentifiers.length && otherImportIdentifiers.some(other => path.startsWith(other)))) {
199
+ if ((polyImportIdentifier &&
200
+ path.startsWith(polyImportIdentifier)) ||
201
+ (variImportIdentifier &&
202
+ path.startsWith(variImportIdentifier)) ||
203
+ (tabiImportIdentifier &&
204
+ path.startsWith(tabiImportIdentifier)) ||
205
+ (otherImportIdentifiers.length &&
206
+ otherImportIdentifiers.some((other) => path.startsWith(other)))) {
179
207
  if (node.name && typescript_1.default.isIdentifier(node.name)) {
180
208
  aliasMap.set(node.name.text, path);
181
209
  return node;
@@ -203,42 +231,95 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
203
231
  const root = path.split('.')[0];
204
232
  if (aliasMap.has(root)) {
205
233
  const aliasBase = aliasMap.get(root);
206
- path = aliasBase.split(".").concat(path.split('.').slice(1)).join('.');
234
+ path = aliasBase
235
+ .split('.')
236
+ .concat(path.split('.').slice(1))
237
+ .join('.');
207
238
  }
208
- if ((polyImportIdentifier && path.startsWith(polyImportIdentifier)) ||
209
- (variImportIdentifier && path.startsWith(variImportIdentifier)) ||
210
- (tabiImportIdentifier && path.startsWith(tabiImportIdentifier)) ||
211
- (otherImportIdentifiers.length && otherImportIdentifiers.some(other => path.startsWith(other)))) {
239
+ if ((polyImportIdentifier &&
240
+ path.startsWith(polyImportIdentifier)) ||
241
+ (variImportIdentifier &&
242
+ path.startsWith(variImportIdentifier)) ||
243
+ (tabiImportIdentifier &&
244
+ path.startsWith(tabiImportIdentifier)) ||
245
+ (otherImportIdentifiers.length &&
246
+ otherImportIdentifiers.some((other) => path.startsWith(other)))) {
212
247
  aliasMap.set(localName, path);
213
248
  }
214
249
  }
215
250
  return node;
216
251
  }
217
252
  }
218
- else if (typescript_1.default.isPropertyAccessExpression(node) && !typescript_1.default.isPropertyAccessExpression(node.parent)) {
253
+ else if (typescript_1.default.isPropertyAccessExpression(node) &&
254
+ !typescript_1.default.isPropertyAccessExpression(node.parent) &&
255
+ !typescript_1.default.isElementAccessExpression(node.parent)) {
219
256
  let path = getPropertyPath(node);
220
257
  const root = path.split('.')[0];
221
258
  if (aliasMap.has(root)) {
222
259
  const aliasBase = aliasMap.get(root);
223
- path = aliasBase.split(".").concat(path.split('.').slice(1)).join('.');
260
+ path = aliasBase
261
+ .split('.')
262
+ .concat(path.split('.').slice(1))
263
+ .join('.');
224
264
  }
225
- if (polyImportIdentifier && path.startsWith(polyImportIdentifier)) {
265
+ if (polyImportIdentifier &&
266
+ path.startsWith(polyImportIdentifier)) {
226
267
  internalReferences.add(path);
227
268
  }
228
- else if (variImportIdentifier && path.startsWith(variImportIdentifier)) {
229
- internalReferences.add(path.replace(VariMethods, ''));
269
+ else if (variImportIdentifier &&
270
+ path.startsWith(variImportIdentifier)) {
271
+ if (VariMethods.test(path)) {
272
+ internalReferences.add(path.replace(VariMethods, ''));
273
+ }
230
274
  }
231
- else if (tabiImportIdentifier && path.startsWith(tabiImportIdentifier)) {
232
- internalReferences.add(path.replace(TabiMethods, ''));
275
+ else if (tabiImportIdentifier &&
276
+ path.startsWith(tabiImportIdentifier)) {
277
+ if (TabiMethods.test(path)) {
278
+ internalReferences.add(path.replace(TabiMethods, ''));
279
+ }
233
280
  }
234
281
  else if (otherImportIdentifiers.length) {
235
- const match = otherImportIdentifiers.find(other => path.startsWith(other));
282
+ const match = otherImportIdentifiers.find((other) => path.startsWith(other));
236
283
  if (match)
237
284
  internalReferences.add(path);
238
285
  }
239
286
  }
287
+ else if (typescript_1.default.isCallExpression(node)) {
288
+ const target = unwrapExpression(node.expression);
289
+ if (typescript_1.default.isPropertyAccessExpression(target) ||
290
+ typescript_1.default.isElementAccessExpression(target)) {
291
+ let path = getPropertyPath(target);
292
+ const root = path.split('.')[0];
293
+ if (aliasMap.has(root)) {
294
+ const aliasBase = aliasMap.get(root);
295
+ path = aliasBase
296
+ .split('.')
297
+ .concat(path.split('.').slice(1))
298
+ .join('.');
299
+ }
300
+ if (polyImportIdentifier &&
301
+ path.startsWith(polyImportIdentifier)) {
302
+ internalReferences.add(path);
303
+ }
304
+ else if (variImportIdentifier &&
305
+ path.startsWith(variImportIdentifier)) {
306
+ if (VariMethods.test(path)) {
307
+ internalReferences.add(path.replace(VariMethods, ''));
308
+ }
309
+ }
310
+ else if (tabiImportIdentifier &&
311
+ path.startsWith(tabiImportIdentifier)) {
312
+ if (TabiMethods.test(path)) {
313
+ internalReferences.add(path.replace(TabiMethods, ''));
314
+ }
315
+ }
316
+ else if (otherImportIdentifiers.some((other) => path.startsWith(other))) {
317
+ internalReferences.add(path);
318
+ }
319
+ }
320
+ }
240
321
  }
241
- if (!ignoreDependencies && schemasImportIdentifier && typescript_1.default.isTypeReferenceNode(node)) {
322
+ if (schemasImportIdentifier && typescript_1.default.isTypeReferenceNode(node)) {
242
323
  const path = flattenTypeName(node.typeName);
243
324
  if (path.startsWith(schemasImportIdentifier)) {
244
325
  internalReferences.add(path);
@@ -256,6 +337,7 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
256
337
  const dependencies = Array.from(importedLibraries).filter((library) => !EXCLUDED_REQUIREMENTS.includes(library));
257
338
  const externalDependencies = {};
258
339
  const internalDependencies = {};
340
+ let internalContexts = [];
259
341
  if (dependencies.length) {
260
342
  let packageJson = {};
261
343
  try {
@@ -269,7 +351,8 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
269
351
  const packageJsonDevDependencies = packageJson.devDependencies || {};
270
352
  for (const dependency of dependencies) {
271
353
  let dependencyName = dependency;
272
- let version = packageJsonDependencies[dependencyName] || packageJsonDevDependencies[dependencyName];
354
+ let version = packageJsonDependencies[dependencyName] ||
355
+ packageJsonDevDependencies[dependencyName];
273
356
  if (version) {
274
357
  externalDependencies[dependency] = version;
275
358
  continue;
@@ -278,7 +361,9 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
278
361
  while (dependencyParts.length > 0) {
279
362
  dependencyParts.pop();
280
363
  dependencyName = dependencyParts.join('/');
281
- version = packageJsonDependencies[dependencyName] || packageJsonDevDependencies[dependencyName];
364
+ version =
365
+ packageJsonDependencies[dependencyName] ||
366
+ packageJsonDevDependencies[dependencyName];
282
367
  if (version) {
283
368
  externalDependencies[dependencyName] = version;
284
369
  break;
@@ -295,54 +380,86 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
295
380
  const found = [];
296
381
  let missing = [];
297
382
  const findReferencedSpecs = (toFind) => {
298
- for (let path of toFind) {
383
+ for (const originalPath of toFind) {
299
384
  let type;
385
+ let path = originalPath;
300
386
  if (path.startsWith(polyImportIdentifier)) {
301
387
  path = path.replace(polyImportIdentifier, '');
302
388
  }
303
389
  else if (path.startsWith(variImportIdentifier)) {
304
- type = "serverVariable";
390
+ type = 'serverVariable';
305
391
  path = path.replace(variImportIdentifier, '');
306
392
  }
307
393
  else if (path.startsWith(tabiImportIdentifier)) {
308
- type = "table";
394
+ type = 'table';
309
395
  path = path.replace(tabiImportIdentifier, '');
310
396
  }
311
397
  else if (path.startsWith(schemasImportIdentifier)) {
312
- type = "schema";
398
+ type = 'schema';
313
399
  path = path.replace(schemasImportIdentifier, '');
314
400
  }
315
- const spec = specs.find(s => {
316
- if (type) {
317
- if (type !== s.type)
318
- return false;
319
- }
320
- else if (['serverVariable', 'table', 'schema'].includes(s.type))
321
- return false;
322
- if (s.type === 'schema') {
323
- return s.contextName.split('.').map(s => (0, helper_string_1.toPascalCase)(s)).join('.') === path;
401
+ if (path.includes('.*')) {
402
+ path = path.split('.*')[0];
403
+ if (internalContexts.includes('*'))
404
+ continue;
405
+ if (!path) {
406
+ internalContexts = ['*'];
324
407
  }
325
- return s.contextName.toLowerCase() === path.toLowerCase();
326
- });
327
- if (spec) {
328
- found.push(spec);
329
- let type = spec.type;
330
- const dep = { path: spec.contextName, id: spec.id };
331
- if (spec.visibilityMetadata.visibility === 'PUBLIC' &&
332
- ['apiFunction', 'customFunction', 'serverFunction'].includes(type)) {
333
- type = `public${type.substring(0, 1).toUpperCase()}${type.substring(1)}`;
334
- dep['tenantName'] = spec.visibilityMetadata.foreignTenantName;
335
- dep['environmentName'] = spec.visibilityMetadata.foreignEnvironmentName;
408
+ else {
409
+ internalContexts.push(path);
336
410
  }
337
- internalDependencies[type] = internalDependencies[type] || [];
338
- internalDependencies[type].push(dep);
339
411
  }
340
412
  else {
341
- missing.push(path);
413
+ const spec = specs.find((s) => {
414
+ if (type) {
415
+ if (type !== s.type)
416
+ return false;
417
+ }
418
+ else if (['serverVariable', 'table', 'schema'].includes(s.type))
419
+ return false;
420
+ if (s.type === 'schema') {
421
+ return (s.contextName
422
+ .split('.')
423
+ .map((s) => (0, helper_string_1.toPascalCase)(s))
424
+ .join('.') === path);
425
+ }
426
+ return s.contextName.toLowerCase() === path.toLowerCase();
427
+ });
428
+ if (spec) {
429
+ found.push(spec);
430
+ let type = spec.type;
431
+ const dep = { path: spec.contextName, id: spec.id };
432
+ if (spec.visibilityMetadata.visibility === 'PUBLIC' &&
433
+ ['apiFunction', 'customFunction', 'serverFunction'].includes(type)) {
434
+ type = `public${type
435
+ .substring(0, 1)
436
+ .toUpperCase()}${type.substring(1)}`;
437
+ dep['tenantName'] = spec.visibilityMetadata.foreignTenantName;
438
+ dep['environmentName'] =
439
+ spec.visibilityMetadata.foreignEnvironmentName;
440
+ }
441
+ internalDependencies[type] = internalDependencies[type] || [];
442
+ internalDependencies[type].push(dep);
443
+ }
444
+ else {
445
+ missing.push(path);
446
+ }
342
447
  }
343
448
  }
344
449
  };
345
450
  findReferencedSpecs(internalReferences);
451
+ if (internalContexts.length) {
452
+ internalContexts.sort();
453
+ const toKeep = [];
454
+ for (const context of internalContexts) {
455
+ if (toKeep.find((c) => context.startsWith(c)))
456
+ continue;
457
+ toKeep.push(context);
458
+ }
459
+ if (toKeep.length) {
460
+ internalDependencies.contexts = toKeep;
461
+ }
462
+ }
346
463
  if (missing.length && !fetchedSpecs) {
347
464
  specs = await (0, api_1.getSpecs)();
348
465
  (0, utils_1.writeCachedSpecs)(libPath, specs);
@@ -351,11 +468,16 @@ const getDependencies = async (code, fileName, baseUrl, ignoreDependencies) => {
351
468
  missing = [];
352
469
  findReferencedSpecs(toFind);
353
470
  }
354
- if (missing.length) {
355
- throw new Error(`Cannot resolve all poly resources referenced within function.\n\nMissing:\n${missing.map(n => ` '${n}'`).join('\n')}\n\nRerun command with '--ignore-dependencies' to skip resolving dependencies.`);
471
+ if (missing.length && !ignoreDependencies) {
472
+ throw new Error(`Cannot resolve all poly resources referenced within function.\n\nMissing:\n${missing
473
+ .map((n) => ` '${n}'`)
474
+ .join('\n')}\n\nRerun command with '--ignore-dependencies' to skip resolving dependencies.`);
356
475
  }
357
476
  }
358
- return [dependencies.length ? externalDependencies : undefined, internalReferences.size && !ignoreDependencies ? internalDependencies : undefined];
477
+ return [
478
+ dependencies.length ? externalDependencies : undefined,
479
+ internalReferences.size ? internalDependencies : undefined,
480
+ ];
359
481
  };
360
482
  exports.getDependencies = getDependencies;
361
483
  const parseDeployComment = (comment) => {
@@ -545,14 +667,23 @@ const parseDeployableFunction = async (sourceFile, polyConfig, baseUrl, fileRevi
545
667
  polyConfig.description = functionDetails.types.description || '';
546
668
  }
547
669
  const [externalDependencies, internalDependencies] = await (0, exports.getDependencies)(sourceFile.getFullText(), sourceFile.fileName, baseUrl, true);
548
- const typeSchemas = (0, exports.generateTypeSchemas)(sourceFile.fileName, deployables_1.DeployableTypeEntries.map(d => d[0]), polyConfig.name);
670
+ const referencedSchemas = internalDependencies && 'schema' in internalDependencies
671
+ ? Object.fromEntries(internalDependencies.schema.map((schema) => [
672
+ `schemas.${schema.path
673
+ .split('.')
674
+ .map((s) => (0, helper_string_1.toPascalCase)(s))
675
+ .join('.')}`,
676
+ { 'x-poly-ref': { path: schema.path } },
677
+ ]))
678
+ : null;
679
+ const typeSchemas = (0, exports.generateTypeSchemas)(sourceFile.fileName, deployables_1.DeployableTypeEntries.map((d) => d[0]), polyConfig.name, referencedSchemas);
549
680
  return {
550
681
  ...polyConfig,
551
682
  ...functionDetails,
552
683
  deployments,
553
684
  deploymentCommentRanges,
554
685
  externalDependencies,
555
- internalDependencies,
686
+ internalDependencies: null,
556
687
  typeSchemas,
557
688
  fileRevision,
558
689
  gitRevision,
@@ -593,7 +724,8 @@ const parseDeployable = async (filePath, baseUrl, gitRevision) => {
593
724
  }
594
725
  catch (e) {
595
726
  shelljs_1.default.echo(chalk_1.default.redBright(`Prepared ${polyConfig.type.replaceAll('-', ' ')} ${polyConfig.context}.${polyConfig.name}: ERROR`));
596
- shelljs_1.default.echo(chalk_1.default.red((e instanceof Error ? e.message : e.response?.data?.message) || 'Unexpected error.'));
727
+ shelljs_1.default.echo(chalk_1.default.red((e instanceof Error ? e.message : e.response?.data?.message) ||
728
+ 'Unexpected error.'));
597
729
  }
598
730
  };
599
731
  exports.parseDeployable = parseDeployable;
@@ -601,14 +733,14 @@ const dereferenceSchema = (obj, definitions, visited = new Set()) => {
601
733
  if (!obj || typeof obj !== 'object')
602
734
  return obj;
603
735
  if (Array.isArray(obj)) {
604
- return obj.map(item => dereferenceSchema(item, definitions, visited));
736
+ return obj.map((item) => dereferenceSchema(item, definitions, visited));
605
737
  }
606
738
  const result = {};
607
739
  for (const [key, value] of Object.entries(obj)) {
608
740
  if (key === '$ref' && typeof value === 'string') {
609
741
  const match = value.match(/^#\/definitions\/(.+)$/);
610
742
  if (match) {
611
- const defName = match[1];
743
+ const defName = decodeURIComponent(match[1]);
612
744
  if (visited.has(defName)) {
613
745
  return { $ref: value };
614
746
  }
@@ -637,12 +769,15 @@ const dereferenceSchema = (obj, definitions, visited = new Set()) => {
637
769
  };
638
770
  const isInlineableDefinition = (definition, defName) => {
639
771
  const decodedDefName = decodeURIComponent(defName);
640
- if (definition.type === 'object' && definition.properties &&
772
+ if (definition.type === 'object' &&
773
+ definition.properties &&
641
774
  Object.keys(definition.properties).length > 0) {
642
775
  return true;
643
776
  }
644
- if (definition.type === 'array' && definition.items &&
645
- typeof definition.items === 'object' && definition.items.type) {
777
+ if (definition.type === 'array' &&
778
+ definition.items &&
779
+ typeof definition.items === 'object' &&
780
+ definition.items.type) {
646
781
  return true;
647
782
  }
648
783
  if (['string', 'number', 'boolean', 'integer'].includes(definition.type)) {
@@ -654,8 +789,10 @@ const isInlineableDefinition = (definition, defName) => {
654
789
  if ((definition.anyOf || definition.allOf) && !decodedDefName.includes('<')) {
655
790
  return true;
656
791
  }
657
- if (decodedDefName.includes('<') || decodedDefName.includes('>') ||
658
- decodedDefName.includes('|') || decodedDefName.includes('&')) {
792
+ if (decodedDefName.includes('<') ||
793
+ decodedDefName.includes('>') ||
794
+ decodedDefName.includes('|') ||
795
+ decodedDefName.includes('&')) {
659
796
  return false;
660
797
  }
661
798
  return !/[<>%|&]/.test(decodedDefName);
@@ -667,7 +804,7 @@ const dereferenceRoot = (schema) => {
667
804
  if (schema.$ref) {
668
805
  const match = schema.$ref.match(/^#\/definitions\/(.+)$/);
669
806
  if (match) {
670
- const defName = match[1];
807
+ const defName = decodeURIComponent(match[1]);
671
808
  const root = schema.definitions[defName];
672
809
  if (root) {
673
810
  const { definitions, $schema, $ref, ...rest } = schema;
@@ -687,7 +824,7 @@ const dereferenceRoot = (schema) => {
687
824
  if (!obj || typeof obj !== 'object')
688
825
  return;
689
826
  if (Array.isArray(obj)) {
690
- obj.forEach(item => findReferences(item, visited));
827
+ obj.forEach((item) => findReferences(item, visited));
691
828
  return;
692
829
  }
693
830
  for (const [key, value] of Object.entries(obj)) {
@@ -696,8 +833,11 @@ const dereferenceRoot = (schema) => {
696
833
  if (match) {
697
834
  const encodedDefName = match[1];
698
835
  const decodedDefName = decodeURIComponent(encodedDefName);
699
- const actualDefName = definitions[encodedDefName] ? encodedDefName :
700
- definitions[decodedDefName] ? decodedDefName : null;
836
+ const actualDefName = definitions[encodedDefName]
837
+ ? encodedDefName
838
+ : definitions[decodedDefName]
839
+ ? decodedDefName
840
+ : null;
701
841
  if (actualDefName && !visited.has(actualDefName)) {
702
842
  visited.add(actualDefName);
703
843
  filteredDefinitions[actualDefName] = definitions[actualDefName];
@@ -713,7 +853,9 @@ const dereferenceRoot = (schema) => {
713
853
  findReferences(dereferencedRest);
714
854
  return {
715
855
  ...dereferencedRest,
716
- ...(Object.keys(filteredDefinitions).length > 0 && { definitions: filteredDefinitions }),
856
+ ...(Object.keys(filteredDefinitions).length > 0 && {
857
+ definitions: filteredDefinitions,
858
+ }),
717
859
  $schema,
718
860
  };
719
861
  };
@@ -729,7 +871,20 @@ const extractTypesFromAST = (filePath, functionName) => {
729
871
  const extractFromTypeNode = (typeNode) => {
730
872
  if (typescript_1.default.isTypeReferenceNode(typeNode)) {
731
873
  const typeName = typeNode.typeName.getText(sourceFile);
732
- const primitives = ['Promise', 'Array', 'Record', 'string', 'number', 'boolean', 'void', 'any', 'unknown', 'object', 'undefined', 'null'];
874
+ const primitives = [
875
+ 'Promise',
876
+ 'Array',
877
+ 'Record',
878
+ 'string',
879
+ 'number',
880
+ 'boolean',
881
+ 'void',
882
+ 'any',
883
+ 'unknown',
884
+ 'object',
885
+ 'undefined',
886
+ 'null',
887
+ ];
733
888
  if (!primitives.includes(typeName)) {
734
889
  extractedTypes.add(typeName);
735
890
  }
@@ -739,7 +894,8 @@ const extractTypesFromAST = (filePath, functionName) => {
739
894
  }
740
895
  }
741
896
  }
742
- else if (typescript_1.default.isUnionTypeNode(typeNode) || typescript_1.default.isIntersectionTypeNode(typeNode)) {
897
+ else if (typescript_1.default.isUnionTypeNode(typeNode) ||
898
+ typescript_1.default.isIntersectionTypeNode(typeNode)) {
743
899
  for (const type of typeNode.types) {
744
900
  extractFromTypeNode(type);
745
901
  }
@@ -762,15 +918,19 @@ const extractTypesFromAST = (filePath, functionName) => {
762
918
  return Array.from(extractedTypes);
763
919
  };
764
920
  exports.extractTypesFromAST = extractTypesFromAST;
765
- const generateTypeSchemas = (filePath, ignoredTypeNames = [], functionName) => {
921
+ const generateTypeSchemas = (filePath, ignoredTypeNames = [], functionName, referencedSchemas = null) => {
766
922
  const tsconfigPath = path_1.default.resolve('tsconfig.json');
767
923
  const actualFunctionName = functionName || path_1.default.basename(filePath, '.ts');
768
924
  const extractedTypes = (0, exports.extractTypesFromAST)(filePath, actualFunctionName);
769
- const typeNames = extractedTypes.filter(typeName => !ignoredTypeNames.includes(typeName));
925
+ const typeNames = extractedTypes.filter((typeName) => !ignoredTypeNames.includes(typeName));
770
926
  const output = {};
771
927
  for (const typeName of typeNames) {
772
928
  if (ignoredTypeNames.includes(typeName))
773
929
  continue;
930
+ if (referencedSchemas?.[typeName]) {
931
+ output[typeName] = referencedSchemas[typeName];
932
+ continue;
933
+ }
774
934
  try {
775
935
  const generator = (0, ts_json_schema_generator_1.createGenerator)({
776
936
  path: filePath,