@jutsustack/api-codegen 0.1.0 → 0.2.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 (199) hide show
  1. package/README.md +574 -141
  2. package/dist/cache/manifest.d.ts +0 -1
  3. package/dist/cache/manifest.d.ts.map +1 -1
  4. package/dist/cache/manifest.js +1 -1
  5. package/dist/cache/manifest.js.map +1 -1
  6. package/dist/cjs/cache/manifest.d.ts +34 -0
  7. package/dist/cjs/cache/manifest.js +45 -0
  8. package/dist/cjs/cli.d.ts +8 -0
  9. package/dist/cjs/cli.js +245 -0
  10. package/dist/cjs/codegen/emit-api.d.ts +6 -0
  11. package/dist/cjs/codegen/emit-api.js +108 -0
  12. package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
  13. package/dist/cjs/codegen/emit-bindings.js +115 -0
  14. package/dist/cjs/codegen/emit-types.d.ts +10 -0
  15. package/dist/cjs/codegen/emit-types.js +232 -0
  16. package/dist/cjs/codegen/emit.d.ts +28 -0
  17. package/dist/cjs/codegen/emit.js +180 -0
  18. package/dist/cjs/codegen/files.d.ts +14 -0
  19. package/dist/cjs/codegen/files.js +66 -0
  20. package/dist/cjs/codegen/plan.d.ts +32 -0
  21. package/dist/cjs/codegen/plan.js +84 -0
  22. package/dist/cjs/codegen/print.d.ts +10 -0
  23. package/dist/cjs/codegen/print.js +65 -0
  24. package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
  25. package/dist/cjs/codegen/templates/bindings.js +707 -0
  26. package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
  27. package/dist/cjs/codegen/templates/runtime.js +1401 -0
  28. package/dist/cjs/codegen/templates/transports.d.ts +1 -0
  29. package/dist/cjs/codegen/templates/transports.js +272 -0
  30. package/dist/cjs/codegen/tsType.d.ts +15 -0
  31. package/dist/cjs/codegen/tsType.js +114 -0
  32. package/dist/cjs/collect/collect.d.ts +16 -0
  33. package/dist/cjs/collect/collect.js +472 -0
  34. package/dist/cjs/collect/naming.d.ts +25 -0
  35. package/dist/cjs/collect/naming.js +149 -0
  36. package/dist/cjs/collect/path.d.ts +10 -0
  37. package/dist/cjs/collect/path.js +67 -0
  38. package/dist/cjs/config/init.d.ts +37 -0
  39. package/dist/cjs/config/init.js +143 -0
  40. package/dist/cjs/config/load.d.ts +11 -0
  41. package/dist/cjs/config/load.js +121 -0
  42. package/dist/cjs/config/types.d.ts +88 -0
  43. package/dist/cjs/config/types.js +2 -0
  44. package/dist/cjs/config/validate.d.ts +8 -0
  45. package/dist/cjs/config/validate.js +200 -0
  46. package/dist/cjs/generate.d.ts +55 -0
  47. package/dist/cjs/generate.js +263 -0
  48. package/dist/cjs/index.d.ts +23 -0
  49. package/dist/cjs/index.js +48 -0
  50. package/dist/cjs/model/collection.d.ts +83 -0
  51. package/dist/cjs/model/collection.js +16 -0
  52. package/dist/cjs/model/infer.d.ts +7 -0
  53. package/dist/cjs/model/infer.js +95 -0
  54. package/dist/cjs/model/merge.d.ts +3 -0
  55. package/dist/cjs/model/merge.js +131 -0
  56. package/dist/cjs/model/reserved.d.ts +2 -0
  57. package/dist/cjs/model/reserved.js +128 -0
  58. package/dist/cjs/model/schema.d.ts +54 -0
  59. package/dist/cjs/model/schema.js +2 -0
  60. package/dist/cjs/package.json +1 -0
  61. package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
  62. package/dist/cjs/parsers/openapi-schema.js +241 -0
  63. package/dist/cjs/parsers/openapi.d.ts +8 -0
  64. package/dist/cjs/parsers/openapi.js +435 -0
  65. package/dist/cjs/parsers/postman.d.ts +20 -0
  66. package/dist/cjs/parsers/postman.js +493 -0
  67. package/dist/cjs/parsers/types.d.ts +52 -0
  68. package/dist/cjs/parsers/types.js +2 -0
  69. package/dist/cjs/sources/load.d.ts +25 -0
  70. package/dist/cjs/sources/load.js +296 -0
  71. package/dist/cjs/sources/parse.d.ts +4 -0
  72. package/dist/cjs/sources/parse.js +50 -0
  73. package/dist/cjs/util/errors.d.ts +9 -0
  74. package/dist/cjs/util/errors.js +23 -0
  75. package/dist/cjs/util/fs.d.ts +7 -0
  76. package/dist/cjs/util/fs.js +44 -0
  77. package/dist/cjs/util/hash.d.ts +3 -0
  78. package/dist/cjs/util/hash.js +26 -0
  79. package/dist/cjs/util/json.d.ts +10 -0
  80. package/dist/cjs/util/json.js +31 -0
  81. package/dist/cjs/util/log.d.ts +22 -0
  82. package/dist/cjs/util/log.js +45 -0
  83. package/dist/cjs/version.d.ts +2 -0
  84. package/dist/cjs/version.js +6 -0
  85. package/dist/cli.d.ts +3 -1
  86. package/dist/cli.d.ts.map +1 -1
  87. package/dist/cli.js +42 -12
  88. package/dist/cli.js.map +1 -1
  89. package/dist/codegen/emit-api.d.ts +3 -1
  90. package/dist/codegen/emit-api.d.ts.map +1 -1
  91. package/dist/codegen/emit-api.js +32 -7
  92. package/dist/codegen/emit-api.js.map +1 -1
  93. package/dist/codegen/emit-bindings.d.ts +9 -0
  94. package/dist/codegen/emit-bindings.d.ts.map +1 -0
  95. package/dist/codegen/emit-bindings.js +112 -0
  96. package/dist/codegen/emit-bindings.js.map +1 -0
  97. package/dist/codegen/emit-types.d.ts +8 -1
  98. package/dist/codegen/emit-types.d.ts.map +1 -1
  99. package/dist/codegen/emit-types.js +10 -8
  100. package/dist/codegen/emit-types.js.map +1 -1
  101. package/dist/codegen/emit.d.ts +10 -1
  102. package/dist/codegen/emit.d.ts.map +1 -1
  103. package/dist/codegen/emit.js +142 -37
  104. package/dist/codegen/emit.js.map +1 -1
  105. package/dist/codegen/files.d.ts +3 -12
  106. package/dist/codegen/files.d.ts.map +1 -1
  107. package/dist/codegen/files.js +3 -12
  108. package/dist/codegen/files.js.map +1 -1
  109. package/dist/codegen/print.d.ts +1 -4
  110. package/dist/codegen/print.d.ts.map +1 -1
  111. package/dist/codegen/print.js +1 -4
  112. package/dist/codegen/print.js.map +1 -1
  113. package/dist/codegen/templates/bindings.d.ts +14 -0
  114. package/dist/codegen/templates/bindings.d.ts.map +1 -0
  115. package/dist/codegen/templates/bindings.js +705 -0
  116. package/dist/codegen/templates/bindings.js.map +1 -0
  117. package/dist/codegen/templates/runtime.d.ts +2 -1
  118. package/dist/codegen/templates/runtime.d.ts.map +1 -1
  119. package/dist/codegen/templates/runtime.js +1192 -279
  120. package/dist/codegen/templates/runtime.js.map +1 -1
  121. package/dist/codegen/templates/transports.d.ts +2 -0
  122. package/dist/codegen/templates/transports.d.ts.map +1 -0
  123. package/dist/codegen/templates/transports.js +270 -0
  124. package/dist/codegen/templates/transports.js.map +1 -0
  125. package/dist/collect/collect.d.ts +1 -11
  126. package/dist/collect/collect.d.ts.map +1 -1
  127. package/dist/collect/collect.js +21 -28
  128. package/dist/collect/collect.js.map +1 -1
  129. package/dist/collect/naming.d.ts +1 -4
  130. package/dist/collect/naming.d.ts.map +1 -1
  131. package/dist/collect/naming.js +1 -4
  132. package/dist/collect/naming.js.map +1 -1
  133. package/dist/collect/path.d.ts +2 -9
  134. package/dist/collect/path.d.ts.map +1 -1
  135. package/dist/collect/path.js +2 -9
  136. package/dist/collect/path.js.map +1 -1
  137. package/dist/config/init.d.ts +11 -2
  138. package/dist/config/init.d.ts.map +1 -1
  139. package/dist/config/init.js +55 -7
  140. package/dist/config/init.js.map +1 -1
  141. package/dist/config/load.d.ts.map +1 -1
  142. package/dist/config/load.js +26 -1
  143. package/dist/config/load.js.map +1 -1
  144. package/dist/config/types.d.ts +13 -5
  145. package/dist/config/types.d.ts.map +1 -1
  146. package/dist/config/validate.d.ts +2 -6
  147. package/dist/config/validate.d.ts.map +1 -1
  148. package/dist/config/validate.js +18 -7
  149. package/dist/config/validate.js.map +1 -1
  150. package/dist/generate.d.ts +2 -8
  151. package/dist/generate.d.ts.map +1 -1
  152. package/dist/generate.js +13 -12
  153. package/dist/generate.js.map +1 -1
  154. package/dist/index.d.ts +4 -4
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +4 -4
  157. package/dist/index.js.map +1 -1
  158. package/dist/model/infer.d.ts +2 -9
  159. package/dist/model/infer.d.ts.map +1 -1
  160. package/dist/model/infer.js +2 -9
  161. package/dist/model/infer.js.map +1 -1
  162. package/dist/model/merge.d.ts +1 -5
  163. package/dist/model/merge.d.ts.map +1 -1
  164. package/dist/model/merge.js +1 -5
  165. package/dist/model/merge.js.map +1 -1
  166. package/dist/model/reserved.d.ts +1 -4
  167. package/dist/model/reserved.d.ts.map +1 -1
  168. package/dist/model/reserved.js +63 -4
  169. package/dist/model/reserved.js.map +1 -1
  170. package/dist/model/schema.d.ts +1 -4
  171. package/dist/model/schema.d.ts.map +1 -1
  172. package/dist/parsers/openapi-schema.d.ts +1 -5
  173. package/dist/parsers/openapi-schema.d.ts.map +1 -1
  174. package/dist/parsers/openapi-schema.js +2 -5
  175. package/dist/parsers/openapi-schema.js.map +1 -1
  176. package/dist/parsers/postman.d.ts +0 -3
  177. package/dist/parsers/postman.d.ts.map +1 -1
  178. package/dist/parsers/postman.js +2 -5
  179. package/dist/parsers/postman.js.map +1 -1
  180. package/dist/sources/load.d.ts +0 -6
  181. package/dist/sources/load.d.ts.map +1 -1
  182. package/dist/sources/load.js +4 -7
  183. package/dist/sources/load.js.map +1 -1
  184. package/dist/sources/parse.d.ts +0 -2
  185. package/dist/sources/parse.d.ts.map +1 -1
  186. package/dist/sources/parse.js +1 -1
  187. package/dist/sources/parse.js.map +1 -1
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/package.json +40 -12
  191. package/schema/config.schema.json +58 -12
  192. package/dist/codegen/emit-hooks.d.ts +0 -5
  193. package/dist/codegen/emit-hooks.d.ts.map +0 -1
  194. package/dist/codegen/emit-hooks.js +0 -67
  195. package/dist/codegen/emit-hooks.js.map +0 -1
  196. package/dist/codegen/templates/hooks.d.ts +0 -11
  197. package/dist/codegen/templates/hooks.d.ts.map +0 -1
  198. package/dist/codegen/templates/hooks.js +0 -272
  199. package/dist/codegen/templates/hooks.js.map +0 -1
@@ -0,0 +1,472 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildCollection = buildCollection;
4
+ exports.globToRegExp = globToRegExp;
5
+ const merge_js_1 = require("../model/merge.js");
6
+ const reserved_js_1 = require("../model/reserved.js");
7
+ const hash_js_1 = require("../util/hash.js");
8
+ const version_js_1 = require("../version.js");
9
+ const naming_js_1 = require("./naming.js");
10
+ const path_js_1 = require("./path.js");
11
+ /** Type names whose binding wrapper (useX, injectX, createX) would shadow a bindings import. */
12
+ const HOOK_NAME_CLASHES = [
13
+ 'Api',
14
+ 'ApiContext',
15
+ 'ApiMutation',
16
+ 'ApiPlugin',
17
+ 'ApiQuery',
18
+ 'Callback',
19
+ 'Client',
20
+ 'Component',
21
+ 'Context',
22
+ 'Effect',
23
+ 'Memo',
24
+ 'Mutation',
25
+ 'MutationController',
26
+ 'PendingRequests',
27
+ 'QueryController',
28
+ 'Ref',
29
+ 'Request',
30
+ 'Signal',
31
+ 'State',
32
+ 'SyncExternalStore',
33
+ ];
34
+ /** Suffixes appended to an operation's type name; all must be free for a name to be taken. */
35
+ const TYPE_SUFFIXES = [
36
+ 'Args',
37
+ 'Params',
38
+ 'Query',
39
+ 'Body',
40
+ 'Fields',
41
+ 'Response',
42
+ 'Errors',
43
+ 'DefaultError',
44
+ ];
45
+ /** Merges parsed sources into one {@link ApiCollection} with stable, unique names. */
46
+ function buildCollection(sources, options) {
47
+ const warnings = sources.flatMap((s) => s.warnings);
48
+ const models = mergeModels(sources, warnings);
49
+ const merged = [...bucketBySameApi(sources, options)].map(([key, ops]) => mergeOperations(key, ops, options.groupBy ?? 'folder', warnings));
50
+ stringifyObjectQueries(merged, models, warnings);
51
+ return {
52
+ format: 'jutsu-api-collection',
53
+ version: 1,
54
+ generator: `${version_js_1.PACKAGE_NAME}@${version_js_1.VERSION}`,
55
+ project: options.project,
56
+ servers: [...new Set(sources.flatMap((s) => s.servers))],
57
+ sources: sources.map((s) => summarize(s, options.hashes?.[s.id] ?? '')),
58
+ models,
59
+ groups: nameAndGroup(merged, models),
60
+ warnings,
61
+ };
62
+ }
63
+ /** Requests that are the same API share a key; buckets keep first-seen order. */
64
+ function bucketBySameApi(sources, options) {
65
+ const methods = new Set(options.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
66
+ const include = (options.include ?? []).map(globToRegExp);
67
+ const exclude = (options.exclude ?? []).map(globToRegExp);
68
+ const buckets = new Map();
69
+ for (const op of sources.flatMap((s) => s.operations)) {
70
+ if (!methods.has(op.method))
71
+ continue;
72
+ const display = displayPath(op.segments);
73
+ const matches = (re) => re.test(display) || re.test(`${op.method} ${display}`);
74
+ if ((include.length && !include.some(matches)) || exclude.some(matches))
75
+ continue;
76
+ const key = (0, path_js_1.operationKey)(op.method, op.segments);
77
+ const bucket = buckets.get(key);
78
+ if (bucket)
79
+ bucket.push(op);
80
+ else
81
+ buckets.set(key, [op]);
82
+ }
83
+ return buckets;
84
+ }
85
+ /** Object query values are not serialised, so they must not be typed as objects. */
86
+ function stringifyObjectQueries(merged, models, warnings) {
87
+ for (const { op } of merged) {
88
+ for (const param of op.query) {
89
+ const target = param.schema.type === 'ref' ? models[param.schema.name] : param.schema;
90
+ if (target?.type !== 'object')
91
+ continue;
92
+ param.schema = {
93
+ type: 'string',
94
+ description: `${param.description ? `${param.description} ` : ''}(object value: serialise it yourself, e.g. JSON)`,
95
+ };
96
+ warnings.push(`${op.key}: query param "${param.wireName}" is an object; typed as string, serialise it before calling`);
97
+ }
98
+ }
99
+ }
100
+ /** Unique group keys, endpoint names unique per group, type names unique overall. */
101
+ function nameAndGroup(merged, models) {
102
+ const groupKeys = new naming_js_1.NameRegistry(['default']);
103
+ const groups = new Map();
104
+ const typeNames = new naming_js_1.NameRegistry([
105
+ ...reserved_js_1.RESERVED_TYPE_NAMES,
106
+ ...Object.keys(models),
107
+ ]);
108
+ for (const { op, groupName, nameHint } of merged) {
109
+ let entry = groups.get(groupName);
110
+ if (!entry) {
111
+ const key = groupKeys.claim([(0, naming_js_1.toIdentifier)(groupName, 'api')]);
112
+ entry = {
113
+ group: { key, name: groupName, operations: [] },
114
+ names: new naming_js_1.NameRegistry(['raw']),
115
+ };
116
+ groups.set(groupName, entry);
117
+ }
118
+ op.name = entry.names.claim([
119
+ (0, naming_js_1.toIdentifier)(nameHint, 'call'),
120
+ (0, naming_js_1.toIdentifier)(`${op.method} ${nameHint}`, 'call'),
121
+ ]);
122
+ op.typeName = claimTypeName(typeNames, op.name, entry.group.key);
123
+ entry.group.operations.push(op);
124
+ }
125
+ return [...groups.values()].map((e) => e.group);
126
+ }
127
+ function claimTypeName(registry, name, groupKey) {
128
+ const base = (0, naming_js_1.toTypeName)(name, 'Call');
129
+ const candidates = [base, (0, naming_js_1.toTypeName)(`${groupKey} ${name}`, 'Call')].filter((c) => !HOOK_NAME_CLASHES.includes(c));
130
+ return registry.claim(candidates.length ? candidates : [`${base}Call`], TYPE_SUFFIXES);
131
+ }
132
+ function summarize(source, hash) {
133
+ const summary = {
134
+ id: source.id,
135
+ kind: source.kind,
136
+ hash,
137
+ operations: source.operations.length,
138
+ };
139
+ if (source.title)
140
+ summary.title = source.title;
141
+ if (source.version)
142
+ summary.version = source.version;
143
+ return summary;
144
+ }
145
+ function mergeOperations(key, ops, groupBy, warnings) {
146
+ // spec (OpenAPI) operations first: they are authoritative
147
+ const ordered = [
148
+ ...ops.filter((o) => o.authority === 'spec'),
149
+ ...ops.filter((o) => o.authority === 'example'),
150
+ ];
151
+ const primary = ordered[0];
152
+ const specs = ordered.filter((o) => o.authority === 'spec');
153
+ const examples = ordered.filter((o) => o.authority === 'example');
154
+ // ── path ──
155
+ const segments = mergeSegments(ordered);
156
+ const pathParams = [];
157
+ const paramNames = new naming_js_1.NameRegistry();
158
+ let path = '';
159
+ for (const seg of segments) {
160
+ if (seg.kind === 'literal') {
161
+ path += '/' + encodePathLiteral(seg.value);
162
+ continue;
163
+ }
164
+ const name = paramNames.claim([(0, naming_js_1.toIdentifier)(seg.name, 'param')]);
165
+ path += '/:' + name;
166
+ const param = {
167
+ name,
168
+ wireName: seg.name,
169
+ required: true,
170
+ schema: seg.schema ?? { type: 'string' },
171
+ };
172
+ if (seg.description)
173
+ param.description = seg.description;
174
+ pathParams.push(param);
175
+ }
176
+ const op = {
177
+ key,
178
+ name: '',
179
+ typeName: '',
180
+ method: primary.method,
181
+ path: path || '/',
182
+ pathParams,
183
+ query: mergeParams(specs, examples, (o) => o.query),
184
+ headers: mergeParams(specs, examples, (o) => o.headers),
185
+ responses: mergeResponses(specs, examples),
186
+ auth: mergeAuth(specs, examples),
187
+ origins: ordered.map((o) => o.origin),
188
+ };
189
+ const body = mergeBody(specs, examples, key, warnings);
190
+ if (body)
191
+ op.body = body;
192
+ const summary = specs.find((o) => o.summary)?.summary ??
193
+ (examples[0]?.name ? (0, naming_js_1.cleanTitle)(examples[0].name) : undefined);
194
+ if (summary)
195
+ op.summary = summary;
196
+ const description = ordered.find((o) => o.description)?.description;
197
+ if (description)
198
+ op.description = description;
199
+ if (specs.some((o) => o.deprecated))
200
+ op.deprecated = true;
201
+ return {
202
+ op,
203
+ groupName: groupName(ordered, segments, groupBy),
204
+ nameHint: nameHint(specs, examples, primary.method, segments),
205
+ };
206
+ }
207
+ /** Per position, prefer the spec's param name, then an explicit Postman name, then an inferred one. */
208
+ function mergeSegments(ops) {
209
+ const base = ops[0].segments.map((s) => ({ ...s }));
210
+ for (let i = 0; i < base.length; i++) {
211
+ const seg = base[i];
212
+ if (seg.kind !== 'param')
213
+ continue;
214
+ const candidates = ops
215
+ .map((o) => o.segments[i])
216
+ .filter((s) => s?.kind === 'param');
217
+ const best = candidates.find((s) => s.explicit) ?? seg;
218
+ const merged = {
219
+ kind: 'param',
220
+ name: best.name,
221
+ explicit: best.explicit,
222
+ };
223
+ const schema = candidates.find((s) => s.schema)?.schema;
224
+ if (schema)
225
+ merged.schema = schema;
226
+ const description = candidates.find((s) => s.description)?.description;
227
+ if (description)
228
+ merged.description = description;
229
+ base[i] = merged;
230
+ }
231
+ return base;
232
+ }
233
+ function mergeParams(specs, examples, pick) {
234
+ const out = new Map();
235
+ const fromSpec = new Set();
236
+ for (const op of specs) {
237
+ for (const p of pick(op)) {
238
+ if (out.has(p.wireName))
239
+ continue;
240
+ fromSpec.add(p.wireName);
241
+ out.set(p.wireName, toParam(p));
242
+ }
243
+ }
244
+ for (const op of examples) {
245
+ for (const p of pick(op)) {
246
+ const prev = out.get(p.wireName);
247
+ if (!prev) {
248
+ // a value seen in one Postman example is not proof the API requires it
249
+ out.set(p.wireName, { ...toParam(p), required: false });
250
+ }
251
+ else if (!fromSpec.has(p.wireName)) {
252
+ prev.schema = (0, merge_js_1.mergeSchemas)(prev.schema, p.schema);
253
+ if (!prev.description && p.description)
254
+ prev.description = p.description;
255
+ }
256
+ }
257
+ }
258
+ const names = new naming_js_1.NameRegistry();
259
+ for (const p of out.values())
260
+ p.name = names.claim([(0, naming_js_1.toIdentifier)(p.wireName, 'param')]);
261
+ return [...out.values()];
262
+ }
263
+ function toParam(p) {
264
+ const param = {
265
+ name: p.wireName,
266
+ wireName: p.wireName,
267
+ required: p.required,
268
+ schema: p.schema,
269
+ };
270
+ if (p.description)
271
+ param.description = p.description;
272
+ return param;
273
+ }
274
+ function mergeBody(specs, examples, key, warnings) {
275
+ const specBody = specs.find((o) => o.body)?.body;
276
+ if (specBody)
277
+ return specBody;
278
+ let body;
279
+ for (const op of examples) {
280
+ if (!op.body)
281
+ continue;
282
+ if (!body) {
283
+ body = { ...op.body };
284
+ }
285
+ else if (body.kind !== op.body.kind) {
286
+ warnings.push(`${key}: examples send different body kinds (${body.kind}, ${op.body.kind}); using ${body.kind}`);
287
+ }
288
+ else {
289
+ body.schema = (0, merge_js_1.mergeSchemas)(body.schema, op.body.schema);
290
+ }
291
+ }
292
+ // an example that sends no body for the same API means the body is optional
293
+ if (body && examples.some((o) => !o.body))
294
+ body.required = false;
295
+ return body;
296
+ }
297
+ function mergeResponses(specs, examples) {
298
+ const keyOf = (r) => `${r.status}${r.range ? 'XX' : ''}`;
299
+ const out = new Map();
300
+ for (const op of specs)
301
+ for (const r of op.responses)
302
+ if (!out.has(keyOf(r)))
303
+ out.set(keyOf(r), { ...r });
304
+ const specStatuses = new Set(out.keys());
305
+ for (const op of examples) {
306
+ for (const r of op.responses) {
307
+ const key = keyOf(r);
308
+ if (specStatuses.has(key))
309
+ continue;
310
+ const prev = out.get(key);
311
+ if (!prev) {
312
+ out.set(key, { ...r });
313
+ continue;
314
+ }
315
+ if (prev.kind === 'empty')
316
+ prev.kind = r.kind;
317
+ if (prev.schema && r.schema)
318
+ prev.schema = (0, merge_js_1.mergeSchemas)(prev.schema, r.schema);
319
+ else if (r.schema)
320
+ prev.schema = r.schema;
321
+ }
322
+ }
323
+ return [...out.values()].sort((a, b) => statusOrder(a) - statusOrder(b));
324
+ }
325
+ const statusOrder = (r) => r.status === 'default' ? 1000 : r.status + (r.range ? 99.5 : 0);
326
+ function mergeAuth(specs, examples) {
327
+ if (specs.length)
328
+ return specs[0].auth;
329
+ return examples.length > 0 && examples.every((o) => o.auth === 'none')
330
+ ? 'none'
331
+ : 'inherit';
332
+ }
333
+ function groupName(ops, segments, groupBy) {
334
+ if (groupBy === 'none')
335
+ return 'api';
336
+ if (groupBy !== 'path') {
337
+ const named = ops.find((o) => o.group)?.group;
338
+ if (named && (0, naming_js_1.camelCase)(named))
339
+ return named;
340
+ }
341
+ const first = segments.find((s) => s.kind === 'literal' &&
342
+ !/^v\d+(\.\d+)*$/i.test(s.value) &&
343
+ !/^api$/i.test(s.value) &&
344
+ (0, naming_js_1.camelCase)(s.value) !== '');
345
+ return first ? first.value : 'api';
346
+ }
347
+ /** operationId, else the most common (then shortest) Postman title, else METHOD + path. */
348
+ function nameHint(specs, examples, method, segments) {
349
+ const operationId = specs.find((o) => o.name && (0, naming_js_1.camelCase)(o.name))?.name;
350
+ if (operationId)
351
+ return operationId;
352
+ const counts = new Map();
353
+ examples.forEach((o, order) => {
354
+ if (!o.name)
355
+ return;
356
+ const title = (0, naming_js_1.cleanTitle)(o.name);
357
+ const id = (0, naming_js_1.camelCase)(title);
358
+ if (!id)
359
+ return;
360
+ const entry = counts.get(id);
361
+ if (entry)
362
+ entry.count++;
363
+ else
364
+ counts.set(id, { title, count: 1, order });
365
+ });
366
+ const best = [...counts.values()].sort((a, b) => b.count - a.count || a.title.length - b.title.length || a.order - b.order)[0];
367
+ return best ? best.title : (0, naming_js_1.nameFromPath)(method, segments);
368
+ }
369
+ function displayPath(segments) {
370
+ return ('/' +
371
+ segments.map((s) => (s.kind === 'param' ? `:${s.name}` : s.value)).join('/'));
372
+ }
373
+ function encodePathLiteral(value) {
374
+ return encodeURIComponent(value)
375
+ .replace(/%3A/gi, ':')
376
+ .replace(/%40/g, '@')
377
+ .replace(/%2C/gi, ',');
378
+ }
379
+ /** `/users/**`, `GET /users/*`, `**\/internal/**` → RegExp over `METHOD /path` or `/path`. */
380
+ function globToRegExp(glob) {
381
+ let re = '';
382
+ for (let i = 0; i < glob.length; i++) {
383
+ const ch = glob[i];
384
+ if (ch === '*' && glob[i + 1] === '*') {
385
+ re += '.*';
386
+ i++;
387
+ }
388
+ else if (ch === '*') {
389
+ re += '[^/]*';
390
+ }
391
+ else {
392
+ re += ch.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
393
+ }
394
+ }
395
+ return new RegExp(`^${re}$`, 'i');
396
+ }
397
+ /** One model namespace: identical models are shared, clashing ones become `<SourceId><Name>`. */
398
+ function mergeModels(sources, warnings) {
399
+ const models = {};
400
+ const registry = new naming_js_1.NameRegistry(reserved_js_1.RESERVED_TYPE_NAMES);
401
+ for (const source of sources) {
402
+ const renames = new Map();
403
+ const conflicts = [];
404
+ // register every name this source keeps before renaming, so a rename can never take
405
+ // the name of one of the source's own models
406
+ for (const [name, schema] of Object.entries(source.models)) {
407
+ const existing = models[name];
408
+ if (existing === undefined)
409
+ registry.add(name);
410
+ else if ((0, hash_js_1.stableStringify)(existing) !== (0, hash_js_1.stableStringify)(schema))
411
+ conflicts.push(name);
412
+ }
413
+ for (const name of conflicts) {
414
+ const renamed = registry.claim([
415
+ `${(0, naming_js_1.toTypeName)(source.id, 'Source')}${name}`,
416
+ ]);
417
+ renames.set(name, renamed);
418
+ warnings.push(`model "${name}" from source "${source.id}" differs from an earlier one; renamed to "${renamed}"`);
419
+ }
420
+ const rewrite = (s) => (renames.size ? renameRefs(s, renames) : s);
421
+ for (const [name, schema] of Object.entries(source.models)) {
422
+ const target = renames.get(name) ?? name;
423
+ if (!(target in models))
424
+ models[target] = rewrite(schema);
425
+ }
426
+ if (renames.size) {
427
+ for (const op of source.operations) {
428
+ if (op.body)
429
+ op.body = { ...op.body, schema: rewrite(op.body.schema) };
430
+ op.responses = op.responses.map((r) => r.schema ? { ...r, schema: rewrite(r.schema) } : r);
431
+ op.query = op.query.map((p) => ({ ...p, schema: rewrite(p.schema) }));
432
+ op.headers = op.headers.map((p) => ({
433
+ ...p,
434
+ schema: rewrite(p.schema),
435
+ }));
436
+ }
437
+ }
438
+ }
439
+ return models;
440
+ }
441
+ function renameRefs(schema, renames) {
442
+ switch (schema.type) {
443
+ case 'ref': {
444
+ const name = renames.get(schema.name);
445
+ return name ? { ...schema, name } : schema;
446
+ }
447
+ case 'array':
448
+ return { ...schema, items: renameRefs(schema.items, renames) };
449
+ case 'object': {
450
+ const properties = {};
451
+ for (const [k, v] of Object.entries(schema.properties))
452
+ properties[k] = renameRefs(v, renames);
453
+ const out = { ...schema, properties };
454
+ if (typeof schema.additionalProperties === 'object') {
455
+ out.additionalProperties = renameRefs(schema.additionalProperties, renames);
456
+ }
457
+ return out;
458
+ }
459
+ case 'union':
460
+ return {
461
+ ...schema,
462
+ anyOf: schema.anyOf.map((s) => renameRefs(s, renames)),
463
+ };
464
+ case 'intersection':
465
+ return {
466
+ ...schema,
467
+ allOf: schema.allOf.map((s) => renameRefs(s, renames)),
468
+ };
469
+ default:
470
+ return schema;
471
+ }
472
+ }
@@ -0,0 +1,25 @@
1
+ import type { HttpMethod } from '../model/collection.js';
2
+ import type { PathSegment } from '../parsers/types.js';
3
+ export declare function isIdentifier(name: string): boolean;
4
+ /** Split `getUserByID`, `get_user-by id`, `HTTPServer2` into lowercase words. */
5
+ export declare function words(input: string): string[];
6
+ export declare function pascalCase(input: string): string;
7
+ export declare function camelCase(input: string): string;
8
+ /** camelCase identifier that is never empty, never starts with a digit and is not reserved. */
9
+ export declare function toIdentifier(input: string, fallback: string): string;
10
+ /** PascalCase type name, never empty and never starting with a digit. */
11
+ export declare function toTypeName(input: string, fallback: string): string;
12
+ export declare function singularize(word: string): string;
13
+ /** Drops scenario suffixes: `Login (401)`, `Login – wrong password`, `Login failed` → `Login`. */
14
+ export declare function cleanTitle(title: string): string;
15
+ /** `GET /v1/users/:id/posts` → `getUsersPosts`; `GET /users/:id` → `getUsersById`. */
16
+ export declare function nameFromPath(method: HttpMethod, segments: PathSegment[]): string;
17
+ /** Hands out unique names: `user`, `user2`, `user3`… */
18
+ export declare class NameRegistry {
19
+ private readonly taken;
20
+ constructor(reserved?: Iterable<string>);
21
+ has(name: string): boolean;
22
+ add(name: string): void;
23
+ /** First of `candidates` that is free (with all `suffixes` appended), else numbered. */
24
+ claim(candidates: string[], suffixes?: string[]): string;
25
+ }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NameRegistry = void 0;
4
+ exports.isIdentifier = isIdentifier;
5
+ exports.words = words;
6
+ exports.pascalCase = pascalCase;
7
+ exports.camelCase = camelCase;
8
+ exports.toIdentifier = toIdentifier;
9
+ exports.toTypeName = toTypeName;
10
+ exports.singularize = singularize;
11
+ exports.cleanTitle = cleanTitle;
12
+ exports.nameFromPath = nameFromPath;
13
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
14
+ const RESERVED_WORDS = new Set(('break case catch class const continue debugger default delete do else enum export extends ' +
15
+ 'false finally for function if import in instanceof new null return super switch this throw ' +
16
+ 'true try typeof var void while with yield let static implements interface package private ' +
17
+ 'protected public await arguments eval undefined NaN Infinity').split(' '));
18
+ function isIdentifier(name) {
19
+ return IDENTIFIER.test(name) && !RESERVED_WORDS.has(name);
20
+ }
21
+ /** Split `getUserByID`, `get_user-by id`, `HTTPServer2` into lowercase words. */
22
+ function words(input) {
23
+ return input
24
+ .normalize('NFKD')
25
+ .replace(/[̀-ͯ]/g, '')
26
+ .replace(/([a-z\d])([A-Z])/g, '$1 $2')
27
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
28
+ .split(/[^A-Za-z\d]+/)
29
+ .filter(Boolean)
30
+ .map((w) => w.toLowerCase());
31
+ }
32
+ const cap = (w) => w.charAt(0).toUpperCase() + w.slice(1);
33
+ function pascalCase(input) {
34
+ return words(input).map(cap).join('');
35
+ }
36
+ function camelCase(input) {
37
+ const p = pascalCase(input);
38
+ return p.charAt(0).toLowerCase() + p.slice(1);
39
+ }
40
+ /** camelCase identifier that is never empty, never starts with a digit and is not reserved. */
41
+ function toIdentifier(input, fallback) {
42
+ let id = camelCase(input) || fallback;
43
+ if (/^\d/.test(id))
44
+ id = `_${id}`;
45
+ if (RESERVED_WORDS.has(id))
46
+ id = `${id}_`;
47
+ return id;
48
+ }
49
+ /** PascalCase type name, never empty and never starting with a digit. */
50
+ function toTypeName(input, fallback) {
51
+ let name = pascalCase(input) || fallback;
52
+ if (/^\d/.test(name))
53
+ name = `T${name}`;
54
+ return name;
55
+ }
56
+ function singularize(word) {
57
+ if (/ies$/i.test(word) && word.length > 4)
58
+ return word.slice(0, -3) + 'y';
59
+ if (/(ss|us|is)$/i.test(word))
60
+ return word;
61
+ if (/(x|ch|sh|ses)es$/i.test(word))
62
+ return word.slice(0, -2);
63
+ if (/s$/i.test(word) && word.length > 1)
64
+ return word.slice(0, -1);
65
+ return word;
66
+ }
67
+ const STATUS_WORD = /^(success(ful(ly)?)?|succeed(ed|s)?|ok|fail(ed|ure|ing|s)?|errors?|invalid|valid|unauthori[sz]ed|forbidden|not|found|bad|request|conflict|timeout|positive|negative|happy|sad|path|edge|case|expired|missing|wrong|incorrect|empty|duplicate|rejected|denied|[1-5]\d\d|[1-5]xx|response|example|scenario|variant)$/i;
68
+ /** A phrase made only of status / scenario words ("not found", "401 Unauthorized"). */
69
+ function isStatusPhrase(phrase) {
70
+ const w = words(phrase);
71
+ return w.length > 0 && w.every((x) => STATUS_WORD.test(x));
72
+ }
73
+ /** A phrase that *starts* with a scenario marker ("wrong password", "invalid token"). */
74
+ function isScenarioPhrase(phrase) {
75
+ const first = words(phrase)[0];
76
+ return first !== undefined && STATUS_WORD.test(first);
77
+ }
78
+ /** Drops scenario suffixes: `Login (401)`, `Login – wrong password`, `Login failed` → `Login`. */
79
+ function cleanTitle(title) {
80
+ let t = title.replace(/[([{]([^)\]}]*)[)\]}]/g, (m, inner) => isStatusPhrase(inner) || isScenarioPhrase(inner) ? ' ' : m);
81
+ const parts = t.split(/\s+-\s+|\s*[–—|]\s*|\s*:\s+/);
82
+ while (parts.length > 1 && isScenarioPhrase(parts[parts.length - 1]))
83
+ parts.pop();
84
+ t = parts.join(' ');
85
+ const w = t.trim().split(/\s+/);
86
+ while (w.length > 1 && STATUS_WORD.test(words(w[w.length - 1]).join('')))
87
+ w.pop();
88
+ const cleaned = w.join(' ').trim();
89
+ return words(cleaned).length > 0 ? cleaned : title.trim();
90
+ }
91
+ const VERBS = {
92
+ GET: 'get',
93
+ HEAD: 'head',
94
+ OPTIONS: 'options',
95
+ POST: 'create',
96
+ PUT: 'update',
97
+ PATCH: 'patch',
98
+ DELETE: 'delete',
99
+ };
100
+ /** `GET /v1/users/:id/posts` → `getUsersPosts`; `GET /users/:id` → `getUsersById`. */
101
+ function nameFromPath(method, segments) {
102
+ const statics = [];
103
+ const trailing = [];
104
+ for (const seg of segments) {
105
+ if (seg.kind === 'literal') {
106
+ trailing.length = 0;
107
+ if (/^v\d+(\.\d+)*$/i.test(seg.value) || /^api$/i.test(seg.value))
108
+ continue;
109
+ statics.push(seg.value);
110
+ }
111
+ else {
112
+ trailing.push(seg.name);
113
+ }
114
+ }
115
+ const noun = statics.map(pascalCase).join('') || 'Root';
116
+ const by = trailing.length ? 'By' + trailing.map(pascalCase).join('And') : '';
117
+ return VERBS[method] + noun + by;
118
+ }
119
+ /** Hands out unique names: `user`, `user2`, `user3`… */
120
+ class NameRegistry {
121
+ taken = new Set();
122
+ constructor(reserved = []) {
123
+ for (const name of reserved)
124
+ this.taken.add(name);
125
+ }
126
+ has(name) {
127
+ return this.taken.has(name);
128
+ }
129
+ add(name) {
130
+ this.taken.add(name);
131
+ }
132
+ /** First of `candidates` that is free (with all `suffixes` appended), else numbered. */
133
+ claim(candidates, suffixes = ['']) {
134
+ const free = (base) => suffixes.every((s) => !this.taken.has(base + s));
135
+ const pick = (base) => {
136
+ for (const s of suffixes)
137
+ this.taken.add(base + s);
138
+ return base;
139
+ };
140
+ for (const c of candidates)
141
+ if (c && free(c))
142
+ return pick(c);
143
+ const base = candidates.find(Boolean) ?? 'Item';
144
+ for (let i = 2;; i++)
145
+ if (free(`${base}${i}`))
146
+ return pick(`${base}${i}`);
147
+ }
148
+ }
149
+ exports.NameRegistry = NameRegistry;
@@ -0,0 +1,10 @@
1
+ import type { HttpMethod } from '../model/collection.js';
2
+ import type { PathSegment } from '../parsers/types.js';
3
+ /** True for values that are almost certainly ids, not route names. */
4
+ export declare function looksLikeId(segment: string): boolean;
5
+ /** `:id`, `{{id}}`, `{id}` → param; `123`, a UUID or ObjectId → inferred param; else literal. */
6
+ export declare function classifySegment(raw: string, previous: string | undefined): PathSegment;
7
+ /** Split a path (no origin, no query) into classified segments. */
8
+ export declare function segmentsFromPath(pathname: string): PathSegment[];
9
+ /** Same-API key: `GET /users/:id` and `GET /users/42` both become `GET /users/{}`. */
10
+ export declare function operationKey(method: HttpMethod, segments: PathSegment[]): string;