@amritk/helpers 0.14.0 → 0.15.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 (65) hide show
  1. package/AI.md +13 -5
  2. package/README.md +4 -1
  3. package/dist/assert-id-scopes.d.ts +20 -0
  4. package/dist/assert-id-scopes.js +45 -0
  5. package/dist/build-anchor-map.d.ts +26 -0
  6. package/dist/build-anchor-map.js +35 -0
  7. package/dist/build-dynamic-ref-map.d.ts +8 -0
  8. package/dist/build-dynamic-ref-map.js +7 -5
  9. package/dist/build-resource-registry.d.ts +88 -0
  10. package/dist/build-resource-registry.js +90 -0
  11. package/dist/escape-regex-pattern.d.ts +27 -0
  12. package/dist/escape-regex-pattern.js +21 -1
  13. package/dist/extract-refs.js +6 -4
  14. package/dist/generate-index-barrel.js +13 -6
  15. package/dist/generate-type-definition.js +1 -4
  16. package/dist/graft-external-schemas.d.ts +83 -0
  17. package/dist/graft-external-schemas.js +70 -0
  18. package/dist/max-schema-depth.d.ts +22 -0
  19. package/dist/max-schema-depth.js +10 -0
  20. package/dist/mjst-extension.d.ts +4 -2
  21. package/dist/mjst-extension.js +11 -2
  22. package/dist/multiple-of-check.d.ts +31 -0
  23. package/dist/multiple-of-check.js +6 -10
  24. package/dist/normalize-ref-scopes.d.ts +29 -0
  25. package/dist/normalize-ref-scopes.js +53 -0
  26. package/dist/prune-external-schemas.d.ts +16 -0
  27. package/dist/prune-external-schemas.js +80 -0
  28. package/dist/ref-to-filename.d.ts +1 -0
  29. package/dist/ref-to-filename.js +19 -3
  30. package/dist/ref-to-name.js +7 -4
  31. package/dist/resolve-dynamic-refs.d.ts +10 -0
  32. package/dist/resolve-dynamic-refs.js +18 -16
  33. package/dist/resolve-ref.d.ts +4 -2
  34. package/dist/resolve-ref.js +32 -6
  35. package/dist/resolve-scoped-ref.d.ts +35 -0
  36. package/dist/resolve-scoped-ref.js +35 -0
  37. package/dist/safe-accessor.d.ts +38 -1
  38. package/dist/safe-accessor.js +15 -0
  39. package/dist/string-length-check.d.ts +8 -0
  40. package/dist/string-length-check.js +23 -0
  41. package/dist/upgrade-draft07-schema.js +9 -6
  42. package/dist/walk-ref-graph.d.ts +38 -3
  43. package/dist/walk-ref-graph.js +170 -23
  44. package/package.json +13 -3
  45. package/src/build-dynamic-ref-map.ts +0 -61
  46. package/src/derive-root-type-name.ts +0 -54
  47. package/src/escape-regex-pattern.ts +0 -87
  48. package/src/extract-dynamic-anchor-defs.ts +0 -25
  49. package/src/extract-refs.ts +0 -73
  50. package/src/fold-nullable.ts +0 -60
  51. package/src/generate-index-barrel.ts +0 -118
  52. package/src/generate-type-definition.ts +0 -784
  53. package/src/mjst-extension.ts +0 -81
  54. package/src/multiple-of-check.ts +0 -32
  55. package/src/parse-documentation.ts +0 -177
  56. package/src/quote-js-string.ts +0 -20
  57. package/src/ref-to-filename.ts +0 -116
  58. package/src/ref-to-name.ts +0 -54
  59. package/src/resolve-dynamic-refs.ts +0 -74
  60. package/src/resolve-ref.ts +0 -82
  61. package/src/safe-accessor.ts +0 -53
  62. package/src/schema-guards.ts +0 -234
  63. package/src/unknown-key-check.ts +0 -68
  64. package/src/upgrade-draft07-schema.ts +0 -179
  65. package/src/walk-ref-graph.ts +0 -257
@@ -1,54 +0,0 @@
1
- import { isObject } from './is-object'
2
-
3
- /**
4
- * Converts an arbitrary title string into a PascalCase TypeScript identifier.
5
- * Splits on any run of non-alphanumeric characters, capitalizes the first
6
- * letter of each word while preserving the rest (so acronyms like "API" or
7
- * "JSON" survive intact), and drops leading digits since an identifier may not
8
- * start with a number.
9
- */
10
- const titleToPascalCase = (title: string): string => {
11
- const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean)
12
- const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('')
13
- return pascal.replace(/^\d+/, '')
14
- }
15
-
16
- /**
17
- * Derives the root type name for a generated schema.
18
- *
19
- * We name the root after the schema itself instead of a generic "Document" so
20
- * the generated types and parsers read naturally (e.g. an OpenAPI schema yields
21
- * `OpenApi` / `parseOpenApi`, and a `spec-plan.json` file yields `SpecPlan` /
22
- * `parseSpecPlan`). The schema's `title` keyword wins when present; otherwise
23
- * the caller can supply the schema's filename (without extension) as a
24
- * `fallbackName` so the name still reflects the source. When neither yields a
25
- * usable identifier we fall back to "Document" to keep output deterministic.
26
- *
27
- * @param schema - The root JSON Schema. A boolean schema or one without a
28
- * string `title` uses `fallbackName`.
29
- * @param fallbackName - Optional name (typically the schema's base filename)
30
- * used when the schema has no usable `title`. PascalCased the same way.
31
- * @returns A PascalCase type name derived from the title or fallback, or
32
- * "Document".
33
- *
34
- * @example
35
- * ```ts
36
- * deriveRootTypeName({ title: 'OpenAPI Document' }) // 'OpenAPIDocument'
37
- * deriveRootTypeName({ title: 'my-config' }) // 'MyConfig'
38
- * deriveRootTypeName({ type: 'object' }, 'spec-plan') // 'SpecPlan'
39
- * deriveRootTypeName({ type: 'object' }) // 'Document'
40
- * ```
41
- */
42
- export const deriveRootTypeName = (schema: unknown, fallbackName?: string): string => {
43
- if (isObject(schema) && typeof schema['title'] === 'string') {
44
- const fromTitle = titleToPascalCase(schema['title'])
45
- if (fromTitle) return fromTitle
46
- }
47
-
48
- if (typeof fallbackName === 'string') {
49
- const fromFilename = titleToPascalCase(fallbackName)
50
- if (fromFilename) return fromFilename
51
- }
52
-
53
- return 'Document'
54
- }
@@ -1,87 +0,0 @@
1
- /**
2
- * Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
3
- * a generated regex literal (`/…/`), and validates that the pattern is a legal
4
- * regex at generation time.
5
- *
6
- * A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
7
- * regex literal — not a string literal — so backslashes are regex syntax and
8
- * must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
9
- * digit" to "a literal backslash followed by d"). Two things would otherwise
10
- * corrupt the surrounding literal:
11
- * - an *unescaped* `/`, which would close the literal early; and
12
- * - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
13
- * inside a regex literal and would split the emitted `/…/` across lines (a
14
- * syntax error). Each is rewritten to its backslash escape, which matches
15
- * the identical character, so the regex's meaning is unchanged.
16
- *
17
- * Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
18
- * `/([/…` and produce output that does not parse. We compile the pattern with
19
- * `new RegExp` here and throw a clear generator-time error instead, so a bad
20
- * schema fails loudly during generation rather than emitting broken code.
21
- *
22
- * @example
23
- * escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
24
- * @throws if `pattern` is not a valid regular expression.
25
- */
26
- // Line terminators, keyed by code point, and the backslash escape each maps to.
27
- // These are the four characters disallowed *raw* inside a regex literal.
28
- const lineTerminatorEscapes: Record<number, string> = {
29
- 10: '\\n', // LF
30
- 13: '\\r', // CR
31
- 8232: '\\u2028', // LINE SEPARATOR
32
- 8233: '\\u2029', // PARAGRAPH SEPARATOR
33
- }
34
-
35
- // Memoized results: the same schema pattern is escaped once per parser, per
36
- // validator, and per assertion context, on every generation — and the dominant
37
- // cost is the validating `new RegExp` compile. Schemas carry a bounded set of
38
- // patterns; the cap only guards a pathological long-lived process.
39
- const escapeCache = new Map<string, string>()
40
- const ESCAPE_CACHE_LIMIT = 1000
41
-
42
- export const escapeRegexPattern = (pattern: string): string => {
43
- const cached = escapeCache.get(pattern)
44
- if (cached !== undefined) return cached
45
-
46
- // Validate at generation time — an invalid pattern must fail here, not emit
47
- // a `/([/` literal that breaks the generated file.
48
- try {
49
- new RegExp(pattern)
50
- } catch (error) {
51
- throw new Error(
52
- `Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`,
53
- )
54
- }
55
-
56
- // Match either an escape sequence (`\` + any char, kept verbatim) or a single
57
- // character that would corrupt the literal (a bare `/` or a line terminator).
58
- // The line terminators are written as `\u….` escapes so this source file is
59
- // itself free of the raw characters it guards against. Consuming escape pairs
60
- // first means the slash in `\/` is never seen as bare, so it is not
61
- // double-escaped.
62
- const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
63
- if (match === '/') return '\\/'
64
- const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)]
65
- if (terminatorEscape !== undefined && match.length === 1) return terminatorEscape
66
- // An escape pair like `\/` or `\d`: keep exactly as authored.
67
- return match
68
- })
69
-
70
- // The empty pattern is valid JSON Schema (it matches everything), but an empty
71
- // regex body would emit `//` \u2014 a line comment, not a literal \u2014 and break the
72
- // generated file. Emit `(?:)` instead, exactly what `new RegExp('').source`
73
- // yields: an empty non-capturing group that still matches everything.
74
- if (escaped === '') {
75
- escapeCache.set(pattern, '(?:)')
76
- return '(?:)'
77
- }
78
-
79
- if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
80
- // Evict the single oldest entry (Maps iterate in insertion order) instead
81
- // of clearing wholesale — a corpus slightly over the limit keeps its hot
82
- // set instead of collapsing to a 0% hit rate every pass.
83
- escapeCache.delete(escapeCache.keys().next().value as string)
84
- }
85
- escapeCache.set(pattern, escaped)
86
- return escaped
87
- }
@@ -1,25 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- import { buildDynamicRefMap } from './build-dynamic-ref-map'
4
-
5
- /**
6
- * Collects a `#/...` ref for every subschema in the document that carries a
7
- * `$dynamicAnchor` — anywhere in the tree, not just direct `$defs` entries.
8
- *
9
- * These definitions are reachable only through `$dynamicRef`, which the ref
10
- * walker does not follow directly (a `$dynamicRef` is rewritten to a concrete
11
- * `$ref` by `resolveDynamicRefs` *after* the schema is extracted, so plain
12
- * `extractRefs` never sees it). Seeding them explicitly guarantees a file is
13
- * generated for each dynamic-anchor target — without this, a generator would
14
- * emit code that imports a type whose file was never produced.
15
- *
16
- * Delegates to {@link buildDynamicRefMap} so the set of seeded refs and the
17
- * `$dynamicRef` rewrite targets can never disagree.
18
- *
19
- * @example
20
- * ```ts
21
- * // $defs.schema has $dynamicAnchor: "meta"
22
- * extractDynamicAnchorDefs(rootSchema) // ['#/$defs/schema']
23
- * ```
24
- */
25
- export const extractDynamicAnchorDefs = (schema: JSONSchema): string[] => Object.values(buildDynamicRefMap(schema))
@@ -1,73 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- /**
4
- * Returns true if a $ref value should be queued for processing.
5
- *
6
- * Accepted forms:
7
- * - Internal: `#/$defs/foo` or `#/definitions/foo`
8
- * - URI key: `http://example.com/foo.json` (no fragment, or empty fragment)
9
- * - URI with fragment: `http://example.com/foo.json#/definitions/bar`
10
- *
11
- * Excluded:
12
- * - `#` alone (self-reference, not a standalone definition)
13
- * - Relative path refs (e.g. `/components/messages/foo`) — these point into
14
- * example data in the schema document, not into type definitions
15
- */
16
- const isResolvableRef = (ref: string): boolean => {
17
- if (ref === '#') return false
18
- if (ref.startsWith('#')) return true
19
- if (ref.startsWith('http://') || ref.startsWith('https://')) return true
20
- return false
21
- }
22
-
23
- /**
24
- * Extracts all $ref values from a JSON Schema recursively.
25
- * Returns both internal (`#`-prefixed) and URI refs so the build pipeline
26
- * can resolve and generate files for all referenced definitions.
27
- *
28
- * @param schema - The JSON Schema to extract refs from
29
- * @returns A Set of unique ref strings found in the schema
30
- *
31
- * @example
32
- * ```ts
33
- * const schema = {
34
- * type: 'object',
35
- * properties: {
36
- * contact: { $ref: '#/$defs/contact' },
37
- * channel: { $ref: 'http://example.com/channel.json' },
38
- * }
39
- * }
40
- * const refs = extractRefs(schema)
41
- * // refs = Set(['#/$defs/contact', 'http://example.com/channel.json'])
42
- * ```
43
- */
44
- export const extractRefs = (schema: JSONSchema): Set<string> => {
45
- const refs = new Set<string>()
46
-
47
- const traverse = (obj: unknown): void => {
48
- if (typeof obj !== 'object' || obj === null) {
49
- return
50
- }
51
-
52
- if (Array.isArray(obj)) {
53
- for (const item of obj) {
54
- traverse(item)
55
- }
56
- return
57
- }
58
-
59
- const record = obj as Record<string, unknown>
60
-
61
- if ('$ref' in record && typeof record['$ref'] === 'string' && isResolvableRef(record['$ref'] as string)) {
62
- refs.add(record['$ref'] as string)
63
- }
64
-
65
- // Recursively traverse all properties using for...in to avoid intermediate array allocation
66
- for (const key in record) {
67
- traverse(record[key])
68
- }
69
- }
70
-
71
- traverse(schema)
72
- return refs
73
- }
@@ -1,60 +0,0 @@
1
- /**
2
- * Rewrites OpenAPI 3.0's `nullable: true` into the JSON Schema form the
3
- * generators already enforce: a `null` member of the node's `type`.
4
- *
5
- * OpenAPI 3.0 has no `type: [...]` — it spells "or null" as a sibling boolean.
6
- * Every generator here reads `type`, so an unfolded document produced parsers
7
- * that rejected `null` outright (strict) or coerced it to a default (non-strict)
8
- * while the schema declared it valid. Folding once, at the document level, means
9
- * no downstream path needs to know the keyword exists.
10
- *
11
- * A node with `nullable: true` but no `type` is left alone: there is no type
12
- * list to extend, and OpenAPI 3.0 ignores keywords alongside a `$ref` anyway.
13
- * The `nullable` key itself is kept so the type generator can still widen the
14
- * emitted TypeScript with `| null`.
15
- *
16
- * Returns the input unchanged (same reference) when the document contains no
17
- * `nullable: true`, so the common case allocates nothing.
18
- */
19
- export const foldNullable = <T>(schema: T): T => {
20
- const folded = fold(schema)
21
- return folded as T
22
- }
23
-
24
- const fold = (node: unknown): unknown => {
25
- if (Array.isArray(node)) {
26
- let changed = false
27
- const next = node.map((item) => {
28
- const folded = fold(item)
29
- if (folded !== item) changed = true
30
- return folded
31
- })
32
- return changed ? next : node
33
- }
34
-
35
- if (typeof node !== 'object' || node === null) return node
36
-
37
- const record = node as Record<string, unknown>
38
- let changed = false
39
- const next: Record<string, unknown> = {}
40
-
41
- for (const key in record) {
42
- const value = record[key]
43
- const folded = fold(value)
44
- if (folded !== value) changed = true
45
- next[key] = folded
46
- }
47
-
48
- const type = record['type']
49
- if (record['nullable'] === true) {
50
- if (typeof type === 'string' && type !== 'null') {
51
- next['type'] = [type, 'null']
52
- changed = true
53
- } else if (Array.isArray(type) && !type.includes('null')) {
54
- next['type'] = [...type, 'null']
55
- changed = true
56
- }
57
- }
58
-
59
- return changed ? next : node
60
- }
@@ -1,118 +0,0 @@
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
- * Extension used on every relative re-export specifier. `'js'` (default) is
17
- * the standard TS NodeNext form (`./x.js` resolving to a sibling `x.ts`);
18
- * `'ts'` emits the literal on-disk path so the output runs directly under
19
- * Node's type stripping.
20
- */
21
- readonly importExt?: 'js' | 'ts'
22
- }
23
-
24
- // Generated files declare their public surface with `export type <Name>` /
25
- // `export const <Name>` at line starts, so the names can be recovered from the
26
- // source text without parsing it.
27
-
28
- /** Reads the identifier following `prefix` when `content` starts with it at `at`. */
29
- const exportNameAt = (content: string, at: number, prefix: string): string | null => {
30
- if (!content.startsWith(prefix, at)) return null
31
- let end = at + prefix.length
32
- while (end < content.length) {
33
- const code = content.charCodeAt(end)
34
- const isWord =
35
- (code >= 97 && code <= 122) || (code >= 65 && code <= 90) || (code >= 48 && code <= 57) || code === 95
36
- if (!isWord) break
37
- end++
38
- }
39
- return end > at + prefix.length ? content.slice(at + prefix.length, end) : null
40
- }
41
-
42
- /** True for every JS LineTerminator code unit — the same set the old `/m` regexes anchored after. */
43
- const isLineTerminator = (code: number): boolean => code === 10 || code === 13 || code === 8232 || code === 8233
44
-
45
- /**
46
- * Collects `export type` / `export const` names with a single line-start walk.
47
- * A multiline-anchored regex scan (`/^export .../gm`) does the same job but
48
- * showed up at several percent of total generation time in CPU profiles — the
49
- * regex engine re-anchors at every line of every generated file on every build.
50
- */
51
- const collectExportNames = (content: string, typeNames: string[], constNames: string[]): void => {
52
- let lineStart = 0
53
- while (lineStart < content.length) {
54
- // charCode prefilter: almost every line starts with whitespace, a brace, or
55
- // a keyword other than `export` — one integer compare skips the substring
56
- // comparison for all of them (101 === 'e').
57
- if (content.charCodeAt(lineStart) === 101 && content.startsWith('export ', lineStart)) {
58
- const typeName = exportNameAt(content, lineStart, 'export type ')
59
- if (typeName !== null) {
60
- typeNames.push(typeName)
61
- } else {
62
- const constName = exportNameAt(content, lineStart, 'export const ')
63
- if (constName !== null) constNames.push(constName)
64
- }
65
- }
66
- // Advance past the next line break of ANY JS flavor (LF, CR, CRLF,
67
- // U+2028, U+2029) — matching the multiline regexes this walk replaced,
68
- // which treated all of them as line starts.
69
- let next = lineStart
70
- while (next < content.length && !isLineTerminator(content.charCodeAt(next))) next++
71
- if (next >= content.length) break
72
- // \r\n counts as one break.
73
- lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1
74
- }
75
- }
76
-
77
- /**
78
- * Builds the `index.ts` barrel that re-exports every generated module. This is
79
- * the shared version of the near-identical barrel each generator used to build
80
- * inline: it scans each file's source for `export type` / `export const`
81
- * declarations and emits one re-export line per module, sorted by filename.
82
- *
83
- * Files under `_helpers/` are internal runtime helpers (embedded-mode output)
84
- * and are never re-exported. Modules that expose nothing are skipped.
85
- *
86
- * @param files - The generated files to barrel (the `index.ts` itself excluded).
87
- * @param options - See {@link GenerateIndexBarrelOptions}.
88
- * @returns The `index.ts` file content.
89
- */
90
- export const generateIndexBarrel = (files: IndexBarrelFile[], options: GenerateIndexBarrelOptions = {}): string => {
91
- const typesOnly = options.typesOnly ?? false
92
- const importExt = options.importExt ?? 'js'
93
-
94
- const sortedFiles = files
95
- .filter((file) => !file.filename.startsWith('_helpers/'))
96
- .sort((a, b) => a.filename.localeCompare(b.filename))
97
-
98
- let indexContent = ''
99
- for (const file of sortedFiles) {
100
- const moduleName = file.filename.replace(/\.ts$/, '')
101
- const typeNames: string[] = []
102
- const constNames: string[] = []
103
-
104
- collectExportNames(file.content, typeNames, constNames)
105
-
106
- if (typeNames.length === 0 && constNames.length === 0) continue
107
-
108
- // An explicit extension so the barrel resolves under Node ESM, not only Bun.
109
- if (typesOnly) {
110
- indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.${importExt}';\n`
111
- } else {
112
- const typeExports = typeNames.map((name) => `type ${name}`)
113
- indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.${importExt}';\n`
114
- }
115
- }
116
-
117
- return indexContent
118
- }