@amritk/helpers 0.6.2 → 0.7.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 (67) hide show
  1. package/dist/build-dynamic-ref-map.d.ts +1 -0
  2. package/dist/build-dynamic-ref-map.d.ts.map +1 -0
  3. package/dist/build-dynamic-ref-map.js +31 -107
  4. package/dist/derive-root-type-name.d.ts +1 -0
  5. package/dist/derive-root-type-name.d.ts.map +1 -0
  6. package/dist/derive-root-type-name.js +37 -17
  7. package/dist/extract-dynamic-anchor-defs.d.ts +20 -0
  8. package/dist/extract-dynamic-anchor-defs.d.ts.map +1 -0
  9. package/dist/extract-dynamic-anchor-defs.js +30 -0
  10. package/dist/extract-refs.d.ts +1 -0
  11. package/dist/extract-refs.d.ts.map +1 -0
  12. package/dist/extract-refs.js +64 -33
  13. package/dist/generate-index-barrel.d.ts +29 -0
  14. package/dist/generate-index-barrel.d.ts.map +1 -0
  15. package/dist/generate-index-barrel.js +43 -0
  16. package/dist/generate-type-definition.d.ts +1 -0
  17. package/dist/generate-type-definition.d.ts.map +1 -0
  18. package/dist/generate-type-definition.js +449 -567
  19. package/dist/has-ref.d.ts +1 -0
  20. package/dist/has-ref.d.ts.map +1 -0
  21. package/dist/has-ref.js +7 -6
  22. package/dist/is-object.d.ts +1 -0
  23. package/dist/is-object.d.ts.map +1 -0
  24. package/dist/is-object.js +14 -5
  25. package/dist/mjst-extension.d.ts +1 -0
  26. package/dist/mjst-extension.d.ts.map +1 -0
  27. package/dist/mjst-extension.js +50 -122
  28. package/dist/parse-documentation.d.ts +1 -0
  29. package/dist/parse-documentation.d.ts.map +1 -0
  30. package/dist/parse-documentation.js +124 -87
  31. package/dist/ref-to-filename.d.ts +1 -0
  32. package/dist/ref-to-filename.d.ts.map +1 -0
  33. package/dist/ref-to-filename.js +106 -42
  34. package/dist/ref-to-name.d.ts +1 -0
  35. package/dist/ref-to-name.d.ts.map +1 -0
  36. package/dist/ref-to-name.js +39 -53
  37. package/dist/resolve-dynamic-refs.d.ts +1 -0
  38. package/dist/resolve-dynamic-refs.d.ts.map +1 -0
  39. package/dist/resolve-dynamic-refs.js +36 -28
  40. package/dist/resolve-ref.d.ts +1 -0
  41. package/dist/resolve-ref.d.ts.map +1 -0
  42. package/dist/resolve-ref.js +74 -39
  43. package/dist/safe-accessor.d.ts +1 -0
  44. package/dist/safe-accessor.d.ts.map +1 -0
  45. package/dist/safe-accessor.js +42 -19
  46. package/dist/schema-guards.d.ts +2 -1
  47. package/dist/schema-guards.d.ts.map +1 -0
  48. package/dist/schema-guards.js +119 -120
  49. package/dist/upgrade-draft07-schema.d.ts +1 -0
  50. package/dist/upgrade-draft07-schema.d.ts.map +1 -0
  51. package/dist/upgrade-draft07-schema.js +152 -130
  52. package/dist/validate-array.d.ts +1 -0
  53. package/dist/validate-array.d.ts.map +1 -0
  54. package/dist/validate-array.js +12 -14
  55. package/dist/validate-record.d.ts +1 -0
  56. package/dist/validate-record.d.ts.map +1 -0
  57. package/dist/validate-record.js +15 -17
  58. package/dist/walk-ref-graph.d.ts +54 -0
  59. package/dist/walk-ref-graph.d.ts.map +1 -0
  60. package/dist/walk-ref-graph.js +123 -0
  61. package/package.json +9 -88
  62. package/src/extract-dynamic-anchor-defs.test.ts +29 -0
  63. package/src/extract-dynamic-anchor-defs.ts +33 -0
  64. package/src/generate-index-barrel.test.ts +41 -0
  65. package/src/generate-index-barrel.ts +62 -0
  66. package/src/walk-ref-graph.test.ts +118 -0
  67. package/src/walk-ref-graph.ts +184 -0
@@ -1,18 +1,16 @@
1
- // src/is-object.ts
2
- var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
3
-
4
- // src/validate-record.ts
5
- var validateRecord = (input, parser) => {
6
- if (!isObject(input)) {
7
- return {};
8
- }
9
- const record = input;
10
- const result = {};
11
- for (const key in record) {
12
- result[key] = parser(record[key]);
13
- }
14
- return result;
15
- };
16
- export {
17
- validateRecord
1
+ import { isObject } from './is-object.js';
2
+ /**
3
+ * Parses the values of a record with a parser function.
4
+ * Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
5
+ */
6
+ export const validateRecord = (input, parser) => {
7
+ if (!isObject(input)) {
8
+ return {};
9
+ }
10
+ const record = input;
11
+ const result = {};
12
+ for (const key in record) {
13
+ result[key] = parser(record[key]);
14
+ }
15
+ return result;
18
16
  };
@@ -0,0 +1,54 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ /**
3
+ * One node of the `$ref` graph, handed to the `visit` callback. Everything a
4
+ * generator needs to emit a single output file is pre-computed here so the
5
+ * traversal, naming, and `$dynamicRef` rewriting live in one place instead of
6
+ * being copy-pasted into every generator.
7
+ */
8
+ export type RefNode = {
9
+ /** The `$ref` string this node was reached through, or `undefined` for the root schema. */
10
+ ref: string | undefined;
11
+ /** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
12
+ typeName: string;
13
+ /** kebab-case filename without extension — the lowercased root type name, or `refToFilename(ref)`. */
14
+ filename: string;
15
+ /** The subschema to generate, with any `$dynamicRef` already rewritten to `$ref`. */
16
+ schema: JSONSchema;
17
+ /** The upgraded root document, for callers that resolve imports against it. */
18
+ rootSchema: Record<string, unknown>;
19
+ /** True for the root schema node, which is always visited first. */
20
+ isRoot: boolean;
21
+ };
22
+ /** Options controlling how `$ref`-derived names are produced. */
23
+ export type WalkRefGraphOptions = {
24
+ /**
25
+ * Suffix appended to every `$ref`-derived type name (e.g. `'Object'` →
26
+ * `ContactObject`). The root type name is used verbatim and is not affected.
27
+ * Defaults to `''`.
28
+ */
29
+ readonly typeSuffix?: string;
30
+ };
31
+ /**
32
+ * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
33
+ * `visit` once per distinct output file: first the root, then every reachable
34
+ * definition (breadth-first). This is the single, shared traversal the parser,
35
+ * validator, and example generators were each re-implementing.
36
+ *
37
+ * For every node the walker has already upgraded draft-07 inputs, resolved the
38
+ * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
39
+ * callers only have to turn `node.schema` into file content. Definitions
40
+ * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
41
+ * code imports goes ungenerated. A ref that fails to resolve is reported via
42
+ * `console.warn` and skipped, matching the generators' prior behavior.
43
+ *
44
+ * Resolution work is memoized per root document (see {@link RootCache}), so
45
+ * running several generators over the same loaded schema does the expensive
46
+ * walking once.
47
+ *
48
+ * @param rootSchema - The root JSON Schema to walk.
49
+ * @param rootTypeName - The name for the root type (e.g. `'Document'`).
50
+ * @param options - Naming options ({@link WalkRefGraphOptions}).
51
+ * @param visit - Called once per output file with a fully prepared {@link RefNode}.
52
+ */
53
+ export declare const walkRefGraph: (rootSchema: JSONSchema, rootTypeName: string, options: WalkRefGraphOptions, visit: (node: RefNode) => void) => void;
54
+ //# sourceMappingURL=walk-ref-graph.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk-ref-graph.d.ts","sourceRoot":"","sources":["../src/walk-ref-graph.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AAWjE;;;;;GAKG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,2FAA2F;IAC3F,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;IACvB,2FAA2F;IAC3F,QAAQ,EAAE,MAAM,CAAA;IAChB,sGAAsG;IACtG,QAAQ,EAAE,MAAM,CAAA;IAChB,qFAAqF;IACrF,MAAM,EAAE,UAAU,CAAA;IAClB,+EAA+E;IAC/E,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACnC,oEAAoE;IACpE,MAAM,EAAE,OAAO,CAAA;CAChB,CAAA;AAED,iEAAiE;AACjE,MAAM,MAAM,mBAAmB,GAAG;IAChC;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAC7B,CAAA;AA2DD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,YAAY,eACX,UAAU,gBACR,MAAM,WACX,mBAAmB,SACrB,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,KAC7B,IAyDF,CAAA"}
@@ -0,0 +1,123 @@
1
+ import { buildDynamicRefMap } from './build-dynamic-ref-map.js';
2
+ import { extractDynamicAnchorDefs } from './extract-dynamic-anchor-defs.js';
3
+ import { extractRefs } from './extract-refs.js';
4
+ import { refToFilename } from './ref-to-filename.js';
5
+ import { refToName } from './ref-to-name.js';
6
+ import { resolveDynamicRefs } from './resolve-dynamic-refs.js';
7
+ import { resolveRef } from './resolve-ref.js';
8
+ import { upgradeDraft07Schema } from './upgrade-draft07-schema.js';
9
+ const rootCaches = new WeakMap();
10
+ const getRootCache = (rootSchema) => {
11
+ // Only object roots can key a WeakMap. A boolean root has no refs to walk and
12
+ // the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
13
+ if (typeof rootSchema !== 'object' || rootSchema === null) {
14
+ const upgraded = rootSchema;
15
+ return { upgraded, dynamicRefMap: {}, resolveRefCache: new Map(), extractRefsCache: new WeakMap() };
16
+ }
17
+ const existing = rootCaches.get(rootSchema);
18
+ if (existing)
19
+ return existing;
20
+ const upgraded = upgradeDraft07Schema(rootSchema);
21
+ const cache = {
22
+ upgraded,
23
+ dynamicRefMap: buildDynamicRefMap(upgraded),
24
+ resolveRefCache: new Map(),
25
+ extractRefsCache: new WeakMap(),
26
+ };
27
+ rootCaches.set(rootSchema, cache);
28
+ return cache;
29
+ };
30
+ /** Memoized `resolveRef` keyed by ref string within a single root document. */
31
+ const cachedResolveRef = (cache, ref) => {
32
+ if (cache.resolveRefCache.has(ref))
33
+ return cache.resolveRefCache.get(ref);
34
+ const resolved = resolveRef(ref, cache.upgraded);
35
+ cache.resolveRefCache.set(ref, resolved);
36
+ return resolved;
37
+ };
38
+ /** Memoized `extractRefs` keyed by the (stable) resolved subschema identity. */
39
+ const cachedExtractRefs = (cache, schema) => {
40
+ if (typeof schema !== 'object' || schema === null)
41
+ return extractRefs(schema);
42
+ const existing = cache.extractRefsCache.get(schema);
43
+ if (existing)
44
+ return existing;
45
+ const refs = extractRefs(schema);
46
+ cache.extractRefsCache.set(schema, refs);
47
+ return refs;
48
+ };
49
+ /**
50
+ * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
51
+ * `visit` once per distinct output file: first the root, then every reachable
52
+ * definition (breadth-first). This is the single, shared traversal the parser,
53
+ * validator, and example generators were each re-implementing.
54
+ *
55
+ * For every node the walker has already upgraded draft-07 inputs, resolved the
56
+ * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
57
+ * callers only have to turn `node.schema` into file content. Definitions
58
+ * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
59
+ * code imports goes ungenerated. A ref that fails to resolve is reported via
60
+ * `console.warn` and skipped, matching the generators' prior behavior.
61
+ *
62
+ * Resolution work is memoized per root document (see {@link RootCache}), so
63
+ * running several generators over the same loaded schema does the expensive
64
+ * walking once.
65
+ *
66
+ * @param rootSchema - The root JSON Schema to walk.
67
+ * @param rootTypeName - The name for the root type (e.g. `'Document'`).
68
+ * @param options - Naming options ({@link WalkRefGraphOptions}).
69
+ * @param visit - Called once per output file with a fully prepared {@link RefNode}.
70
+ */
71
+ export const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
72
+ const typeSuffix = options.typeSuffix ?? '';
73
+ const cache = getRootCache(rootSchema);
74
+ const { upgraded, dynamicRefMap } = cache;
75
+ const processedRefs = new Set();
76
+ const processedFilenames = new Set();
77
+ // Root node first — its filename reserves a slot so a later ref that maps to
78
+ // the same name does not emit a duplicate file.
79
+ const rootFilename = rootTypeName.toLowerCase();
80
+ processedFilenames.add(rootFilename);
81
+ visit({
82
+ ref: undefined,
83
+ typeName: rootTypeName,
84
+ filename: rootFilename,
85
+ schema: resolveDynamicRefs(upgraded, dynamicRefMap),
86
+ rootSchema: upgraded,
87
+ isRoot: true,
88
+ });
89
+ const queue = [
90
+ ...cachedExtractRefs(cache, upgraded),
91
+ ...extractDynamicAnchorDefs(upgraded),
92
+ ];
93
+ while (queue.length > 0) {
94
+ const ref = queue.shift();
95
+ if (!ref || processedRefs.has(ref))
96
+ continue;
97
+ processedRefs.add(ref);
98
+ const resolved = cachedResolveRef(cache, ref);
99
+ if (!resolved) {
100
+ console.warn(`Warning: Could not resolve ref: ${ref}`);
101
+ continue;
102
+ }
103
+ const filename = refToFilename(ref);
104
+ if (!processedFilenames.has(filename)) {
105
+ processedFilenames.add(filename);
106
+ visit({
107
+ ref,
108
+ typeName: refToName(ref, typeSuffix),
109
+ filename,
110
+ schema: resolveDynamicRefs(resolved, dynamicRefMap),
111
+ rootSchema: upgraded,
112
+ isRoot: false,
113
+ });
114
+ }
115
+ // Always queue nested refs from the resolved schema, even when its file was
116
+ // a duplicate: two ref strings can share a filename yet reach different
117
+ // sub-definitions (e.g. a URI key and its short-name alias).
118
+ for (const nested of cachedExtractRefs(cache, resolved)) {
119
+ if (!processedRefs.has(nested))
120
+ queue.push(nested);
121
+ }
122
+ }
123
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.6.2",
3
+ "version": "0.7.1",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,99 +27,20 @@
27
27
  "access": "public"
28
28
  },
29
29
  "scripts": {
30
- "build": "bun run build:code && bun run build:types",
31
- "build:code": "bun build ./src/build-dynamic-ref-map.ts ./src/derive-root-type-name.ts ./src/extract-refs.ts ./src/generate-type-definition.ts ./src/has-ref.ts ./src/is-object.ts ./src/mjst-extension.ts ./src/parse-documentation.ts ./src/ref-to-filename.ts ./src/ref-to-name.ts ./src/resolve-dynamic-refs.ts ./src/resolve-ref.ts ./src/safe-accessor.ts ./src/schema-guards.ts ./src/upgrade-draft07-schema.ts ./src/validate-array.ts ./src/validate-record.ts --outdir=dist --root=src --target=node",
32
- "build:types": "tsc -p ."
30
+ "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
31
+ "types:check": "tsgo -p . --noEmit",
32
+ "test": "NODE_ENV=production vitest run --root ../.. helpers"
33
33
  },
34
34
  "dependencies": {
35
35
  "json-schema-typed": "^8.0.1"
36
36
  },
37
37
  "exports": {
38
38
  "./package.json": "./package.json",
39
- "./build-dynamic-ref-map": {
40
- "bun": "./src/build-dynamic-ref-map.ts",
41
- "default": "./dist/build-dynamic-ref-map.js",
42
- "types": "./dist/build-dynamic-ref-map.d.ts"
43
- },
44
- "./derive-root-type-name": {
45
- "bun": "./src/derive-root-type-name.ts",
46
- "default": "./dist/derive-root-type-name.js",
47
- "types": "./dist/derive-root-type-name.d.ts"
48
- },
49
- "./extract-refs": {
50
- "bun": "./src/extract-refs.ts",
51
- "default": "./dist/extract-refs.js",
52
- "types": "./dist/extract-refs.d.ts"
53
- },
54
- "./generate-type-definition": {
55
- "bun": "./src/generate-type-definition.ts",
56
- "default": "./dist/generate-type-definition.js",
57
- "types": "./dist/generate-type-definition.d.ts"
58
- },
59
- "./has-ref": {
60
- "bun": "./src/has-ref.ts",
61
- "default": "./dist/has-ref.js",
62
- "types": "./dist/has-ref.d.ts"
63
- },
64
- "./is-object": {
65
- "bun": "./src/is-object.ts",
66
- "default": "./dist/is-object.js",
67
- "types": "./dist/is-object.d.ts"
68
- },
69
- "./mjst-extension": {
70
- "bun": "./src/mjst-extension.ts",
71
- "default": "./dist/mjst-extension.js",
72
- "types": "./dist/mjst-extension.d.ts"
73
- },
74
- "./parse-documentation": {
75
- "bun": "./src/parse-documentation.ts",
76
- "default": "./dist/parse-documentation.js",
77
- "types": "./dist/parse-documentation.d.ts"
78
- },
79
- "./ref-to-filename": {
80
- "bun": "./src/ref-to-filename.ts",
81
- "default": "./dist/ref-to-filename.js",
82
- "types": "./dist/ref-to-filename.d.ts"
83
- },
84
- "./ref-to-name": {
85
- "bun": "./src/ref-to-name.ts",
86
- "default": "./dist/ref-to-name.js",
87
- "types": "./dist/ref-to-name.d.ts"
88
- },
89
- "./resolve-dynamic-refs": {
90
- "bun": "./src/resolve-dynamic-refs.ts",
91
- "default": "./dist/resolve-dynamic-refs.js",
92
- "types": "./dist/resolve-dynamic-refs.d.ts"
93
- },
94
- "./resolve-ref": {
95
- "bun": "./src/resolve-ref.ts",
96
- "default": "./dist/resolve-ref.js",
97
- "types": "./dist/resolve-ref.d.ts"
98
- },
99
- "./safe-accessor": {
100
- "bun": "./src/safe-accessor.ts",
101
- "default": "./dist/safe-accessor.js",
102
- "types": "./dist/safe-accessor.d.ts"
103
- },
104
- "./schema-guards": {
105
- "bun": "./src/schema-guards.ts",
106
- "default": "./dist/schema-guards.js",
107
- "types": "./dist/schema-guards.d.ts"
108
- },
109
- "./upgrade-draft07-schema": {
110
- "bun": "./src/upgrade-draft07-schema.ts",
111
- "default": "./dist/upgrade-draft07-schema.js",
112
- "types": "./dist/upgrade-draft07-schema.d.ts"
113
- },
114
- "./validate-array": {
115
- "bun": "./src/validate-array.ts",
116
- "default": "./dist/validate-array.js",
117
- "types": "./dist/validate-array.d.ts"
118
- },
119
- "./validate-record": {
120
- "bun": "./src/validate-record.ts",
121
- "default": "./dist/validate-record.js",
122
- "types": "./dist/validate-record.d.ts"
39
+ "./*": {
40
+ "development": "./src/*.ts",
41
+ "import": "./dist/*.js",
42
+ "types": "./dist/*.d.ts",
43
+ "default": "./dist/*.js"
123
44
  }
124
45
  }
125
46
  }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { extractDynamicAnchorDefs } from './extract-dynamic-anchor-defs'
4
+
5
+ describe('extract-dynamic-anchor-defs', () => {
6
+ it('collects refs for every $defs entry with a $dynamicAnchor', () => {
7
+ const schema = {
8
+ $defs: {
9
+ schema: { $dynamicAnchor: 'meta', type: 'object' },
10
+ contact: { type: 'object' },
11
+ node: { $dynamicAnchor: 'node', type: 'string' },
12
+ },
13
+ }
14
+
15
+ expect(extractDynamicAnchorDefs(schema)).toEqual(['#/$defs/schema', '#/$defs/node'])
16
+ })
17
+
18
+ it('returns an empty array when no $defs are present', () => {
19
+ expect(extractDynamicAnchorDefs({ type: 'object' })).toEqual([])
20
+ })
21
+
22
+ it('returns an empty array when no definition has a $dynamicAnchor', () => {
23
+ expect(extractDynamicAnchorDefs({ $defs: { a: { type: 'string' } } })).toEqual([])
24
+ })
25
+
26
+ it('ignores a non-object schema', () => {
27
+ expect(extractDynamicAnchorDefs(true)).toEqual([])
28
+ })
29
+ })
@@ -0,0 +1,33 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
+
3
+ /**
4
+ * Collects `#/$defs/<key>` refs for every root definition that carries a
5
+ * `$dynamicAnchor`.
6
+ *
7
+ * These definitions are reachable only through `$dynamicRef`, which the ref
8
+ * walker does not follow directly (a `$dynamicRef` is rewritten to a concrete
9
+ * `$ref` by `resolveDynamicRefs` *after* the schema is extracted, so plain
10
+ * `extractRefs` never sees it). Seeding them explicitly guarantees a file is
11
+ * generated for each dynamic-anchor target — without this, a generator would
12
+ * emit code that imports a type whose file was never produced.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * // $defs.schema has $dynamicAnchor: "meta"
17
+ * extractDynamicAnchorDefs(rootSchema) // ['#/$defs/schema']
18
+ * ```
19
+ */
20
+ export const extractDynamicAnchorDefs = (schema: JSONSchema): string[] => {
21
+ const refs: string[] = []
22
+
23
+ if (typeof schema !== 'object' || schema === null) return refs
24
+ if (!('$defs' in schema) || typeof schema['$defs'] !== 'object' || schema['$defs'] === null) return refs
25
+
26
+ for (const [key, value] of Object.entries(schema['$defs'])) {
27
+ if (typeof value === 'object' && value !== null && '$dynamicAnchor' in value) {
28
+ refs.push(`#/$defs/${key}`)
29
+ }
30
+ }
31
+
32
+ return refs
33
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { generateIndexBarrel } from './generate-index-barrel'
4
+
5
+ describe('generate-index-barrel', () => {
6
+ it('re-exports types and consts, sorted by filename', () => {
7
+ const files = [
8
+ { filename: 'contact.ts', content: 'export type Contact = {}\nexport const parseContact = () => {}\n' },
9
+ { filename: 'address.ts', content: 'export type Address = {}\nexport const parseAddress = () => {}\n' },
10
+ ]
11
+
12
+ expect(generateIndexBarrel(files)).toBe(
13
+ "export { type Address, parseAddress } from './address';\n" +
14
+ "export { type Contact, parseContact } from './contact';\n",
15
+ )
16
+ })
17
+
18
+ it('emits type-only re-exports when typesOnly is set', () => {
19
+ const files = [{ filename: 'contact.ts', content: 'export type Contact = {}\n' }]
20
+
21
+ expect(generateIndexBarrel(files, { typesOnly: true })).toBe("export type { Contact } from './contact';\n")
22
+ })
23
+
24
+ it('never re-exports internal _helpers modules', () => {
25
+ const files = [
26
+ { filename: 'document.ts', content: 'export type Document = {}\n' },
27
+ { filename: '_helpers/is-object.ts', content: 'export const isObject = () => {}\n' },
28
+ ]
29
+
30
+ expect(generateIndexBarrel(files)).toBe("export { type Document } from './document';\n")
31
+ })
32
+
33
+ it('skips files that export nothing', () => {
34
+ const files = [
35
+ { filename: 'document.ts', content: 'export type Document = {}\n' },
36
+ { filename: 'empty.ts', content: '// nothing here\n' },
37
+ ]
38
+
39
+ expect(generateIndexBarrel(files)).toBe("export { type Document } from './document';\n")
40
+ })
41
+ })
@@ -0,0 +1,62 @@
1
+ /** A generated file: its name (with extension) and TypeScript source. */
2
+ export type IndexBarrelFile = {
3
+ filename: string
4
+ content: string
5
+ }
6
+
7
+ /** Options controlling how the barrel re-exports each module. */
8
+ export type GenerateIndexBarrelOptions = {
9
+ /**
10
+ * When true, every re-export is type-only (`export type { ... }`). Used by the
11
+ * types-only parser output, where no runtime values exist to re-export.
12
+ * Defaults to `false`.
13
+ */
14
+ readonly typesOnly?: boolean
15
+ }
16
+
17
+ // Generated files declare their public surface with these two forms, so we can
18
+ // recover the export names from the source text without parsing it.
19
+ const TYPE_EXPORT_RE = /^export type (\w+)/gm
20
+ const CONST_EXPORT_RE = /^export const (\w+)/gm
21
+
22
+ /**
23
+ * Builds the `index.ts` barrel that re-exports every generated module. This is
24
+ * the shared version of the near-identical barrel each generator used to build
25
+ * inline: it scans each file's source for `export type` / `export const`
26
+ * declarations and emits one re-export line per module, sorted by filename.
27
+ *
28
+ * Files under `_helpers/` are internal runtime helpers (embedded-mode output)
29
+ * and are never re-exported. Modules that expose nothing are skipped.
30
+ *
31
+ * @param files - The generated files to barrel (the `index.ts` itself excluded).
32
+ * @param options - See {@link GenerateIndexBarrelOptions}.
33
+ * @returns The `index.ts` file content.
34
+ */
35
+ export const generateIndexBarrel = (files: IndexBarrelFile[], options: GenerateIndexBarrelOptions = {}): string => {
36
+ const typesOnly = options.typesOnly ?? false
37
+
38
+ const sortedFiles = files
39
+ .filter((file) => !file.filename.startsWith('_helpers/'))
40
+ .sort((a, b) => a.filename.localeCompare(b.filename))
41
+
42
+ let indexContent = ''
43
+ for (const file of sortedFiles) {
44
+ const moduleName = file.filename.replace(/\.ts$/, '')
45
+ const typeNames: string[] = []
46
+ const constNames: string[] = []
47
+
48
+ for (const match of file.content.matchAll(TYPE_EXPORT_RE)) typeNames.push(match[1] as string)
49
+ for (const match of file.content.matchAll(CONST_EXPORT_RE)) constNames.push(match[1] as string)
50
+
51
+ if (typeNames.length === 0 && constNames.length === 0) continue
52
+
53
+ if (typesOnly) {
54
+ indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}';\n`
55
+ } else {
56
+ const typeExports = typeNames.map((name) => `type ${name}`)
57
+ indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}';\n`
58
+ }
59
+ }
60
+
61
+ return indexContent
62
+ }
@@ -0,0 +1,118 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+
3
+ import { type RefNode, walkRefGraph } from './walk-ref-graph'
4
+
5
+ /** Collects every visited node so a test can assert what the walker produced. */
6
+ const collect = (rootSchema: Parameters<typeof walkRefGraph>[0], rootTypeName: string, typeSuffix = ''): RefNode[] => {
7
+ const nodes: RefNode[] = []
8
+ walkRefGraph(rootSchema, rootTypeName, { typeSuffix }, (node) => nodes.push(node))
9
+ return nodes
10
+ }
11
+
12
+ describe('walk-ref-graph', () => {
13
+ it('visits the root first, then each referenced definition', () => {
14
+ const schema = {
15
+ type: 'object',
16
+ properties: { contact: { $ref: '#/$defs/contact' } },
17
+ $defs: { contact: { type: 'object', properties: { email: { type: 'string' } } } },
18
+ }
19
+
20
+ const nodes = collect(schema, 'Document')
21
+
22
+ expect(nodes.map((n) => ({ ref: n.ref, typeName: n.typeName, filename: n.filename, isRoot: n.isRoot }))).toEqual([
23
+ { ref: undefined, typeName: 'Document', filename: 'document', isRoot: true },
24
+ { ref: '#/$defs/contact', typeName: 'Contact', filename: 'contact', isRoot: false },
25
+ ])
26
+ })
27
+
28
+ it('follows nested refs breadth-first and resolves each schema', () => {
29
+ const schema = {
30
+ properties: { user: { $ref: '#/$defs/user' } },
31
+ $defs: {
32
+ user: { type: 'object', properties: { address: { $ref: '#/$defs/address' } } },
33
+ address: { type: 'object', properties: { city: { type: 'string' } } },
34
+ },
35
+ }
36
+
37
+ const nodes = collect(schema, 'Document')
38
+
39
+ expect(nodes.map((n) => n.filename)).toEqual(['document', 'user', 'address'])
40
+ expect(nodes[2]?.schema).toEqual({ type: 'object', properties: { city: { type: 'string' } } })
41
+ })
42
+
43
+ it('applies the type suffix to ref-derived names but not the root', () => {
44
+ const schema = { properties: { contact: { $ref: '#/$defs/contact' } }, $defs: { contact: { type: 'object' } } }
45
+
46
+ const nodes = collect(schema, 'Document', 'Object')
47
+
48
+ expect(nodes.map((n) => n.typeName)).toEqual(['Document', 'ContactObject'])
49
+ })
50
+
51
+ it('does not visit two refs that map to the same filename twice', () => {
52
+ // A URI key and its short-name alias both resolve to the same definition and
53
+ // share a filename, so only one file should be emitted.
54
+ const schema = {
55
+ allOf: [{ $ref: 'http://example.com/channel.json' }, { $ref: '#/$defs/channel' }],
56
+ $defs: {
57
+ 'http://example.com/channel.json': { type: 'object' },
58
+ channel: { type: 'object' },
59
+ },
60
+ }
61
+
62
+ const filenames = collect(schema, 'Document').map((n) => n.filename)
63
+ expect(filenames.filter((f) => f === 'channel')).toHaveLength(1)
64
+ })
65
+
66
+ it('seeds $dynamicAnchor definitions and rewrites $dynamicRef to $ref', () => {
67
+ const schema = {
68
+ type: 'object',
69
+ properties: { payload: { $dynamicRef: '#meta' } },
70
+ $defs: { schema: { $dynamicAnchor: 'meta', type: 'object' } },
71
+ }
72
+
73
+ const nodes = collect(schema, 'Document')
74
+
75
+ // The dynamic-anchor target gets its own file even though no plain $ref points at it...
76
+ expect(nodes.map((n) => n.filename)).toContain('schema')
77
+ // ...and the $dynamicRef on the root is rewritten to a concrete $ref.
78
+ const root = nodes.find((n) => n.isRoot)
79
+ expect(root?.schema).toMatchObject({ properties: { payload: { $ref: '#/$defs/schema' } } })
80
+ })
81
+
82
+ it('warns and skips a ref that cannot be resolved', () => {
83
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
84
+ const schema = { properties: { missing: { $ref: '#/$defs/nope' } }, $defs: {} }
85
+
86
+ const nodes = collect(schema, 'Document')
87
+
88
+ expect(nodes.map((n) => n.filename)).toEqual(['document'])
89
+ expect(warn).toHaveBeenCalledWith('Warning: Could not resolve ref: #/$defs/nope')
90
+ warn.mockRestore()
91
+ })
92
+
93
+ it('handles circular refs (A → B → A) without infinite looping', () => {
94
+ const schema = {
95
+ properties: { root: { $ref: '#/$defs/a' } },
96
+ $defs: {
97
+ a: { type: 'object', properties: { b: { $ref: '#/$defs/b' } } },
98
+ b: { type: 'object', properties: { a: { $ref: '#/$defs/a' } } },
99
+ },
100
+ }
101
+
102
+ const nodes = collect(schema, 'Document')
103
+
104
+ // Both defs are visited exactly once each despite the cycle.
105
+ expect(nodes.map((n) => n.filename)).toEqual(['document', 'a', 'b'])
106
+ })
107
+
108
+ it('reuses cached resolution across repeated walks of the same schema object', () => {
109
+ // The second walk should produce the same nodes from the per-root cache,
110
+ // proving the cache does not corrupt or drop results on reuse.
111
+ const schema = { properties: { contact: { $ref: '#/$defs/contact' } }, $defs: { contact: { type: 'object' } } }
112
+
113
+ const first = collect(schema, 'Document').map((n) => n.filename)
114
+ const second = collect(schema, 'Document').map((n) => n.filename)
115
+
116
+ expect(second).toEqual(first)
117
+ })
118
+ })