@burnsred/entity-sync 0.0.0-stage → 3.0.0-rc.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +11 -0
  3. package/CHANGELOG.md +15 -0
  4. package/LICENSE +21 -0
  5. package/README.md +240 -2
  6. package/agents/entity-editor.md +16 -0
  7. package/bin/entity-sync.mjs +36 -0
  8. package/dist/cli.d.mts +20 -0
  9. package/dist/commands/asserts.d.mts +4 -0
  10. package/dist/commands/check.d.mts +6 -0
  11. package/dist/commands/inspect.d.mts +30 -0
  12. package/dist/commands/plan.d.mts +28 -0
  13. package/dist/commands/schema.d.mts +39 -0
  14. package/dist/config.d.mts +175 -0
  15. package/dist/index.d.mts +5 -0
  16. package/dist/lib/cache.d.mts +120 -0
  17. package/dist/lib/diff.d.mts +228 -0
  18. package/dist/lib/field-map.d.mts +93 -0
  19. package/dist/lib/gen-asserts.d.mts +70 -0
  20. package/dist/lib/graph.d.mts +90 -0
  21. package/dist/lib/parse-entities.d.mts +257 -0
  22. package/dist/lib/parse-schema.d.mts +98 -0
  23. package/dist/lib/resolve.d.mts +135 -0
  24. package/dist/project.d.mts +60 -0
  25. package/hooks/editor-guard.mjs +86 -0
  26. package/hooks/hooks.json +15 -0
  27. package/package.json +54 -4
  28. package/skills/entity/SKILL.md +105 -0
  29. package/skills/entity/reference/create.md +74 -0
  30. package/skills/entity/reference/editor.md +80 -0
  31. package/skills/entity/reference/enums.md +89 -0
  32. package/skills/entity/reference/fields.md +101 -0
  33. package/skills/entity/reference/sync.md +191 -0
  34. package/src/cli.mjs +110 -0
  35. package/src/commands/asserts.mjs +52 -0
  36. package/src/commands/check.mjs +88 -0
  37. package/src/commands/inspect.mjs +290 -0
  38. package/src/commands/plan.mjs +542 -0
  39. package/src/commands/schema.mjs +206 -0
  40. package/src/config.mjs +205 -0
  41. package/src/index.mjs +19 -0
  42. package/src/lib/cache.mjs +323 -0
  43. package/src/lib/diff.mjs +706 -0
  44. package/src/lib/field-map.mjs +438 -0
  45. package/src/lib/gen-asserts.mjs +478 -0
  46. package/src/lib/graph.mjs +284 -0
  47. package/src/lib/parse-entities.mjs +935 -0
  48. package/src/lib/parse-schema.mjs +667 -0
  49. package/src/lib/resolve.mjs +455 -0
  50. package/src/project.mjs +115 -0
@@ -0,0 +1,667 @@
1
+ // @ts-check
2
+ /**
3
+ * Parse `src/api/schema.d.ts` into a normalised, JSON-serialisable description of
4
+ * every OpenAPI component and an index of which component each endpoint returns.
5
+ *
6
+ * ## Why the AST and not the type checker
7
+ *
8
+ * The obvious approach is to ask the TypeScript type checker for the type of each
9
+ * property. That loses exactly the information this tool exists to track: the
10
+ * checker resolves `components['schemas']['Member']` to its structural type, so
11
+ * the component *name* - the edge in the dependency graph - disappears. Walking
12
+ * the declared syntax keeps `$ref` targets, array-ness and `| null` intact,
13
+ * because those are all syntactic in the generated output.
14
+ *
15
+ * The generated file is machine-written and highly regular, so a syntactic walk
16
+ * is also predictable in a way checker-based inference is not.
17
+ *
18
+ * ## What "normalised" means
19
+ *
20
+ * Every field is reduced to the signals an Entity definition actually depends on
21
+ * (see `field-map.mjs`): the primitive kind, the `$ref` targets, `Format:` from
22
+ * the JSDoc, and the three modifiers `readonly` / `?` / `| null`. Anything else
23
+ * openapi-typescript emits - `@example`, `@enum`, header maps - is dropped.
24
+ */
25
+
26
+ import { readFileSync } from 'node:fs';
27
+
28
+ import ts from 'typescript';
29
+
30
+ /**
31
+ * The value side of an `additionalProperties` map, described with the same
32
+ * vocabulary as a field so `field-map.mjs` can render `Record<string, V>`.
33
+ *
34
+ * @typedef {object} MapValue
35
+ * @property {string} tsType
36
+ * @property {boolean} isArray
37
+ * @property {boolean} nullable
38
+ * @property {string[]} refs
39
+ */
40
+
41
+ /**
42
+ * @typedef {object} SchemaField
43
+ * @property {string} name
44
+ * @property {boolean} optional had a `?` modifier (DRF `required: false`)
45
+ * @property {boolean} readonly had a `readonly` modifier (DRF `readOnly: true`)
46
+ * @property {boolean} nullable the type union included `null`
47
+ * @property {boolean} isArray the type was `T[]`
48
+ * @property {string[]} refs component names this field references, in order
49
+ * @property {string} tsType 'string' | 'number' | 'boolean' | 'ref' | 'record' | 'unknown'
50
+ * @property {MapValue | null} mapValue populated when tsType === 'record'
51
+ * @property {string | null} format e.g. 'uuid', 'date-time', 'decimal'
52
+ * @property {string | null} description
53
+ */
54
+
55
+ /**
56
+ * @typedef {object} SchemaComponent
57
+ * @property {string} name
58
+ * @property {'object' | 'enum' | 'other'} kind
59
+ * @property {string | null} description
60
+ * @property {SchemaField[]} fields populated when kind === 'object'
61
+ * @property {string[]} enumValues populated when kind === 'enum'
62
+ */
63
+
64
+ /**
65
+ * @typedef {object} EndpointResponse
66
+ * @property {string} operation the `operations` key, e.g. 'x_application_retrieve'
67
+ * @property {string} component the component the 2xx JSON response resolves to
68
+ * @property {boolean} paginated the response was a `Paginated…List` wrapper
69
+ */
70
+
71
+ /**
72
+ * @typedef {object} ParsedSchema
73
+ * @property {Record<string, SchemaComponent>} components
74
+ * @property {Record<string, Record<string, EndpointResponse>>} pathsIndex
75
+ * urlPath -> httpMethod -> response info
76
+ */
77
+
78
+ /** Media type whose response shape the entity layer consumes. */
79
+ const JSON_MEDIA_TYPE = 'application/json';
80
+
81
+ /** Methods worth indexing; `options`/`head`/`trace` never carry entity shapes. */
82
+ const INDEXED_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
83
+
84
+ // ── AST helpers ────────────────────────────────────────────────────────────────
85
+
86
+ /**
87
+ * Read the property name of a member, whether written bare or quoted.
88
+ *
89
+ * Path keys arrive as string literals (`'/api/x/'`), component names bare
90
+ * (`Application`), and status codes as numeric literals (`200`).
91
+ *
92
+ * @param {ts.PropertySignature} member
93
+ * @returns {string | null}
94
+ */
95
+ function memberName(member) {
96
+ const { name } = member;
97
+ if (ts.isIdentifier(name)) return name.text;
98
+ if (ts.isStringLiteral(name)) return name.text;
99
+ if (ts.isNumericLiteral(name)) return name.text;
100
+ return null;
101
+ }
102
+
103
+ /**
104
+ * Find a named member inside a type literal.
105
+ *
106
+ * @param {ts.TypeLiteralNode} literal
107
+ * @param {string} name
108
+ * @returns {ts.PropertySignature | null}
109
+ */
110
+ function findMember(literal, name) {
111
+ for (const member of literal.members) {
112
+ if (ts.isPropertySignature(member) && memberName(member) === name) {
113
+ return member;
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * Find a top-level `export interface <name>` declaration.
121
+ *
122
+ * @param {ts.SourceFile} sourceFile
123
+ * @param {string} name
124
+ * @returns {ts.InterfaceDeclaration | null}
125
+ */
126
+ function findInterface(sourceFile, name) {
127
+ for (const statement of sourceFile.statements) {
128
+ if (ts.isInterfaceDeclaration(statement) && statement.name.text === name) {
129
+ return statement;
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * Recognise `components['schemas']['Name']` and return `Name`.
137
+ *
138
+ * The generated form is a doubly-nested indexed access, so both index steps are
139
+ * checked rather than just grabbing the last one - that way an unexpected shape
140
+ * returns null instead of a plausible-looking wrong answer.
141
+ *
142
+ * @param {ts.TypeNode} node
143
+ * @returns {string | null}
144
+ */
145
+ function componentRefName(node) {
146
+ if (!ts.isIndexedAccessTypeNode(node)) return null;
147
+
148
+ const inner = node.objectType;
149
+ if (!ts.isIndexedAccessTypeNode(inner)) return null;
150
+
151
+ // inner.objectType must be the `components` type reference
152
+ const base = inner.objectType;
153
+ if (!ts.isTypeReferenceNode(base)) return null;
154
+ if (!ts.isIdentifier(base.typeName) || base.typeName.text !== 'components') {
155
+ return null;
156
+ }
157
+
158
+ // inner.indexType must be the literal 'schemas'
159
+ if (!ts.isLiteralTypeNode(inner.indexType)) return null;
160
+ if (!ts.isStringLiteral(inner.indexType.literal)) return null;
161
+ if (inner.indexType.literal.text !== 'schemas') return null;
162
+
163
+ // node.indexType is the component name
164
+ if (!ts.isLiteralTypeNode(node.indexType)) return null;
165
+ if (!ts.isStringLiteral(node.indexType.literal)) return null;
166
+
167
+ return node.indexType.literal.text;
168
+ }
169
+
170
+ /**
171
+ * Map a primitive type keyword to our `tsType` vocabulary.
172
+ *
173
+ * @param {ts.TypeNode} node
174
+ * @returns {string | null}
175
+ */
176
+ function primitiveKind(node) {
177
+ switch (node.kind) {
178
+ case ts.SyntaxKind.StringKeyword:
179
+ return 'string';
180
+ case ts.SyntaxKind.NumberKeyword:
181
+ return 'number';
182
+ case ts.SyntaxKind.BooleanKeyword:
183
+ return 'boolean';
184
+ case ts.SyntaxKind.UnknownKeyword:
185
+ case ts.SyntaxKind.AnyKeyword:
186
+ return 'unknown';
187
+ default:
188
+ return null;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Recognise `{ [key: string]: V }` and return the value type node.
194
+ *
195
+ * This is how openapi-typescript renders `additionalProperties`, which is what
196
+ * drf-spectacular emits for a `DictField` / `HStoreField`. It is neither a
197
+ * primitive keyword nor an indexed access, so without this it falls through to
198
+ * `unknown` - and a correctly-typed `Record<string, T>` on the entity then
199
+ * reads as drift on every run.
200
+ *
201
+ * Only a sole index signature counts. A literal mixing named members with an
202
+ * index signature is a shape the entity layer does not model, and returning
203
+ * null lets it fall through to `unknown` rather than silently dropping the
204
+ * named members.
205
+ *
206
+ * @param {ts.TypeNode} node
207
+ * @returns {ts.TypeNode | null}
208
+ */
209
+ function indexSignatureValue(node) {
210
+ if (!ts.isTypeLiteralNode(node)) return null;
211
+ if (node.members.length !== 1) return null;
212
+
213
+ const [member] = node.members;
214
+ if (!ts.isIndexSignatureDeclaration(member)) return null;
215
+
216
+ return member.type ?? null;
217
+ }
218
+
219
+ /**
220
+ * Is this the `null` literal type?
221
+ *
222
+ * @param {ts.TypeNode} node
223
+ */
224
+ function isNullLiteral(node) {
225
+ return (
226
+ ts.isLiteralTypeNode(node) &&
227
+ node.literal.kind === ts.SyntaxKind.NullKeyword
228
+ );
229
+ }
230
+
231
+ // ── Field parsing ──────────────────────────────────────────────────────────────
232
+
233
+ /**
234
+ * Reduce a field's declared type to `{ tsType, nullable, isArray, refs }`.
235
+ *
236
+ * Handles the five shapes openapi-typescript actually emits for a property:
237
+ *
238
+ * string -> primitive
239
+ * string | null -> primitive, nullable
240
+ * components['schemas']['X'] -> ref
241
+ * components['schemas']['X'][] -> ref, isArray
242
+ * components['schemas']['A'] | ['schemas']['B'] -> two refs (enum + BlankEnum)
243
+ * { [key: string]: string } -> 'record', with mapValue
244
+ *
245
+ * @param {ts.TypeNode} node
246
+ * @returns {{ tsType: string, nullable: boolean, isArray: boolean, refs: string[], mapValue: MapValue | null }}
247
+ */
248
+ function parseFieldType(node) {
249
+ let nullable = false;
250
+ let isArray = false;
251
+ /** @type {string[]} */
252
+ const refs = [];
253
+ /** @type {string | null} */
254
+ let tsType = null;
255
+ /** @type {MapValue | null} */
256
+ let mapValue = null;
257
+
258
+ /** @param {ts.TypeNode} current */
259
+ const visit = (current) => {
260
+ // `A | B | null` - flatten, recording null as a modifier rather than a member
261
+ if (ts.isUnionTypeNode(current)) {
262
+ for (const member of current.types) {
263
+ if (isNullLiteral(member)) {
264
+ nullable = true;
265
+ continue;
266
+ }
267
+ visit(member);
268
+ }
269
+ return;
270
+ }
271
+
272
+ // `(A | B | C) | null` - openapi-typescript parenthesises the members of a
273
+ // nullable anyOf, as on `Payment.payment_destination`. Without unwrapping,
274
+ // the whole group reads as one unknown member and every ref inside it is
275
+ // lost, so a nullable enum stops looking like an enum at all.
276
+ if (ts.isParenthesizedTypeNode(current)) {
277
+ visit(current.type);
278
+ return;
279
+ }
280
+
281
+ // `T[]` - unwrap, recording the array-ness
282
+ if (ts.isArrayTypeNode(current)) {
283
+ isArray = true;
284
+ visit(current.elementType);
285
+ return;
286
+ }
287
+
288
+ // `readonly T[]` shows up when openapi-typescript is run with --immutable
289
+ if (
290
+ ts.isTypeOperatorNode(current) &&
291
+ current.operator === ts.SyntaxKind.ReadonlyKeyword
292
+ ) {
293
+ visit(current.type);
294
+ return;
295
+ }
296
+
297
+ const ref = componentRefName(current);
298
+ if (ref) {
299
+ refs.push(ref);
300
+ tsType = 'ref';
301
+ return;
302
+ }
303
+
304
+ const primitive = primitiveKind(current);
305
+ if (primitive) {
306
+ // Don't let a primitive overwrite a ref seen earlier in the union.
307
+ tsType ??= primitive;
308
+ return;
309
+ }
310
+
311
+ // String-literal unions appear inline for some inline enums.
312
+ if (ts.isLiteralTypeNode(current) && ts.isStringLiteral(current.literal)) {
313
+ tsType ??= 'string';
314
+ return;
315
+ }
316
+
317
+ // `{ [key: string]: V }` - an `additionalProperties` map. The value is
318
+ // parsed with the same machinery, so `{ [key: string]: string[] }` and a
319
+ // map of `$ref`s both come back described rather than flattened.
320
+ const valueNode = indexSignatureValue(current);
321
+ if (valueNode) {
322
+ const value = parseFieldType(valueNode);
323
+ tsType ??= 'record';
324
+ mapValue ??= {
325
+ tsType: value.tsType,
326
+ isArray: value.isArray,
327
+ nullable: value.nullable,
328
+ refs: value.refs,
329
+ };
330
+ return;
331
+ }
332
+
333
+ tsType ??= 'unknown';
334
+ };
335
+
336
+ visit(node);
337
+
338
+ return { tsType: tsType ?? 'unknown', nullable, isArray, refs, mapValue };
339
+ }
340
+
341
+ /**
342
+ * Pull `Format:` and `@description` out of a member's JSDoc.
343
+ *
344
+ * openapi-typescript writes `Format: uuid` as free comment text, not a tag, so
345
+ * both the comment body and the tag list have to be read:
346
+ *
347
+ * \/**
348
+ * * Format: uuid
349
+ * * @description Member associated with this application.
350
+ * *\/
351
+ *
352
+ * @param {ts.Node} node
353
+ * @returns {{ format: string | null, description: string | null }}
354
+ */
355
+ function parseJsDoc(node) {
356
+ /** @type {string | null} */
357
+ let format = null;
358
+ /** @type {string | null} */
359
+ let description = null;
360
+
361
+ // `jsDoc` is an internal-ish property, but it is the only way to reach the
362
+ // free comment text; getJSDocTags() alone would miss `Format:`.
363
+ const jsDocs = /** @type {{ jsDoc?: ts.JSDoc[] }} */ (node).jsDoc ?? [];
364
+
365
+ for (const doc of jsDocs) {
366
+ const body = typeof doc.comment === 'string' ? doc.comment : '';
367
+ const match = body.match(/Format:\s*(\S+)/);
368
+ if (match) format = match[1];
369
+
370
+ for (const tag of doc.tags ?? []) {
371
+ if (
372
+ tag.tagName.text === 'description' &&
373
+ typeof tag.comment === 'string'
374
+ ) {
375
+ description = tag.comment.trim();
376
+ }
377
+ }
378
+ }
379
+
380
+ return { format, description };
381
+ }
382
+
383
+ /**
384
+ * @param {ts.PropertySignature} member
385
+ * @returns {SchemaField | null}
386
+ */
387
+ function parseField(member) {
388
+ const name = memberName(member);
389
+ if (!name || !member.type) return null;
390
+
391
+ const { tsType, nullable, isArray, refs, mapValue } = parseFieldType(
392
+ member.type,
393
+ );
394
+ const { format, description } = parseJsDoc(member);
395
+
396
+ return {
397
+ name,
398
+ optional: Boolean(member.questionToken),
399
+ readonly: Boolean(
400
+ member.modifiers?.some((m) => m.kind === ts.SyntaxKind.ReadonlyKeyword),
401
+ ),
402
+ nullable,
403
+ isArray,
404
+ refs,
405
+ tsType,
406
+ mapValue,
407
+ format,
408
+ description,
409
+ };
410
+ }
411
+
412
+ // ── Component parsing ──────────────────────────────────────────────────────────
413
+
414
+ /**
415
+ * @param {ts.PropertySignature} member a member of `components.schemas`
416
+ * @returns {SchemaComponent | null}
417
+ */
418
+ function parseComponent(member) {
419
+ const name = memberName(member);
420
+ if (!name || !member.type) return null;
421
+
422
+ const { description } = parseJsDoc(member);
423
+
424
+ // Object components: `Application: { … }`
425
+ if (ts.isTypeLiteralNode(member.type)) {
426
+ /** @type {SchemaField[]} */
427
+ const fields = [];
428
+ for (const field of member.type.members) {
429
+ if (!ts.isPropertySignature(field)) continue;
430
+ const parsed = parseField(field);
431
+ if (parsed) fields.push(parsed);
432
+ }
433
+ return { name, kind: 'object', description, fields, enumValues: [] };
434
+ }
435
+
436
+ // Enum components: `ApplicationStatusEnum: 'pending' | 'approved' | …`
437
+ const enumValues = parseEnumValues(member.type);
438
+ if (enumValues) {
439
+ return { name, kind: 'enum', description, fields: [], enumValues };
440
+ }
441
+
442
+ return { name, kind: 'other', description, fields: [], enumValues: [] };
443
+ }
444
+
445
+ /**
446
+ * Read a string-literal union (or single literal) as enum values.
447
+ *
448
+ * Returns null when the node is not a literal union, so the caller can fall
449
+ * through to `kind: 'other'` rather than treating it as an empty enum.
450
+ *
451
+ * @param {ts.TypeNode} node
452
+ * @returns {string[] | null}
453
+ */
454
+ function parseEnumValues(node) {
455
+ if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) {
456
+ return [node.literal.text];
457
+ }
458
+
459
+ if (!ts.isUnionTypeNode(node)) return null;
460
+
461
+ /** @type {string[]} */
462
+ const values = [];
463
+ for (const member of node.types) {
464
+ if (!ts.isLiteralTypeNode(member)) return null;
465
+ if (!ts.isStringLiteral(member.literal)) return null;
466
+ values.push(member.literal.text);
467
+ }
468
+
469
+ return values.length ? values : null;
470
+ }
471
+
472
+ // ── Paths / operations indexing ────────────────────────────────────────────────
473
+
474
+ /**
475
+ * Resolve an operation's 2xx JSON response to a component name.
476
+ *
477
+ * Walks `responses` -> first 2xx -> `content` -> `application/json`, then
478
+ * unwraps a `Paginated…List` wrapper by following its `results` field, so a
479
+ * list endpoint reports the item component rather than the envelope.
480
+ *
481
+ * @param {ts.TypeLiteralNode} operation
482
+ * @param {Record<string, SchemaComponent>} components
483
+ * @returns {{ component: string, paginated: boolean } | null}
484
+ */
485
+ function resolveOperationResponse(operation, components) {
486
+ const responses = findMember(operation, 'responses');
487
+ if (!responses?.type || !ts.isTypeLiteralNode(responses.type)) return null;
488
+
489
+ for (const status of responses.type.members) {
490
+ if (!ts.isPropertySignature(status)) continue;
491
+
492
+ const code = Number(memberName(status));
493
+ if (!Number.isFinite(code) || code < 200 || code > 299) continue;
494
+ if (!status.type || !ts.isTypeLiteralNode(status.type)) continue;
495
+
496
+ const content = findMember(status.type, 'content');
497
+ if (!content?.type || !ts.isTypeLiteralNode(content.type)) continue;
498
+
499
+ const json = findMember(content.type, JSON_MEDIA_TYPE);
500
+ if (!json?.type) continue;
501
+
502
+ const ref = componentRefName(json.type);
503
+ if (!ref) continue;
504
+
505
+ // Unwrap `PaginatedXList` -> `X` via its `results` field, so callers see
506
+ // the entity component and not the pagination envelope.
507
+ const wrapper = components[ref];
508
+ if (wrapper?.kind === 'object') {
509
+ const results = wrapper.fields.find((f) => f.name === 'results');
510
+ if (results?.isArray && results.refs.length === 1) {
511
+ return { component: results.refs[0], paginated: true };
512
+ }
513
+ }
514
+
515
+ return { component: ref, paginated: false };
516
+ }
517
+
518
+ return null;
519
+ }
520
+
521
+ /**
522
+ * Build `urlPath -> method -> { operation, component, paginated }`.
523
+ *
524
+ * `paths` members point at `operations['name']` rather than inlining the
525
+ * response, so this resolves that one level of indirection explicitly.
526
+ *
527
+ * @param {ts.SourceFile} sourceFile
528
+ * @param {Record<string, SchemaComponent>} components
529
+ * @returns {Record<string, Record<string, EndpointResponse>>}
530
+ */
531
+ function parsePaths(sourceFile, components) {
532
+ const pathsInterface = findInterface(sourceFile, 'paths');
533
+ const operationsInterface = findInterface(sourceFile, 'operations');
534
+ if (!pathsInterface || !operationsInterface) return {};
535
+
536
+ // Index operations by name once, so path resolution stays linear.
537
+ /** @type {Map<string, ts.TypeLiteralNode>} */
538
+ const operations = new Map();
539
+ for (const member of operationsInterface.members) {
540
+ if (!ts.isPropertySignature(member)) continue;
541
+ const name = memberName(member);
542
+ if (name && member.type && ts.isTypeLiteralNode(member.type)) {
543
+ operations.set(name, member.type);
544
+ }
545
+ }
546
+
547
+ /** @type {Record<string, Record<string, EndpointResponse>>} */
548
+ const index = {};
549
+
550
+ for (const pathMember of pathsInterface.members) {
551
+ if (!ts.isPropertySignature(pathMember)) continue;
552
+
553
+ const urlPath = memberName(pathMember);
554
+ if (!urlPath || !pathMember.type) continue;
555
+ if (!ts.isTypeLiteralNode(pathMember.type)) continue;
556
+
557
+ /** @type {Record<string, EndpointResponse>} */
558
+ const methods = {};
559
+
560
+ for (const method of INDEXED_METHODS) {
561
+ const methodMember = findMember(pathMember.type, method);
562
+ if (!methodMember?.type) continue;
563
+
564
+ // Unsupported methods are typed `never`.
565
+ const operationName = operationRefName(methodMember.type);
566
+ if (!operationName) continue;
567
+
568
+ const operation = operations.get(operationName);
569
+ if (!operation) continue;
570
+
571
+ const resolved = resolveOperationResponse(operation, components);
572
+ if (!resolved) continue;
573
+
574
+ methods[method] = { operation: operationName, ...resolved };
575
+ }
576
+
577
+ if (Object.keys(methods).length) index[urlPath] = methods;
578
+ }
579
+
580
+ return index;
581
+ }
582
+
583
+ /**
584
+ * Recognise `operations['name']` and return `name`.
585
+ *
586
+ * @param {ts.TypeNode} node
587
+ * @returns {string | null}
588
+ */
589
+ function operationRefName(node) {
590
+ if (!ts.isIndexedAccessTypeNode(node)) return null;
591
+
592
+ const base = node.objectType;
593
+ if (!ts.isTypeReferenceNode(base)) return null;
594
+ if (!ts.isIdentifier(base.typeName) || base.typeName.text !== 'operations') {
595
+ return null;
596
+ }
597
+
598
+ if (!ts.isLiteralTypeNode(node.indexType)) return null;
599
+ if (!ts.isStringLiteral(node.indexType.literal)) return null;
600
+
601
+ return node.indexType.literal.text;
602
+ }
603
+
604
+ // ── Entry point ────────────────────────────────────────────────────────────────
605
+
606
+ /**
607
+ * Parse a `schema.d.ts` source string.
608
+ *
609
+ * Exposed separately from `parseSchemaFile` so tests can run against fixture
610
+ * strings without touching the filesystem.
611
+ *
612
+ * @param {string} source
613
+ * @param {string} [fileName] for diagnostics only
614
+ * @returns {ParsedSchema}
615
+ */
616
+ export function parseSchema(source, fileName = 'schema.d.ts') {
617
+ const sourceFile = ts.createSourceFile(
618
+ fileName,
619
+ source,
620
+ ts.ScriptTarget.ES2022,
621
+ // `true` keeps parent pointers and JSDoc, which parseJsDoc depends on.
622
+ true,
623
+ );
624
+
625
+ const componentsInterface = findInterface(sourceFile, 'components');
626
+ if (!componentsInterface) {
627
+ throw new Error(`${fileName}: no \`export interface components\` found`);
628
+ }
629
+
630
+ const schemas = componentsInterface.members.find(
631
+ (m) => ts.isPropertySignature(m) && memberName(m) === 'schemas',
632
+ );
633
+ if (
634
+ !schemas ||
635
+ !ts.isPropertySignature(schemas) ||
636
+ !schemas.type ||
637
+ !ts.isTypeLiteralNode(schemas.type)
638
+ ) {
639
+ throw new Error(
640
+ `${fileName}: \`components.schemas\` is not an object type`,
641
+ );
642
+ }
643
+
644
+ /** @type {Record<string, SchemaComponent>} */
645
+ const components = {};
646
+ for (const member of schemas.type.members) {
647
+ if (!ts.isPropertySignature(member)) continue;
648
+ const component = parseComponent(member);
649
+ if (component) components[component.name] = component;
650
+ }
651
+
652
+ // Paths are resolved after components, because unwrapping a paginated
653
+ // response needs the wrapper component's `results` field.
654
+ const pathsIndex = parsePaths(sourceFile, components);
655
+
656
+ return { components, pathsIndex };
657
+ }
658
+
659
+ /**
660
+ * Parse a `schema.d.ts` file from disk.
661
+ *
662
+ * @param {string} filePath
663
+ * @returns {ParsedSchema}
664
+ */
665
+ export function parseSchemaFile(filePath) {
666
+ return parseSchema(readFileSync(filePath, 'utf8'), filePath);
667
+ }