@type-bridge/node 1.5.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.
@@ -0,0 +1,67 @@
1
+ import type { Annotation } from "./index.js";
2
+ /**
3
+ * How a model class name is converted to its TypeDB type name when no explicit
4
+ * name is given. Mirrors the Python `TypeNameCase`: `CLASS_NAME` keeps the class
5
+ * name as-is, `LOWERCASE` lowercases it, `SNAKE_CASE` converts to snake_case.
6
+ */
7
+ export declare enum TypeNameCase {
8
+ LOWERCASE = "lowercase",
9
+ CLASS_NAME = "classname",
10
+ SNAKE_CASE = "snake_case"
11
+ }
12
+ export interface TypeFlagsOptions {
13
+ name?: string | null;
14
+ abstract?: boolean;
15
+ base?: boolean;
16
+ case?: TypeNameCase;
17
+ }
18
+ export interface ResolvedTypeFlags {
19
+ readonly name: string | null;
20
+ readonly abstract: boolean;
21
+ readonly base: boolean;
22
+ readonly case: TypeNameCase;
23
+ }
24
+ export interface AttributeFlagsOptions {
25
+ name?: string | null;
26
+ case?: TypeNameCase | null;
27
+ }
28
+ export interface ResolvedAttributeFlags {
29
+ readonly name: string | null;
30
+ readonly case: TypeNameCase | null;
31
+ }
32
+ export interface CardSpec<Min extends number = number, Max extends number | null = number | null> {
33
+ readonly kind: "card";
34
+ readonly min: Min;
35
+ readonly max: Max;
36
+ }
37
+ export interface FlagSpec {
38
+ readonly kind: "flag";
39
+ readonly annotations: Annotation[];
40
+ readonly cardinality: [number, number | null] | null;
41
+ readonly isOrdered: boolean;
42
+ readonly isDistinct: boolean;
43
+ }
44
+ /** Marks a field as the type's key attribute (implies cardinality `[1, 1]`). */
45
+ export declare const Key = "Key";
46
+ /** Marks a field's attribute value as unique across the type. */
47
+ export declare const Unique = "Unique";
48
+ /** Declares this owns clause as a list attribute (`owns attr[]`). Schema-only. */
49
+ export declare const Ordered = "Ordered";
50
+ /** Emits `@distinct` on the owns clause. Requires `Ordered`. Schema-only. */
51
+ export declare const Distinct = "Distinct";
52
+ export type FlagInput = typeof Key | typeof Unique | typeof Ordered | typeof Distinct | CardSpec | FlagSpec;
53
+ /** Type-level config for an `Entity`/`Relation` (explicit name, abstract, base, case). */
54
+ export declare function TypeFlags(options?: TypeFlagsOptions): ResolvedTypeFlags;
55
+ /** Attribute-level config: an explicit attribute name and/or case override. */
56
+ export declare function AttributeFlags(options?: AttributeFlagsOptions): ResolvedAttributeFlags;
57
+ /** A cardinality bound `[min, max]`. Omitting `max` means unbounded (`[min, null]`). */
58
+ export declare function Card<const Min extends number, const Max extends number | null = null>(min: Min, max?: Max): CardSpec<Min, Max>;
59
+ /**
60
+ * Combine flags (`Key`, `Unique`, `Card(...)`) for one field into a resolved set
61
+ * of descriptor annotations plus a derived cardinality.
62
+ */
63
+ export declare function Flag(...flags: FlagInput[]): FlagSpec;
64
+ /** Lower a flag list to its `{ annotations, cardinality, isOrdered, isDistinct }` descriptor form. */
65
+ export declare function resolveFlags(flags: readonly FlagInput[]): FlagSpec;
66
+ /** Convert a model class name to its TypeDB type name under the given case. */
67
+ export declare function formatTypeName(className: string, typeCase: TypeNameCase): string;
package/dist/flags.js ADDED
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Distinct = exports.Ordered = exports.Unique = exports.Key = exports.TypeNameCase = void 0;
4
+ exports.TypeFlags = TypeFlags;
5
+ exports.AttributeFlags = AttributeFlags;
6
+ exports.Card = Card;
7
+ exports.Flag = Flag;
8
+ exports.resolveFlags = resolveFlags;
9
+ exports.formatTypeName = formatTypeName;
10
+ /**
11
+ * How a model class name is converted to its TypeDB type name when no explicit
12
+ * name is given. Mirrors the Python `TypeNameCase`: `CLASS_NAME` keeps the class
13
+ * name as-is, `LOWERCASE` lowercases it, `SNAKE_CASE` converts to snake_case.
14
+ */
15
+ var TypeNameCase;
16
+ (function (TypeNameCase) {
17
+ TypeNameCase["LOWERCASE"] = "lowercase";
18
+ TypeNameCase["CLASS_NAME"] = "classname";
19
+ TypeNameCase["SNAKE_CASE"] = "snake_case";
20
+ })(TypeNameCase || (exports.TypeNameCase = TypeNameCase = {}));
21
+ /** Marks a field as the type's key attribute (implies cardinality `[1, 1]`). */
22
+ exports.Key = "Key";
23
+ /** Marks a field's attribute value as unique across the type. */
24
+ exports.Unique = "Unique";
25
+ /** Declares this owns clause as a list attribute (`owns attr[]`). Schema-only. */
26
+ exports.Ordered = "Ordered";
27
+ /** Emits `@distinct` on the owns clause. Requires `Ordered`. Schema-only. */
28
+ exports.Distinct = "Distinct";
29
+ /** Type-level config for an `Entity`/`Relation` (explicit name, abstract, base, case). */
30
+ function TypeFlags(options = {}) {
31
+ return {
32
+ name: options.name ?? null,
33
+ abstract: options.abstract ?? false,
34
+ base: options.base ?? false,
35
+ case: options.case ?? TypeNameCase.CLASS_NAME,
36
+ };
37
+ }
38
+ /** Attribute-level config: an explicit attribute name and/or case override. */
39
+ function AttributeFlags(options = {}) {
40
+ return {
41
+ name: options.name ?? null,
42
+ case: options.case ?? null,
43
+ };
44
+ }
45
+ /** A cardinality bound `[min, max]`. Omitting `max` means unbounded (`[min, null]`). */
46
+ function Card(min, max) {
47
+ return {
48
+ kind: "card",
49
+ min,
50
+ max: (max ?? null),
51
+ };
52
+ }
53
+ /**
54
+ * Combine flags (`Key`, `Unique`, `Card(...)`) for one field into a resolved set
55
+ * of descriptor annotations plus a derived cardinality.
56
+ */
57
+ function Flag(...flags) {
58
+ return resolveFlags(flags);
59
+ }
60
+ /** Lower a flag list to its `{ annotations, cardinality, isOrdered, isDistinct }` descriptor form. */
61
+ function resolveFlags(flags) {
62
+ const annotations = [];
63
+ let cardinality = null;
64
+ let isOrdered = false;
65
+ let isDistinct = false;
66
+ for (const flag of flags) {
67
+ if (isFlagSpec(flag)) {
68
+ annotations.push(...flag.annotations);
69
+ cardinality = flag.cardinality ?? cardinality;
70
+ isOrdered = isOrdered || flag.isOrdered;
71
+ isDistinct = isDistinct || flag.isDistinct;
72
+ continue;
73
+ }
74
+ if (flag === exports.Key) {
75
+ annotations.push("Key");
76
+ cardinality = [1, 1];
77
+ continue;
78
+ }
79
+ if (flag === exports.Unique) {
80
+ annotations.push("Unique");
81
+ continue;
82
+ }
83
+ if (flag === exports.Ordered) {
84
+ isOrdered = true;
85
+ continue;
86
+ }
87
+ if (flag === exports.Distinct) {
88
+ isDistinct = true;
89
+ continue;
90
+ }
91
+ if (isCardSpec(flag)) {
92
+ const card = [flag.min, flag.max];
93
+ annotations.push({ Card: card });
94
+ cardinality = card;
95
+ }
96
+ }
97
+ if (isDistinct && !isOrdered) {
98
+ throw new TypeError("Flag(Distinct) requires Flag(Ordered): @distinct is only valid on a list attribute (owns attr[]).");
99
+ }
100
+ return { kind: "flag", annotations, cardinality, isOrdered, isDistinct };
101
+ }
102
+ /** Convert a model class name to its TypeDB type name under the given case. */
103
+ function formatTypeName(className, typeCase) {
104
+ if (typeCase === TypeNameCase.CLASS_NAME) {
105
+ return className;
106
+ }
107
+ if (typeCase === TypeNameCase.SNAKE_CASE) {
108
+ return toSnakeCase(className);
109
+ }
110
+ return className.toLowerCase();
111
+ }
112
+ function toSnakeCase(name) {
113
+ return name
114
+ .replace(/(.)([A-Z][a-z]+)/g, "$1_$2")
115
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
116
+ .toLowerCase();
117
+ }
118
+ function isCardSpec(flag) {
119
+ return typeof flag === "object" && flag !== null && flag.kind === "card";
120
+ }
121
+ function isFlagSpec(flag) {
122
+ return typeof flag === "object" && flag !== null && flag.kind === "flag";
123
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Shared cardinality predicate helpers for TypeScript code generation.
3
+ *
4
+ * Used by both renderEntities.ts and renderRelations.ts. Each predicate
5
+ * mirrors the corresponding Python `Cardinality` property in models.py.
6
+ */
7
+ import type { Cardinality } from "../parser.js";
8
+ /** True if at most one value is allowed (max === 1). */
9
+ export declare function isCardSingle(c: Cardinality): boolean;
10
+ /** True if at least one value is required (min >= 1). */
11
+ export declare function isCardRequired(c: Cardinality): boolean;
12
+ /** True if multiple values are allowed (max === null || max > 1). */
13
+ export declare function isCardMulti(c: Cardinality): boolean;
14
+ /** True if zero or one value (min === 0, max === 1) — the optional-single case. */
15
+ export declare function isCardOptionalSingle(c: Cardinality): boolean;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * Shared cardinality predicate helpers for TypeScript code generation.
4
+ *
5
+ * Used by both renderEntities.ts and renderRelations.ts. Each predicate
6
+ * mirrors the corresponding Python `Cardinality` property in models.py.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.isCardSingle = isCardSingle;
10
+ exports.isCardRequired = isCardRequired;
11
+ exports.isCardMulti = isCardMulti;
12
+ exports.isCardOptionalSingle = isCardOptionalSingle;
13
+ /** True if at most one value is allowed (max === 1). */
14
+ function isCardSingle(c) {
15
+ return c.max === 1;
16
+ }
17
+ /** True if at least one value is required (min >= 1). */
18
+ function isCardRequired(c) {
19
+ return c.min >= 1;
20
+ }
21
+ /** True if multiple values are allowed (max === null || max > 1). */
22
+ function isCardMulti(c) {
23
+ return c.max === null || c.max > 1;
24
+ }
25
+ /** True if zero or one value (min === 0, max === 1) — the optional-single case. */
26
+ function isCardOptionalSingle(c) {
27
+ return c.min === 0 && c.max === 1;
28
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * TypeScript model generator — the `generate_models()` twin.
3
+ *
4
+ * Mirrors `type_bridge/generator/__init__.py` → `generate_models()`.
5
+ * Consumes a parsed `TypeSchema` (via `parseSchema`) and writes the typed
6
+ * `.ts` surface to a caller-supplied output directory.
7
+ *
8
+ * The native module is INJECTED (not self-resolved) — callers load the native
9
+ * module via the package root's `loadNative()` and pass the `SchemaParserNative`
10
+ * slice in `options.native`. This keeps the generator free of any native-resolution
11
+ * path, so it survives the package layout change.
12
+ *
13
+ * Generated files import from `@type-bridge/node` (package entrypoint), never
14
+ * from a hardcoded relative path, so they are valid across packaging layout changes.
15
+ *
16
+ * Build-time code generation; no runtime ORM logic.
17
+ */
18
+ import { type SchemaParserNative } from "../parser.js";
19
+ import type { NamingOptions } from "./naming.js";
20
+ /** Options for `generateModels`. */
21
+ export interface GenerateModelsOptions extends NamingOptions {
22
+ /**
23
+ * The native module slice providing `parseSchemaJson`. Callers obtain this
24
+ * from the package root's `loadNative()` return value. Required — the
25
+ * generator does not self-load the native module.
26
+ */
27
+ native: SchemaParserNative;
28
+ }
29
+ /**
30
+ * Generate the typed TypeScript model surface from a TQL `define` block.
31
+ *
32
+ * Mirrors Python `generate_models(tql, output_dir, implicit_key_attributes=...)`.
33
+ *
34
+ * Writes `attributes.ts`, `entities.ts`, `relations.ts`, and `index.ts`
35
+ * (package barrel) to `outputDir`.
36
+ *
37
+ * @param tql - TQL schema string (a `define` block).
38
+ * @param outputDir - Directory to write the generated `.ts` files into.
39
+ * Created if absent. Passed by the caller; the generator
40
+ * does not enforce a specific location.
41
+ * @param options - `native` (required) + optional `implicitKeyAttributes`.
42
+ */
43
+ export declare function generateModels(tql: string, outputDir: string, options: GenerateModelsOptions): void;
44
+ export { toClassName, toFieldName, type NamingOptions } from "./naming.js";
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript model generator — the `generate_models()` twin.
4
+ *
5
+ * Mirrors `type_bridge/generator/__init__.py` → `generate_models()`.
6
+ * Consumes a parsed `TypeSchema` (via `parseSchema`) and writes the typed
7
+ * `.ts` surface to a caller-supplied output directory.
8
+ *
9
+ * The native module is INJECTED (not self-resolved) — callers load the native
10
+ * module via the package root's `loadNative()` and pass the `SchemaParserNative`
11
+ * slice in `options.native`. This keeps the generator free of any native-resolution
12
+ * path, so it survives the package layout change.
13
+ *
14
+ * Generated files import from `@type-bridge/node` (package entrypoint), never
15
+ * from a hardcoded relative path, so they are valid across packaging layout changes.
16
+ *
17
+ * Build-time code generation; no runtime ORM logic.
18
+ */
19
+ var __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.toFieldName = exports.toClassName = void 0;
24
+ exports.generateModels = generateModels;
25
+ const node_fs_1 = __importDefault(require("node:fs"));
26
+ const node_path_1 = __importDefault(require("node:path"));
27
+ const parser_js_1 = require("../parser.js");
28
+ const renderAttributes_js_1 = require("./renderAttributes.js");
29
+ const renderEntities_js_1 = require("./renderEntities.js");
30
+ const renderRelations_js_1 = require("./renderRelations.js");
31
+ const renderPackage_js_1 = require("./renderPackage.js");
32
+ /**
33
+ * Generate the typed TypeScript model surface from a TQL `define` block.
34
+ *
35
+ * Mirrors Python `generate_models(tql, output_dir, implicit_key_attributes=...)`.
36
+ *
37
+ * Writes `attributes.ts`, `entities.ts`, `relations.ts`, and `index.ts`
38
+ * (package barrel) to `outputDir`.
39
+ *
40
+ * @param tql - TQL schema string (a `define` block).
41
+ * @param outputDir - Directory to write the generated `.ts` files into.
42
+ * Created if absent. Passed by the caller; the generator
43
+ * does not enforce a specific location.
44
+ * @param options - `native` (required) + optional `implicitKeyAttributes`.
45
+ */
46
+ function generateModels(tql, outputDir, options) {
47
+ // Parse: TQL string → fully-resolved TypeSchema (Rust-backed, via NAPI)
48
+ const schema = (0, parser_js_1.parseSchema)(tql, options.native);
49
+ // Render
50
+ const attrSource = (0, renderAttributes_js_1.renderAttributes)(schema);
51
+ const entitySource = (0, renderEntities_js_1.renderEntities)(schema, options);
52
+ const relationSource = (0, renderRelations_js_1.renderRelations)(schema, options);
53
+ const packageSource = (0, renderPackage_js_1.renderPackage)(schema);
54
+ // Write
55
+ node_fs_1.default.mkdirSync(outputDir, { recursive: true });
56
+ node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "attributes.ts"), attrSource, "utf-8");
57
+ node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "entities.ts"), entitySource, "utf-8");
58
+ node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "relations.ts"), relationSource, "utf-8");
59
+ node_fs_1.default.writeFileSync(node_path_1.default.join(outputDir, "index.ts"), packageSource, "utf-8");
60
+ }
61
+ // Re-export the naming utilities and options type for callers that need them
62
+ var naming_js_1 = require("./naming.js");
63
+ Object.defineProperty(exports, "toClassName", { enumerable: true, get: function () { return naming_js_1.toClassName; } });
64
+ Object.defineProperty(exports, "toFieldName", { enumerable: true, get: function () { return naming_js_1.toFieldName; } });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Naming convention utilities for TypeScript code generation.
3
+ *
4
+ * Mirrors `type_bridge/generator/naming.py` exactly so that the TS generator
5
+ * and the Python generator apply identical naming policy to the same schema and
6
+ * produce cross-language-parity descriptors.
7
+ *
8
+ * Build-time code generation; no runtime ORM logic. The RUNTIME facade is a
9
+ * separate marshalling-only layer; this module does not touch it.
10
+ */
11
+ /**
12
+ * Convert a TypeDB type name to PascalCase for TypeScript class names.
13
+ *
14
+ * Mirrors Python `to_class_name`:
15
+ * `"".join(part.capitalize() for part in label.replace("_","-").split("-"))`
16
+ *
17
+ * `capitalize()` upper-cases the FIRST character and LOWER-CASES the rest —
18
+ * equivalent to `p[0].toUpperCase() + p.slice(1).toLowerCase()` in JS.
19
+ *
20
+ * Examples:
21
+ * "person" -> "Person"
22
+ * "isbn-13" -> "Isbn13"
23
+ * "order-line" -> "OrderLine"
24
+ * "user_story" -> "UserStory"
25
+ * "login_at" -> "LoginAt"
26
+ * "parity-tag" -> "ParityTag"
27
+ * "URL" -> "Url" (proves lower-casing of the rest)
28
+ */
29
+ export declare function toClassName(label: string): string;
30
+ /**
31
+ * Convert a TypeDB attribute name to a snake_case field key.
32
+ *
33
+ * Mirrors Python `to_python_name`:
34
+ * `label.replace("-", "_")`
35
+ *
36
+ * Kebab-to-snake only. Prefix is KEPT; no pluralization; no stripping.
37
+ *
38
+ * Examples:
39
+ * "parity-id" -> "parity_id"
40
+ * "parity-tag" -> "parity_tag" (singular — no pluralization)
41
+ * "parity-birth-date" -> "parity_birth_date"
42
+ * "isbn-13" -> "isbn_13"
43
+ * "order-line" -> "order_line"
44
+ */
45
+ export declare function toFieldName(label: string): string;
46
+ /**
47
+ * Options controlling key-inference policy, mirroring
48
+ * `generate_models(... implicit_key_attributes=...)`.
49
+ *
50
+ * An attribute whose name is listed in `implicitKeyAttributes` is emitted with
51
+ * `field(Attr, Key)` unless the schema already marks it `@key` (schema key always
52
+ * wins — implicit key never downgrades a schema key).
53
+ */
54
+ export interface NamingOptions {
55
+ /** Attribute names to treat as keys even when the schema has no `@key`. */
56
+ implicitKeyAttributes?: string[];
57
+ }
58
+ /**
59
+ * Return true when `attrName` should be emitted as a Key field.
60
+ *
61
+ * Schema `is_key` always wins. `implicitKeyAttributes` adds key-ness only for
62
+ * attributes NOT already marked by the schema — it never downgrades a schema key.
63
+ */
64
+ export declare function isKeyAttribute(attrName: string, isSchemaKey: boolean, options?: NamingOptions): boolean;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * Naming convention utilities for TypeScript code generation.
4
+ *
5
+ * Mirrors `type_bridge/generator/naming.py` exactly so that the TS generator
6
+ * and the Python generator apply identical naming policy to the same schema and
7
+ * produce cross-language-parity descriptors.
8
+ *
9
+ * Build-time code generation; no runtime ORM logic. The RUNTIME facade is a
10
+ * separate marshalling-only layer; this module does not touch it.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.toClassName = toClassName;
14
+ exports.toFieldName = toFieldName;
15
+ exports.isKeyAttribute = isKeyAttribute;
16
+ /**
17
+ * Convert a TypeDB type name to PascalCase for TypeScript class names.
18
+ *
19
+ * Mirrors Python `to_class_name`:
20
+ * `"".join(part.capitalize() for part in label.replace("_","-").split("-"))`
21
+ *
22
+ * `capitalize()` upper-cases the FIRST character and LOWER-CASES the rest —
23
+ * equivalent to `p[0].toUpperCase() + p.slice(1).toLowerCase()` in JS.
24
+ *
25
+ * Examples:
26
+ * "person" -> "Person"
27
+ * "isbn-13" -> "Isbn13"
28
+ * "order-line" -> "OrderLine"
29
+ * "user_story" -> "UserStory"
30
+ * "login_at" -> "LoginAt"
31
+ * "parity-tag" -> "ParityTag"
32
+ * "URL" -> "Url" (proves lower-casing of the rest)
33
+ */
34
+ function toClassName(label) {
35
+ return label
36
+ .replace(/_/g, "-")
37
+ .split("-")
38
+ .map((part) => (part.length === 0 ? "" : part[0].toUpperCase() + part.slice(1).toLowerCase()))
39
+ .join("");
40
+ }
41
+ /**
42
+ * Convert a TypeDB attribute name to a snake_case field key.
43
+ *
44
+ * Mirrors Python `to_python_name`:
45
+ * `label.replace("-", "_")`
46
+ *
47
+ * Kebab-to-snake only. Prefix is KEPT; no pluralization; no stripping.
48
+ *
49
+ * Examples:
50
+ * "parity-id" -> "parity_id"
51
+ * "parity-tag" -> "parity_tag" (singular — no pluralization)
52
+ * "parity-birth-date" -> "parity_birth_date"
53
+ * "isbn-13" -> "isbn_13"
54
+ * "order-line" -> "order_line"
55
+ */
56
+ function toFieldName(label) {
57
+ return label.replace(/-/g, "_");
58
+ }
59
+ /**
60
+ * Return true when `attrName` should be emitted as a Key field.
61
+ *
62
+ * Schema `is_key` always wins. `implicitKeyAttributes` adds key-ness only for
63
+ * attributes NOT already marked by the schema — it never downgrades a schema key.
64
+ */
65
+ function isKeyAttribute(attrName, isSchemaKey, options) {
66
+ if (isSchemaKey)
67
+ return true;
68
+ return (options?.implicitKeyAttributes ?? []).includes(attrName);
69
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Render the `attributes.ts` module text from a parsed TypeSchema.
3
+ *
4
+ * Mirrors `type_bridge/generator/render/attributes.py` → `render_attributes()`.
5
+ * Emits one branded `export class <ClassName> extends attr.<Kind>("<name>", ...) {}`
6
+ * per attribute, in deterministic parent-before-child order matching the
7
+ * Python generator's topological/sorted emit.
8
+ *
9
+ * Build-time code generation; no runtime ORM logic.
10
+ */
11
+ import type { TypeSchema } from "../parser.js";
12
+ /**
13
+ * Render the complete `attributes.ts` source text from the parsed schema.
14
+ *
15
+ * Each attribute emits:
16
+ * export class <ClassName> extends attr.<Kind>("<schema-name>") {}
17
+ *
18
+ * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
19
+ * never a hardcoded relative path, so generated files stay valid across
20
+ * the packaging layout change.
21
+ */
22
+ export declare function renderAttributes(schema: TypeSchema): string;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ /**
3
+ * Render the `attributes.ts` module text from a parsed TypeSchema.
4
+ *
5
+ * Mirrors `type_bridge/generator/render/attributes.py` → `render_attributes()`.
6
+ * Emits one branded `export class <ClassName> extends attr.<Kind>("<name>", ...) {}`
7
+ * per attribute, in deterministic parent-before-child order matching the
8
+ * Python generator's topological/sorted emit.
9
+ *
10
+ * Build-time code generation; no runtime ORM logic.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.renderAttributes = renderAttributes;
14
+ const naming_js_1 = require("./naming.js");
15
+ /**
16
+ * Map TypeDB `value_type` strings to the `attr.*` factory method name.
17
+ *
18
+ * Verified against `typescript/attribute.ts` `attr` export:
19
+ * attr.String -> "string"
20
+ * attr.Integer -> "long" (bigint, maps to the `long` wire type)
21
+ * attr.Double -> "double"
22
+ * attr.Boolean -> "boolean"
23
+ * attr.Date -> "date"
24
+ * attr.DateTime -> "datetime"
25
+ * attr.DateTimeTZ -> "datetime-tz"
26
+ * attr.Decimal -> "decimal"
27
+ * attr.Duration -> "duration"
28
+ *
29
+ * The parsed schema preserves the declared value_type: an integer attribute
30
+ * arrives as "integer", not "long". Both "integer" and "long" map to attr.Integer
31
+ * (whose descriptor records the "long" wire type), mirroring the Python generator.
32
+ */
33
+ const VALUE_TYPE_TO_KIND = {
34
+ string: "String",
35
+ integer: "Integer",
36
+ long: "Integer",
37
+ double: "Double",
38
+ boolean: "Boolean",
39
+ date: "Date",
40
+ datetime: "DateTime",
41
+ "datetime-tz": "DateTimeTZ",
42
+ decimal: "Decimal",
43
+ duration: "Duration",
44
+ };
45
+ /**
46
+ * Resolve the `attr.*` factory kind for an attribute, following value_type
47
+ * inheritance. Mirrors `_resolve_value_type` in `render/attributes.py`.
48
+ */
49
+ function resolveAttrKind(attrName, schema, visited = new Set()) {
50
+ if (visited.has(attrName))
51
+ return "String";
52
+ visited.add(attrName);
53
+ const attr = schema.attributes[attrName];
54
+ if (!attr)
55
+ return "String";
56
+ if (attr.value_type) {
57
+ const kind = VALUE_TYPE_TO_KIND[attr.value_type];
58
+ if (kind === undefined) {
59
+ // Fail loudly rather than emit a silently-wrong attr.String — an
60
+ // unmapped value_type means a TypeDB type the generator does not handle.
61
+ throw new Error(`Cannot generate attribute "${attrName}": unsupported value_type "${attr.value_type}".`);
62
+ }
63
+ return kind;
64
+ }
65
+ if (attr.parent) {
66
+ return resolveAttrKind(attr.parent, schema, visited);
67
+ }
68
+ return "String";
69
+ }
70
+ /**
71
+ * Return attribute names in deterministic topological order: parents before
72
+ * children, with alphabetical order among unrelated attributes.
73
+ */
74
+ function sortedAttrNames(schema) {
75
+ const sorted = [];
76
+ const visited = new Set();
77
+ const names = Object.keys(schema.attributes).sort();
78
+ function visit(name) {
79
+ if (visited.has(name))
80
+ return;
81
+ visited.add(name);
82
+ const parent = schema.attributes[name]?.parent;
83
+ if (parent && schema.attributes[parent]) {
84
+ visit(parent);
85
+ }
86
+ sorted.push(name);
87
+ }
88
+ for (const name of names) {
89
+ visit(name);
90
+ }
91
+ return sorted;
92
+ }
93
+ function attributeOptionsLiteral(attrName, schema, attrClassMap) {
94
+ const attribute = schema.attributes[attrName];
95
+ if (!attribute)
96
+ return "";
97
+ const fields = [];
98
+ if (attribute.parent) {
99
+ const parentClass = attrClassMap.get(attribute.parent);
100
+ fields.push(parentClass
101
+ ? `parent: ${parentClass}`
102
+ : `parent: ${JSON.stringify(attribute.parent)}`);
103
+ }
104
+ if (attribute.is_abstract) {
105
+ fields.push(`abstract: true`);
106
+ }
107
+ if (attribute.is_independent) {
108
+ fields.push(`independent: true`);
109
+ }
110
+ if (attribute.regex !== null) {
111
+ fields.push(`regex: ${JSON.stringify(attribute.regex)}`);
112
+ }
113
+ if (attribute.allowed_values !== null) {
114
+ fields.push(`values: ${JSON.stringify(attribute.allowed_values)}`);
115
+ }
116
+ if (attribute.range_min !== null || attribute.range_max !== null) {
117
+ fields.push(`range: [${optionalStringLiteral(attribute.range_min)}, ${optionalStringLiteral(attribute.range_max)}]`);
118
+ }
119
+ return fields.length === 0 ? "" : `, { ${fields.join(", ")} }`;
120
+ }
121
+ function optionalStringLiteral(value) {
122
+ return value === null ? "null" : JSON.stringify(value);
123
+ }
124
+ /**
125
+ * Render the complete `attributes.ts` source text from the parsed schema.
126
+ *
127
+ * Each attribute emits:
128
+ * export class <ClassName> extends attr.<Kind>("<schema-name>") {}
129
+ *
130
+ * The import header always uses the PACKAGE ENTRYPOINT `@type-bridge/node`,
131
+ * never a hardcoded relative path, so generated files stay valid across
132
+ * the packaging layout change.
133
+ */
134
+ function renderAttributes(schema) {
135
+ const names = sortedAttrNames(schema);
136
+ const attrClassMap = new Map();
137
+ for (const name of Object.keys(schema.attributes)) {
138
+ attrClassMap.set(name, (0, naming_js_1.toClassName)(name));
139
+ }
140
+ const lines = [
141
+ `import { attr } from "@type-bridge/node";`,
142
+ ``,
143
+ ];
144
+ for (const name of names) {
145
+ const className = attrClassMap.get(name) ?? (0, naming_js_1.toClassName)(name);
146
+ const kind = resolveAttrKind(name, schema);
147
+ const options = attributeOptionsLiteral(name, schema, attrClassMap);
148
+ lines.push(`export class ${className} extends attr.${kind}("${name}"${options}) {}`);
149
+ }
150
+ // Trailing newline
151
+ lines.push(``);
152
+ return lines.join("\n");
153
+ }