@amritk/helpers 0.13.2 → 0.13.4

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.
package/AI.md ADDED
@@ -0,0 +1,40 @@
1
+ # @amritk/helpers — notes for AI coding agents
2
+
3
+ Shared schema-traversal, codegen, and runtime utilities for the mjst ecosystem,
4
+ each published as its own subpath so consumers import only what they need. Full
5
+ reference is [README.md](./README.md).
6
+
7
+ > Pre-alpha: internal ecosystem package — most users never import it directly.
8
+ > APIs change in **minor** versions.
9
+
10
+ ## Minimal example
11
+
12
+ ```ts
13
+ import { resolveRef } from '@amritk/helpers/resolve-ref'
14
+ import { isObjectSchema, hasProperties } from '@amritk/helpers/schema-guards'
15
+
16
+ const node = resolveRef('#/$defs/info', rootSchema) // (ref, root); undefined on miss
17
+
18
+ if (node && isObjectSchema(node) && hasProperties(node)) {
19
+ for (const [name, property] of Object.entries(node.properties)) {
20
+ // …
21
+ }
22
+ }
23
+ ```
24
+
25
+ ## Gotchas — where agents fail
26
+
27
+ 1. **No barrel — import per subpath.** `@amritk/helpers/resolve-ref`, NOT
28
+ `@amritk/helpers`. The subpath is the exact kebab-case filename with no `.ts`.
29
+ 2. **`resolveRef(ref, rootSchema)`** takes the ref first, root second, handles
30
+ JSON-pointer `$ref`s only, and returns `undefined` on a miss (no throw) —
31
+ guard the result.
32
+ 3. **Two similar guards:** `isSchemaObject` narrows to a non-boolean schema;
33
+ `isObjectSchema` narrows to a `type: object` schema. Don't confuse them.
34
+ 4. **Some modules are copied verbatim into generated output** (`is-object`,
35
+ `safe-accessor`, `validate-array`, `validate-record`) — intentionally
36
+ dependency-free and minimal, not general-purpose validators.
37
+
38
+ Notable subpaths: `/resolve-ref`, `/extract-refs`, `/schema-guards`,
39
+ `/ref-to-name`, `/ref-to-filename`, `/upgrade-draft07-schema`,
40
+ `/generate-type-definition`, `/is-object`. Install: `bun add @amritk/helpers`.
@@ -1,55 +1,32 @@
1
- import { isSchemaObject } from './schema-guards.js';
2
- /** Escapes a JSON Pointer segment (RFC 6901): `~` → `~0`, `/` → `~1`. */
3
- const escapeSegment = (segment) => segment.indexOf('~') !== -1 || segment.indexOf('/') !== -1
4
- ? segment.replace(/~/g, '~0').replace(/\//g, '~1')
5
- : segment;
6
- // Keywords whose values are data, not subschemas — a `$dynamicAnchor` key inside
7
- // an enum member or example value is instance data and must not register.
8
- const NON_SCHEMA_KEYWORDS = new Set(['enum', 'const', 'default', 'examples']);
9
- /**
10
- * Builds a map of $dynamicRef anchor values to their corresponding $ref paths.
11
- *
12
- * JSON Schema 2020-12 uses $dynamicAnchor and $dynamicRef for late-binding references.
13
- * In the OpenAPI spec, $dynamicAnchor: "meta" on the schema definition allows properties
14
- * like media-type.schema to reference it via $dynamicRef: "#meta".
15
- *
16
- * The whole document is scanned — a `$dynamicAnchor` may sit anywhere, not just
17
- * on a direct `$defs` entry — and each anchor maps to the JSON Pointer of the
18
- * subschema that declares it. When the same anchor name appears more than once,
19
- * the first occurrence in document order wins, matching how the resolvers bind
20
- * a name to a single document-global target.
21
- *
22
- * @example
23
- * // Given a schema with $defs.schema having $dynamicAnchor: "meta"
24
- * buildDynamicRefMap(rootSchema)
25
- * // Returns: { "#meta": "#/$defs/schema" }
26
- */
27
- export const buildDynamicRefMap = (rootSchema) => {
28
- const map = {};
29
- if (!isSchemaObject(rootSchema))
30
- return map;
31
- const walk = (node, pointer) => {
32
- if (node === null || typeof node !== 'object')
33
- return;
34
- if (Array.isArray(node)) {
35
- for (let i = 0; i < node.length; i++)
36
- walk(node[i], `${pointer}/${i}`);
37
- return;
38
- }
39
- const record = node;
40
- const anchor = record['$dynamicAnchor'];
41
- // The document root is skipped: mapping it would rewrite `$dynamicRef` to
42
- // `$ref: "#"`, a self-reference the file-per-definition generators cannot
43
- // name an output file for. Every nested subschema gets a real pointer.
44
- if (pointer !== '' && typeof anchor === 'string' && !(`#${anchor}` in map)) {
45
- map[`#${anchor}`] = `#${pointer}`;
46
- }
47
- for (const key of Object.keys(record)) {
48
- if (NON_SCHEMA_KEYWORDS.has(key))
49
- continue;
50
- walk(record[key], `${pointer}/${escapeSegment(key)}`);
51
- }
52
- };
53
- walk(rootSchema, '');
1
+ import { isSchemaObject } from "./schema-guards.js";
2
+ const escapeSegment = (segment) => segment.indexOf("~") !== -1 || segment.indexOf("/") !== -1 ? segment.replace(/~/g, "~0").replace(/\//g, "~1") : segment;
3
+ const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
4
+ const buildDynamicRefMap = (rootSchema) => {
5
+ const map = {};
6
+ if (!isSchemaObject(rootSchema))
54
7
  return map;
8
+ const walk = (node, pointer) => {
9
+ if (node === null || typeof node !== "object")
10
+ return;
11
+ if (Array.isArray(node)) {
12
+ for (let i = 0; i < node.length; i++)
13
+ walk(node[i], `${pointer}/${i}`);
14
+ return;
15
+ }
16
+ const record = node;
17
+ const anchor = record["$dynamicAnchor"];
18
+ if (pointer !== "" && typeof anchor === "string" && !(`#${anchor}` in map)) {
19
+ map[`#${anchor}`] = `#${pointer}`;
20
+ }
21
+ for (const key of Object.keys(record)) {
22
+ if (NON_SCHEMA_KEYWORDS.has(key))
23
+ continue;
24
+ walk(record[key], `${pointer}/${escapeSegment(key)}`);
25
+ }
26
+ };
27
+ walk(rootSchema, "");
28
+ return map;
29
+ };
30
+ export {
31
+ buildDynamicRefMap
55
32
  };
@@ -1,52 +1,22 @@
1
- import { isObject } from './is-object.js';
2
- /**
3
- * Converts an arbitrary title string into a PascalCase TypeScript identifier.
4
- * Splits on any run of non-alphanumeric characters, capitalizes the first
5
- * letter of each word while preserving the rest (so acronyms like "API" or
6
- * "JSON" survive intact), and drops leading digits since an identifier may not
7
- * start with a number.
8
- */
1
+ import { isObject } from "./is-object.js";
9
2
  const titleToPascalCase = (title) => {
10
- const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean);
11
- const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('');
12
- return pascal.replace(/^\d+/, '');
3
+ const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean);
4
+ const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
5
+ return pascal.replace(/^\d+/, "");
13
6
  };
14
- /**
15
- * Derives the root type name for a generated schema.
16
- *
17
- * We name the root after the schema itself instead of a generic "Document" so
18
- * the generated types and parsers read naturally (e.g. an OpenAPI schema yields
19
- * `OpenApi` / `parseOpenApi`, and a `spec-plan.json` file yields `SpecPlan` /
20
- * `parseSpecPlan`). The schema's `title` keyword wins when present; otherwise
21
- * the caller can supply the schema's filename (without extension) as a
22
- * `fallbackName` so the name still reflects the source. When neither yields a
23
- * usable identifier we fall back to "Document" to keep output deterministic.
24
- *
25
- * @param schema - The root JSON Schema. A boolean schema or one without a
26
- * string `title` uses `fallbackName`.
27
- * @param fallbackName - Optional name (typically the schema's base filename)
28
- * used when the schema has no usable `title`. PascalCased the same way.
29
- * @returns A PascalCase type name derived from the title or fallback, or
30
- * "Document".
31
- *
32
- * @example
33
- * ```ts
34
- * deriveRootTypeName({ title: 'OpenAPI Document' }) // 'OpenAPIDocument'
35
- * deriveRootTypeName({ title: 'my-config' }) // 'MyConfig'
36
- * deriveRootTypeName({ type: 'object' }, 'spec-plan') // 'SpecPlan'
37
- * deriveRootTypeName({ type: 'object' }) // 'Document'
38
- * ```
39
- */
40
- export const deriveRootTypeName = (schema, fallbackName) => {
41
- if (isObject(schema) && typeof schema['title'] === 'string') {
42
- const fromTitle = titleToPascalCase(schema['title']);
43
- if (fromTitle)
44
- return fromTitle;
45
- }
46
- if (typeof fallbackName === 'string') {
47
- const fromFilename = titleToPascalCase(fallbackName);
48
- if (fromFilename)
49
- return fromFilename;
50
- }
51
- return 'Document';
7
+ const deriveRootTypeName = (schema, fallbackName) => {
8
+ if (isObject(schema) && typeof schema["title"] === "string") {
9
+ const fromTitle = titleToPascalCase(schema["title"]);
10
+ if (fromTitle)
11
+ return fromTitle;
12
+ }
13
+ if (typeof fallbackName === "string") {
14
+ const fromFilename = titleToPascalCase(fallbackName);
15
+ if (fromFilename)
16
+ return fromFilename;
17
+ }
18
+ return "Document";
19
+ };
20
+ export {
21
+ deriveRootTypeName
52
22
  };
@@ -1,83 +1,42 @@
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
1
  const lineTerminatorEscapes = {
29
- 10: '\\n', // LF
30
- 13: '\\r', // CR
31
- 8232: '\\u2028', // LINE SEPARATOR
32
- 8233: '\\u2029', // PARAGRAPH SEPARATOR
2
+ 10: "\\n",
3
+ // LF
4
+ 13: "\\r",
5
+ // CR
6
+ 8232: "\\u2028",
7
+ // LINE SEPARATOR
8
+ 8233: "\\u2029"
9
+ // PARAGRAPH SEPARATOR
33
10
  };
34
- // Memoized results: the same schema pattern is escaped once per parser, per
35
- // validator, and per assertion context, on every generation — and the dominant
36
- // cost is the validating `new RegExp` compile. Schemas carry a bounded set of
37
- // patterns; the cap only guards a pathological long-lived process.
38
- const escapeCache = new Map();
39
- const ESCAPE_CACHE_LIMIT = 1000;
40
- export const escapeRegexPattern = (pattern) => {
41
- const cached = escapeCache.get(pattern);
42
- if (cached !== undefined)
43
- return cached;
44
- // Validate at generation time — an invalid pattern must fail here, not emit
45
- // a `/([/` literal that breaks the generated file.
46
- try {
47
- new RegExp(pattern);
48
- }
49
- catch (error) {
50
- throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
51
- }
52
- // Match either an escape sequence (`\` + any char, kept verbatim) or a single
53
- // character that would corrupt the literal (a bare `/` or a line terminator).
54
- // The line terminators are written as `\u….` escapes so this source file is
55
- // itself free of the raw characters it guards against. Consuming escape pairs
56
- // first means the slash in `\/` is never seen as bare, so it is not
57
- // double-escaped.
58
- const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
59
- if (match === '/')
60
- return '\\/';
61
- const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
62
- if (terminatorEscape !== undefined && match.length === 1)
63
- return terminatorEscape;
64
- // An escape pair like `\/` or `\d`: keep exactly as authored.
65
- return match;
66
- });
67
- // The empty pattern is valid JSON Schema (it matches everything), but an empty
68
- // regex body would emit `//` \u2014 a line comment, not a literal \u2014 and break the
69
- // generated file. Emit `(?:)` instead, exactly what `new RegExp('').source`
70
- // yields: an empty non-capturing group that still matches everything.
71
- if (escaped === '') {
72
- escapeCache.set(pattern, '(?:)');
73
- return '(?:)';
74
- }
75
- if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
76
- // Evict the single oldest entry (Maps iterate in insertion order) instead
77
- // of clearing wholesale — a corpus slightly over the limit keeps its hot
78
- // set instead of collapsing to a 0% hit rate every pass.
79
- escapeCache.delete(escapeCache.keys().next().value);
80
- }
81
- escapeCache.set(pattern, escaped);
82
- return escaped;
11
+ const escapeCache = /* @__PURE__ */ new Map();
12
+ const ESCAPE_CACHE_LIMIT = 1e3;
13
+ const escapeRegexPattern = (pattern) => {
14
+ const cached = escapeCache.get(pattern);
15
+ if (cached !== void 0)
16
+ return cached;
17
+ try {
18
+ new RegExp(pattern);
19
+ } catch (error) {
20
+ throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
21
+ }
22
+ const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
23
+ if (match === "/")
24
+ return "\\/";
25
+ const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
26
+ if (terminatorEscape !== void 0 && match.length === 1)
27
+ return terminatorEscape;
28
+ return match;
29
+ });
30
+ if (escaped === "") {
31
+ escapeCache.set(pattern, "(?:)");
32
+ return "(?:)";
33
+ }
34
+ if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
35
+ escapeCache.delete(escapeCache.keys().next().value);
36
+ }
37
+ escapeCache.set(pattern, escaped);
38
+ return escaped;
39
+ };
40
+ export {
41
+ escapeRegexPattern
83
42
  };
@@ -1,22 +1,5 @@
1
- import { buildDynamicRefMap } from './build-dynamic-ref-map.js';
2
- /**
3
- * Collects a `#/...` ref for every subschema in the document that carries a
4
- * `$dynamicAnchor` — anywhere in the tree, not just direct `$defs` entries.
5
- *
6
- * These definitions are reachable only through `$dynamicRef`, which the ref
7
- * walker does not follow directly (a `$dynamicRef` is rewritten to a concrete
8
- * `$ref` by `resolveDynamicRefs` *after* the schema is extracted, so plain
9
- * `extractRefs` never sees it). Seeding them explicitly guarantees a file is
10
- * generated for each dynamic-anchor target — without this, a generator would
11
- * emit code that imports a type whose file was never produced.
12
- *
13
- * Delegates to {@link buildDynamicRefMap} so the set of seeded refs and the
14
- * `$dynamicRef` rewrite targets can never disagree.
15
- *
16
- * @example
17
- * ```ts
18
- * // $defs.schema has $dynamicAnchor: "meta"
19
- * extractDynamicAnchorDefs(rootSchema) // ['#/$defs/schema']
20
- * ```
21
- */
22
- export const extractDynamicAnchorDefs = (schema) => Object.values(buildDynamicRefMap(schema));
1
+ import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
2
+ const extractDynamicAnchorDefs = (schema) => Object.values(buildDynamicRefMap(schema));
3
+ export {
4
+ extractDynamicAnchorDefs
5
+ };
@@ -1,67 +1,35 @@
1
- /**
2
- * Returns true if a $ref value should be queued for processing.
3
- *
4
- * Accepted forms:
5
- * - Internal: `#/$defs/foo` or `#/definitions/foo`
6
- * - URI key: `http://example.com/foo.json` (no fragment, or empty fragment)
7
- * - URI with fragment: `http://example.com/foo.json#/definitions/bar`
8
- *
9
- * Excluded:
10
- * - `#` alone (self-reference, not a standalone definition)
11
- * - Relative path refs (e.g. `/components/messages/foo`) — these point into
12
- * example data in the schema document, not into type definitions
13
- */
14
1
  const isResolvableRef = (ref) => {
15
- if (ref === '#')
16
- return false;
17
- if (ref.startsWith('#'))
18
- return true;
19
- if (ref.startsWith('http://') || ref.startsWith('https://'))
20
- return true;
2
+ if (ref === "#")
21
3
  return false;
4
+ if (ref.startsWith("#"))
5
+ return true;
6
+ if (ref.startsWith("http://") || ref.startsWith("https://"))
7
+ return true;
8
+ return false;
22
9
  };
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) => {
45
- const refs = new Set();
46
- const traverse = (obj) => {
47
- if (typeof obj !== 'object' || obj === null) {
48
- return;
49
- }
50
- if (Array.isArray(obj)) {
51
- for (const item of obj) {
52
- traverse(item);
53
- }
54
- return;
55
- }
56
- const record = obj;
57
- if ('$ref' in record && typeof record['$ref'] === 'string' && isResolvableRef(record['$ref'])) {
58
- refs.add(record['$ref']);
59
- }
60
- // Recursively traverse all properties using for...in to avoid intermediate array allocation
61
- for (const key in record) {
62
- traverse(record[key]);
63
- }
64
- };
65
- traverse(schema);
66
- return refs;
10
+ const extractRefs = (schema) => {
11
+ const refs = /* @__PURE__ */ new Set();
12
+ const traverse = (obj) => {
13
+ if (typeof obj !== "object" || obj === null) {
14
+ return;
15
+ }
16
+ if (Array.isArray(obj)) {
17
+ for (const item of obj) {
18
+ traverse(item);
19
+ }
20
+ return;
21
+ }
22
+ const record = obj;
23
+ if ("$ref" in record && typeof record["$ref"] === "string" && isResolvableRef(record["$ref"])) {
24
+ refs.add(record["$ref"]);
25
+ }
26
+ for (const key in record) {
27
+ traverse(record[key]);
28
+ }
29
+ };
30
+ traverse(schema);
31
+ return refs;
32
+ };
33
+ export {
34
+ extractRefs
67
35
  };
@@ -1,92 +1,61 @@
1
- // Generated files declare their public surface with `export type <Name>` /
2
- // `export const <Name>` at line starts, so the names can be recovered from the
3
- // source text without parsing it.
4
- /** Reads the identifier following `prefix` when `content` starts with it at `at`. */
5
1
  const exportNameAt = (content, at, prefix) => {
6
- if (!content.startsWith(prefix, at))
7
- return null;
8
- let end = at + prefix.length;
9
- while (end < content.length) {
10
- const code = content.charCodeAt(end);
11
- const isWord = (code >= 97 && code <= 122) || (code >= 65 && code <= 90) || (code >= 48 && code <= 57) || code === 95;
12
- if (!isWord)
13
- break;
14
- end++;
15
- }
16
- return end > at + prefix.length ? content.slice(at + prefix.length, end) : null;
2
+ if (!content.startsWith(prefix, at))
3
+ return null;
4
+ let end = at + prefix.length;
5
+ while (end < content.length) {
6
+ const code = content.charCodeAt(end);
7
+ const isWord = code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
8
+ if (!isWord)
9
+ break;
10
+ end++;
11
+ }
12
+ return end > at + prefix.length ? content.slice(at + prefix.length, end) : null;
17
13
  };
18
- /** True for every JS LineTerminator code unit — the same set the old `/m` regexes anchored after. */
19
14
  const isLineTerminator = (code) => code === 10 || code === 13 || code === 8232 || code === 8233;
20
- /**
21
- * Collects `export type` / `export const` names with a single line-start walk.
22
- * A multiline-anchored regex scan (`/^export .../gm`) does the same job but
23
- * showed up at several percent of total generation time in CPU profiles — the
24
- * regex engine re-anchors at every line of every generated file on every build.
25
- */
26
15
  const collectExportNames = (content, typeNames, constNames) => {
27
- let lineStart = 0;
28
- while (lineStart < content.length) {
29
- // charCode prefilter: almost every line starts with whitespace, a brace, or
30
- // a keyword other than `export` — one integer compare skips the substring
31
- // comparison for all of them (101 === 'e').
32
- if (content.charCodeAt(lineStart) === 101 && content.startsWith('export ', lineStart)) {
33
- const typeName = exportNameAt(content, lineStart, 'export type ');
34
- if (typeName !== null) {
35
- typeNames.push(typeName);
36
- }
37
- else {
38
- const constName = exportNameAt(content, lineStart, 'export const ');
39
- if (constName !== null)
40
- constNames.push(constName);
41
- }
42
- }
43
- // Advance past the next line break of ANY JS flavor (LF, CR, CRLF,
44
- // U+2028, U+2029) — matching the multiline regexes this walk replaced,
45
- // which treated all of them as line starts.
46
- let next = lineStart;
47
- while (next < content.length && !isLineTerminator(content.charCodeAt(next)))
48
- next++;
49
- if (next >= content.length)
50
- break;
51
- // \r\n counts as one break.
52
- lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1;
16
+ let lineStart = 0;
17
+ while (lineStart < content.length) {
18
+ if (content.charCodeAt(lineStart) === 101 && content.startsWith("export ", lineStart)) {
19
+ const typeName = exportNameAt(content, lineStart, "export type ");
20
+ if (typeName !== null) {
21
+ typeNames.push(typeName);
22
+ } else {
23
+ const constName = exportNameAt(content, lineStart, "export const ");
24
+ if (constName !== null)
25
+ constNames.push(constName);
26
+ }
53
27
  }
28
+ let next = lineStart;
29
+ while (next < content.length && !isLineTerminator(content.charCodeAt(next)))
30
+ next++;
31
+ if (next >= content.length)
32
+ break;
33
+ lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1;
34
+ }
54
35
  };
55
- /**
56
- * Builds the `index.ts` barrel that re-exports every generated module. This is
57
- * the shared version of the near-identical barrel each generator used to build
58
- * inline: it scans each file's source for `export type` / `export const`
59
- * declarations and emits one re-export line per module, sorted by filename.
60
- *
61
- * Files under `_helpers/` are internal runtime helpers (embedded-mode output)
62
- * and are never re-exported. Modules that expose nothing are skipped.
63
- *
64
- * @param files - The generated files to barrel (the `index.ts` itself excluded).
65
- * @param options - See {@link GenerateIndexBarrelOptions}.
66
- * @returns The `index.ts` file content.
67
- */
68
- export const generateIndexBarrel = (files, options = {}) => {
69
- const typesOnly = options.typesOnly ?? false;
70
- const importExt = options.importExt ?? 'js';
71
- const sortedFiles = files
72
- .filter((file) => !file.filename.startsWith('_helpers/'))
73
- .sort((a, b) => a.filename.localeCompare(b.filename));
74
- let indexContent = '';
75
- for (const file of sortedFiles) {
76
- const moduleName = file.filename.replace(/\.ts$/, '');
77
- const typeNames = [];
78
- const constNames = [];
79
- collectExportNames(file.content, typeNames, constNames);
80
- if (typeNames.length === 0 && constNames.length === 0)
81
- continue;
82
- // An explicit extension so the barrel resolves under Node ESM, not only Bun.
83
- if (typesOnly) {
84
- indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.${importExt}';\n`;
85
- }
86
- else {
87
- const typeExports = typeNames.map((name) => `type ${name}`);
88
- indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.${importExt}';\n`;
89
- }
36
+ const generateIndexBarrel = (files, options = {}) => {
37
+ const typesOnly = options.typesOnly ?? false;
38
+ const importExt = options.importExt ?? "js";
39
+ const sortedFiles = files.filter((file) => !file.filename.startsWith("_helpers/")).sort((a, b) => a.filename.localeCompare(b.filename));
40
+ let indexContent = "";
41
+ for (const file of sortedFiles) {
42
+ const moduleName = file.filename.replace(/\.ts$/, "");
43
+ const typeNames = [];
44
+ const constNames = [];
45
+ collectExportNames(file.content, typeNames, constNames);
46
+ if (typeNames.length === 0 && constNames.length === 0)
47
+ continue;
48
+ if (typesOnly) {
49
+ indexContent += `export type { ${typeNames.join(", ")} } from './${moduleName}.${importExt}';
50
+ `;
51
+ } else {
52
+ const typeExports = typeNames.map((name) => `type ${name}`);
53
+ indexContent += `export { ${[...typeExports, ...constNames].join(", ")} } from './${moduleName}.${importExt}';
54
+ `;
90
55
  }
91
- return indexContent;
56
+ }
57
+ return indexContent;
58
+ };
59
+ export {
60
+ generateIndexBarrel
92
61
  };