@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.
package/dist/model.js ADDED
@@ -0,0 +1,481 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RoleSpec = exports.ListFieldSpec = exports.FieldSpec = void 0;
4
+ exports.field = field;
5
+ exports.role = role;
6
+ exports.Entity = Entity;
7
+ exports.Relation = Relation;
8
+ const flags_js_1 = require("./flags.js");
9
+ const iid_js_1 = require("./iid.js");
10
+ const manager_js_1 = require("./manager.js");
11
+ const codec_js_1 = require("./codec.js");
12
+ const ATTRIBUTE_SCHEMA_METADATA = Symbol.for("@type-bridge/node.attributeSchemaMetadata");
13
+ /**
14
+ * A declared owned-attribute field: the attribute class, its resolved flags, and
15
+ * whether it is optional. Produced by `field()`; consumed by the model factory to
16
+ * type construction and to emit `owned_attributes`.
17
+ */
18
+ class FieldSpec {
19
+ attrType;
20
+ isOptional;
21
+ kind = "field";
22
+ flags;
23
+ constructor(attrType, flags = [], isOptional = false) {
24
+ this.attrType = attrType;
25
+ this.isOptional = isOptional;
26
+ this.flags = (0, flags_js_1.resolveFlags)(flags);
27
+ }
28
+ optional() {
29
+ return new FieldSpec(this.attrType, [this.flags], true);
30
+ }
31
+ /**
32
+ * Declare this field as a multi-value (list) attribute. Pass a `Card(min, max)`
33
+ * cardinality bound; an unbounded list uses `Card(0)` (max = null).
34
+ *
35
+ * The returned `ListFieldSpec` emits `{"Card":[min,max|null]}` in `annotations`
36
+ * and sets `is_optional` when `card_min == 0` (mirroring `_is_optional` in
37
+ * `type_bridge/_rust_runtime.py`). The typed value is `Attr[] | undefined`
38
+ * when optional, `Attr[]` when required.
39
+ */
40
+ list(card) {
41
+ return new ListFieldSpec(this.attrType, card, this.flags.isOrdered, this.flags.isDistinct);
42
+ }
43
+ }
44
+ exports.FieldSpec = FieldSpec;
45
+ /**
46
+ * A declared multi-value (list) owned-attribute field. Produced by
47
+ * `field(Attr).list(Card(min, max))`; emits a `{"Card":[min,max|null]}`
48
+ * annotation. Analogous to the Python ORM's `card_min`/`card_max` flags.
49
+ *
50
+ * `is_optional` is derived from `card_min == 0`, matching `_is_optional` in
51
+ * `type_bridge/_rust_runtime.py`.
52
+ */
53
+ class ListFieldSpec {
54
+ attrType;
55
+ kind = "list-field";
56
+ /** Explicit cardinality `[min, max | null]`. Always present for list fields. */
57
+ card;
58
+ isOptional;
59
+ /** True when the parent FieldSpec carried the `Ordered` flag. A multi-value
60
+ * `Card` field is a set, not a TypeDB list: only the `Ordered` flag makes
61
+ * the descriptor emit `is_ordered: true` (and `[]` in the define block). */
62
+ isOrdered;
63
+ /** True when the parent FieldSpec carried the `Distinct` flag. */
64
+ isDistinct;
65
+ constructor(attrType, cardSpec, isOrdered = false, isDistinct = false) {
66
+ this.attrType = attrType;
67
+ this.card = [cardSpec.min, cardSpec.max];
68
+ // A list field is optional when the minimum cardinality is 0, mirroring the
69
+ // Python `_is_optional` rule: `flags.card_min == 0`.
70
+ this.isOptional = (cardSpec.min === 0);
71
+ this.isOrdered = isOrdered;
72
+ this.isDistinct = isDistinct;
73
+ }
74
+ }
75
+ exports.ListFieldSpec = ListFieldSpec;
76
+ /**
77
+ * A declared relation role: its permitted player model(s), optional
78
+ * relates-side cardinality, and optional plays-side cardinality. Produced by
79
+ * `role()`; consumed by the model factory to emit `roles[*]` plus metadata
80
+ * used by `DescriptorRegistry.schemaInfo()`. Multi-player roles list more than
81
+ * one player token.
82
+ */
83
+ class RoleSpec {
84
+ players;
85
+ kind = "role";
86
+ cardinality;
87
+ playsCardinality;
88
+ /** Parent role name this role specializes via TypeDB's `relates child as parent` syntax.
89
+ * Used only for descriptor computation (effective-set role exclusion); specialization
90
+ * semantics are resolved at schema-define time. */
91
+ overrides;
92
+ /** When ``true``, this role is abstract at the TypeDB schema level (``@abstract`` on
93
+ * the ``relates`` clause). The engine rejects direct players at the declaring
94
+ * relation's own scope; subtypes that plain-inherit or override the role are
95
+ * unaffected. */
96
+ isAbstract;
97
+ /** When ``true``, declares this role as a list role (``relates name[]`` in TypeQL).
98
+ * Schema-only; instance-level list writes are not yet supported by the engine. */
99
+ ordered;
100
+ /** When ``true``, emits ``@distinct`` on the relates clause. Requires ``ordered``. */
101
+ distinct;
102
+ constructor(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct) {
103
+ this.players = players;
104
+ if (playsCardinality != null && players.length === 0) {
105
+ throw new TypeError("playsCardinality requires at least one role player");
106
+ }
107
+ if (distinct && !ordered) {
108
+ throw new TypeError("RoleSpec: distinct requires ordered — @distinct is only valid on a list role (relates name[]).");
109
+ }
110
+ this.cardinality = cardinality == null ? null : [cardinality.min, cardinality.max];
111
+ this.playsCardinality =
112
+ playsCardinality == null ? null : [playsCardinality.min, playsCardinality.max];
113
+ this.overrides = overrides;
114
+ this.isAbstract = isAbstract ?? false;
115
+ this.ordered = ordered ?? false;
116
+ this.distinct = distinct ?? false;
117
+ }
118
+ }
119
+ exports.RoleSpec = RoleSpec;
120
+ /** Declare an owned-attribute field on a model schema, with optional flags. */
121
+ function field(attrType, ...flags) {
122
+ return new FieldSpec(attrType, flags);
123
+ }
124
+ function role(...playersAndOptions) {
125
+ const { players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct } = splitRoleArguments(playersAndOptions);
126
+ return new RoleSpec(players, cardinality, playsCardinality, overrides, isAbstract, ordered, distinct);
127
+ }
128
+ function Entity(typeNameOrFlags, schema, options) {
129
+ return createModelClass(typeNameOrFlags, schema, "entity", options?.parent ?? null);
130
+ }
131
+ function Relation(typeNameOrFlags, schema, options) {
132
+ return createModelClass(typeNameOrFlags, schema, "relation", options?.parent ?? null);
133
+ }
134
+ // Shared factory behind `Entity()` and `Relation()`. Returns an abstract base
135
+ // class carrying the schema, resolved flags, a typed frozen-field constructor,
136
+ // and `descriptor()`. The two public wrappers only differ in their return type
137
+ // and whether `descriptor()` includes `roles`.
138
+ //
139
+ // When `parent` is supplied, the merged schema (parent + child) is used for
140
+ // constructor field population and instance field access. The descriptor emits
141
+ // `parent_type` and the full flattened `owned_attributes`.
142
+ function createModelClass(typeNameOrFlags, schema, kind, parent = null) {
143
+ const flags = typeof typeNameOrFlags === "string" ? (0, flags_js_1.TypeFlags)({ name: typeNameOrFlags }) : typeNameOrFlags;
144
+ // The merged schema is what the constructor and instance fields use.
145
+ // Parent fields come first; child-local fields follow (and shadow parent keys).
146
+ const parentSchema = parent?.schema ?? {};
147
+ const mergedSchema = { ...parentSchema, ...schema };
148
+ class TypedModel {
149
+ // Expose the child-local schema as the declared schema (matches the class
150
+ // declaration surface), but use mergedSchema at runtime for construction.
151
+ static schema = mergedSchema;
152
+ static flags = flags;
153
+ static get typeName() {
154
+ return flags.name ?? (0, flags_js_1.formatTypeName)(this.name, flags.case);
155
+ }
156
+ constructor(values) {
157
+ (0, iid_js_1.defineIidSlot)(this);
158
+ for (const key of Object.keys(mergedSchema)) {
159
+ const spec = mergedSchema[key];
160
+ const present = key in values;
161
+ const optional = spec instanceof RoleSpec ||
162
+ (spec instanceof FieldSpec && spec.isOptional) ||
163
+ (spec instanceof ListFieldSpec && spec.isOptional);
164
+ // The constructor type already forbids omitting a required field, but
165
+ // guard at runtime too: callers crossing an `any`/JS boundary bypass the
166
+ // compile-time check, and a silent `undefined` would corrupt the
167
+ // descriptor round-trip rather than fail loudly.
168
+ //
169
+ // RoleSpec fields are always treated as optional here: role players are
170
+ // a relation-level concern that fromDict() and attribute-only hydration
171
+ // paths legitimately leave unset. The manager's hydrateRelationGroup
172
+ // always populates them via hydrateRoleFields().
173
+ if (!present && !optional) {
174
+ throw new TypeError(`${flags.name ?? this.constructor.name}: missing required field "${key}"`);
175
+ }
176
+ Object.defineProperty(this, key, {
177
+ value: present ? values[key] : undefined,
178
+ enumerable: true,
179
+ writable: false,
180
+ });
181
+ }
182
+ }
183
+ /**
184
+ * Serialize this typed instance to the canonical plain dict.
185
+ * See `ModelClass.toDict()` for the full contract.
186
+ *
187
+ * The concrete body returns the structural `Record<string, unknown>` because
188
+ * the runtime walks `mergedSchema` dynamically; the precise
189
+ * `InstanceDict<Schema>` is recovered at the public boundary by
190
+ * `ModelInstance<Schema>` / `ModelClass`, which every caller sees. The
191
+ * widening is contained to this base class — callers never observe it.
192
+ */
193
+ toDict() {
194
+ const result = {};
195
+ const self = this;
196
+ for (const [key, spec] of Object.entries(mergedSchema)) {
197
+ if (spec instanceof RoleSpec) {
198
+ // Role fields are not serialized in the attribute dict.
199
+ continue;
200
+ }
201
+ const value = self[key];
202
+ if (value === undefined) {
203
+ // Absent optional field: omit entirely (mirrors Python exclude_unset).
204
+ continue;
205
+ }
206
+ if (spec instanceof ListFieldSpec) {
207
+ if (!Array.isArray(value)) {
208
+ throw new codec_js_1.TypedCodecError(`List field "${key}" is not an array`);
209
+ }
210
+ result[key] = (0, codec_js_1.attributeToPlain)(value);
211
+ }
212
+ else {
213
+ result[key] = (0, codec_js_1.attributeToPlain)(value);
214
+ }
215
+ }
216
+ return result;
217
+ }
218
+ static fromDict(data) {
219
+ // Check for unknown keys (strict mode, mirrors Python from_dict strict=True).
220
+ for (const key of Object.keys(data)) {
221
+ if (!(key in mergedSchema) || mergedSchema[key] instanceof RoleSpec) {
222
+ throw new codec_js_1.TypedCodecError(`fromDict: unknown field "${key}" for ${this.typeName}`);
223
+ }
224
+ }
225
+ // Re-brand each plain value into a typed Attribute / Attribute[].
226
+ const values = {};
227
+ for (const [key, spec] of Object.entries(mergedSchema)) {
228
+ if (spec instanceof RoleSpec) {
229
+ continue;
230
+ }
231
+ const rawValue = data[key];
232
+ if (rawValue === undefined || rawValue === null) {
233
+ // Let the constructor handle missing required field detection.
234
+ continue;
235
+ }
236
+ const isList = spec instanceof ListFieldSpec;
237
+ values[key] = (0, codec_js_1.plainToAttribute)(spec.attrType, rawValue, key, isList);
238
+ }
239
+ // Constructor throws TypeError on missing required fields (existing guard).
240
+ return new this(values);
241
+ }
242
+ static descriptor() {
243
+ const parentTypeName = parent != null ? parent.typeName : null;
244
+ const descriptor = {
245
+ type_name: this.typeName,
246
+ is_abstract: flags.abstract,
247
+ parent_type: parentTypeName,
248
+ // Flattened owned_attributes: parent attrs first, then child-local attrs.
249
+ // The schema generator only emits `owns` for non-inherited attrs, but the
250
+ // Python descriptor contract re-lists inherited attrs in the child —
251
+ // descriptors.json `parity-person` is the reference.
252
+ owned_attributes: ownedAttributes(parentSchema, schema),
253
+ };
254
+ attachAttributeSchemaMetadata(descriptor, parentSchema, schema);
255
+ if (kind === "entity") {
256
+ return descriptor;
257
+ }
258
+ // For the effective role set we need the parent's own effective roles
259
+ // (recursively resolved), not its raw schema. Calling parent.descriptor()
260
+ // here is safe: the parent class is already fully defined when descriptor()
261
+ // is invoked on the child.
262
+ const parentEffectiveRoles = (() => {
263
+ if (parent == null)
264
+ return [];
265
+ const pd = parent.descriptor();
266
+ return pd.roles ?? [];
267
+ })();
268
+ const relationDescriptor = {
269
+ ...descriptor,
270
+ roles: roleDescriptors(parentEffectiveRoles, schema),
271
+ };
272
+ attachAttributeSchemaMetadata(relationDescriptor, parentSchema, schema);
273
+ return relationDescriptor;
274
+ }
275
+ static manager(db) {
276
+ if (kind === "entity") {
277
+ return (0, manager_js_1.entityManagerFor)(this, db);
278
+ }
279
+ return (0, manager_js_1.relationManagerFor)(this, db);
280
+ }
281
+ }
282
+ return TypedModel;
283
+ }
284
+ /**
285
+ * Emit the full flattened `owned_attributes` list for a descriptor.
286
+ *
287
+ * When a model has a parent, the Python facade contract re-lists the parent's
288
+ * owned attributes in the child's descriptor before the child-local attrs.
289
+ * `parentSchema` is the parent's schema (empty `{}` when there is no parent);
290
+ * `childSchema` is the locally-declared schema. The normalizer sorts by
291
+ * `field_name`, so insertion order is irrelevant for parity, but we follow
292
+ * the Python facade ordering (parent-first) for readability.
293
+ */
294
+ function ownedAttributes(parentSchema, childSchema) {
295
+ const descriptors = [];
296
+ // Parent attrs first (inherited, re-listed).
297
+ for (const [fieldName, spec] of Object.entries(parentSchema)) {
298
+ const entry = ownedAttributeEntry(fieldName, spec);
299
+ if (entry != null) {
300
+ descriptors.push(entry);
301
+ }
302
+ }
303
+ // Child-local attrs (not already covered by the parent re-listing).
304
+ for (const [fieldName, spec] of Object.entries(childSchema)) {
305
+ const entry = ownedAttributeEntry(fieldName, spec);
306
+ if (entry != null) {
307
+ descriptors.push(entry);
308
+ }
309
+ }
310
+ return descriptors;
311
+ }
312
+ /**
313
+ * Convert a single schema spec entry to an `OwnedAttributeDescriptor`.
314
+ *
315
+ * Handles both scalar `FieldSpec` and multi-value `ListFieldSpec`:
316
+ *
317
+ * - `FieldSpec`: emits `annotations` from `resolveFlags()`, `is_optional` from
318
+ * `spec.isOptional`. The normalizer strips scalar `Card(0,1)/(1,1)` — the
319
+ * emitter does NOT strip them (invariant: emitter is unconditional).
320
+ * - `ListFieldSpec`: emits a single `{"Card":[min,max|null]}` annotation from
321
+ * the explicit cardinality. `is_optional` is derived from `card_min == 0`,
322
+ * mirroring `_is_optional` in `type_bridge/_rust_runtime.py`.
323
+ *
324
+ * Returns `null` for `RoleSpec` entries (not attribute descriptors).
325
+ */
326
+ function ownedAttributeEntry(fieldName, spec) {
327
+ if (spec instanceof ListFieldSpec) {
328
+ // Multi-value list field: emit the explicit Card annotation unconditionally.
329
+ // is_optional mirrors Python's `_is_optional`: card_min == 0.
330
+ const cardAnnotation = { Card: [spec.card[0], spec.card[1]] };
331
+ const annotations = [cardAnnotation];
332
+ if (spec.isDistinct) {
333
+ annotations.push("Distinct");
334
+ }
335
+ return {
336
+ field_name: fieldName,
337
+ attr_name: spec.attrType.attrName,
338
+ value_type: spec.attrType.valueType,
339
+ annotations,
340
+ is_optional: spec.isOptional,
341
+ is_ordered: spec.isOrdered,
342
+ };
343
+ }
344
+ if (spec instanceof FieldSpec) {
345
+ return {
346
+ field_name: fieldName,
347
+ attr_name: spec.attrType.attrName,
348
+ value_type: spec.attrType.valueType,
349
+ annotations: spec.flags.annotations.map(copyAnnotation),
350
+ is_optional: spec.isOptional,
351
+ is_ordered: spec.flags.isOrdered,
352
+ };
353
+ }
354
+ // RoleSpec — not an attribute descriptor.
355
+ return null;
356
+ }
357
+ function attachAttributeSchemaMetadata(descriptor, parentSchema, childSchema) {
358
+ const metadata = attributeSchemaMetadata(parentSchema, childSchema);
359
+ if (Object.keys(metadata).length === 0) {
360
+ return;
361
+ }
362
+ Object.defineProperty(descriptor, ATTRIBUTE_SCHEMA_METADATA, {
363
+ value: metadata,
364
+ enumerable: false,
365
+ configurable: false,
366
+ writable: false,
367
+ });
368
+ }
369
+ function attributeSchemaMetadata(parentSchema, childSchema) {
370
+ const metadata = {};
371
+ for (const spec of [...Object.values(parentSchema), ...Object.values(childSchema)]) {
372
+ if (spec instanceof FieldSpec || spec instanceof ListFieldSpec) {
373
+ for (const entry of spec.attrType.attributeSchemaEntries) {
374
+ metadata[entry.attr_name] = copyAttributeSchemaEntry(entry);
375
+ }
376
+ }
377
+ }
378
+ return metadata;
379
+ }
380
+ function copyAttributeSchemaEntry(entry) {
381
+ const copy = { ...entry };
382
+ if (entry.allowed_values !== undefined) {
383
+ copy.allowed_values = entry.allowed_values === null ? null : [...entry.allowed_values];
384
+ }
385
+ if (entry.range !== undefined) {
386
+ copy.range = entry.range === null ? null : [entry.range[0], entry.range[1]];
387
+ }
388
+ return copy;
389
+ }
390
+ /**
391
+ * Emit the canonical effective role set for a relation descriptor.
392
+ *
393
+ * `parentEffectiveRoles` is the parent's already-resolved effective role list
394
+ * (empty for root relations). `childSchema` is the child-local schema.
395
+ *
396
+ * Result: parent effective roles first (excluding those overridden by a child
397
+ * specialization), then child-local roles in declaration order. This mirrors
398
+ * the Python `_effective_roles` algorithm and the contract in `descriptor.rs`.
399
+ */
400
+ function roleDescriptors(parentEffectiveRoles, childSchema) {
401
+ // Collect parent role names overridden by child specializations.
402
+ const overriddenRoleNames = new Set();
403
+ for (const spec of Object.values(childSchema)) {
404
+ if (spec instanceof RoleSpec && spec.overrides != null) {
405
+ overriddenRoleNames.add(spec.overrides);
406
+ }
407
+ }
408
+ const descriptors = [];
409
+ // Parent effective roles first — skip those overridden at this level.
410
+ // Inherited-role entries keep all parent markers (overrides, is_abstract,
411
+ // ordered, distinct) because they were set at declaration time and travel
412
+ // with the descriptor.
413
+ for (const parentRole of parentEffectiveRoles) {
414
+ if (overriddenRoleNames.has(parentRole.role_name))
415
+ continue;
416
+ descriptors.push({ ...parentRole });
417
+ }
418
+ // Child-local roles follow in declaration order.
419
+ for (const [roleName, spec] of Object.entries(childSchema)) {
420
+ if (!(spec instanceof RoleSpec))
421
+ continue;
422
+ descriptors.push({
423
+ role_name: roleName,
424
+ player_type_names: spec.players.map(typeNameFor),
425
+ cardinality: spec.cardinality,
426
+ plays_cardinality: spec.playsCardinality,
427
+ overrides: spec.overrides ?? null,
428
+ is_abstract: spec.isAbstract,
429
+ ordered: spec.ordered,
430
+ distinct: spec.distinct,
431
+ });
432
+ }
433
+ return descriptors;
434
+ }
435
+ function typeNameFor(token) {
436
+ return typeof token === "string" ? token : token.typeName;
437
+ }
438
+ function copyAnnotation(annotation) {
439
+ if (typeof annotation === "string") {
440
+ // Covers "Key", "Unique", "Distinct" — all string-tag variants.
441
+ return annotation;
442
+ }
443
+ return { Card: [annotation.Card[0], annotation.Card[1]] };
444
+ }
445
+ function splitRoleArguments(args) {
446
+ if (args.length === 0) {
447
+ return { players: [], cardinality: null, playsCardinality: null, overrides: undefined, isAbstract: false, ordered: false, distinct: false };
448
+ }
449
+ const maybeOptions = args[args.length - 1];
450
+ if (isRoleOptions(maybeOptions)) {
451
+ return {
452
+ players: args.slice(0, -1),
453
+ cardinality: maybeOptions.cardinality ?? null,
454
+ playsCardinality: maybeOptions.playsCardinality ?? null,
455
+ overrides: maybeOptions.overrides,
456
+ isAbstract: maybeOptions.abstract ?? false,
457
+ ordered: maybeOptions.ordered ?? false,
458
+ distinct: maybeOptions.distinct ?? false,
459
+ };
460
+ }
461
+ return {
462
+ players: args,
463
+ cardinality: null,
464
+ playsCardinality: null,
465
+ overrides: undefined,
466
+ isAbstract: false,
467
+ ordered: false,
468
+ distinct: false,
469
+ };
470
+ }
471
+ // Distinguishes a trailing role-options object from a player token.
472
+ // Safe while player tokens are only strings or model classes (neither carries a
473
+ // cardinality option property); if `role()` gains richer player tokens in a later
474
+ // plan, this discriminator must be revisited.
475
+ function isRoleOptions(value) {
476
+ return (typeof value === "object" &&
477
+ value !== null &&
478
+ ("cardinality" in value || "playsCardinality" in value || "overrides" in value || "abstract" in value || "ordered" in value || "distinct" in value) &&
479
+ !(value instanceof FieldSpec) &&
480
+ !(value instanceof RoleSpec));
481
+ }
@@ -0,0 +1,14 @@
1
+ import type { NativeModule } from "./index.js";
2
+ /**
3
+ * Loads and returns the native .node module. The result is cached after the
4
+ * first successful load; subsequent calls return the same object.
5
+ *
6
+ * Resolution order:
7
+ * 1. TYPE_BRIDGE_NODE_NATIVE_PATH env var (explicit override).
8
+ * 2. Platform-triple candidates at the package root (dist/..).
9
+ * 3. Generic-name candidates at the package root.
10
+ * 4. Same set probed inside dist/ as a robustness fallback.
11
+ *
12
+ * Throws an actionable error listing all tried paths when no candidate exists.
13
+ */
14
+ export declare function loadNative(): NativeModule;
package/dist/native.js ADDED
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadNative = loadNative;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ // This module compiles to dist/native.js (CommonJS). __dirname is therefore
40
+ // the dist/ directory. The .node artifacts are placed at the package root
41
+ // (one level up, i.e. dist/..) by build-native.js, which writes
42
+ // type_bridge_node.<triple>.node beside package.json. The candidates list
43
+ // probes the package root first (primary), then dist/ itself as a robustness
44
+ // fallback for atypical build layouts.
45
+ let _cached = null;
46
+ /**
47
+ * Returns the platform triple used in the built .node filename, or null when
48
+ * the current platform has no recognised triple.
49
+ */
50
+ function platformTriple() {
51
+ const arch = process.arch;
52
+ switch (process.platform) {
53
+ case "darwin":
54
+ return arch === "arm64" ? "darwin-arm64" : "darwin-x64";
55
+ case "linux":
56
+ if (arch === "arm64") {
57
+ return "linux-arm64-gnu";
58
+ }
59
+ return arch === "x64" ? "linux-x64-gnu" : null;
60
+ case "win32":
61
+ return arch === "arm64" ? "win32-arm64-msvc" : "win32-x64-msvc";
62
+ default:
63
+ return null;
64
+ }
65
+ }
66
+ /**
67
+ * Returns the ordered list of absolute candidate paths to probe for the .node
68
+ * artifact. Platform-triple-specific names are tried first; generic fallbacks
69
+ * follow. Both the package root (dist/..) and dist/ itself are probed so that
70
+ * the loader works whether the artifact sits beside package.json or beside the
71
+ * compiled output.
72
+ */
73
+ function nativeCandidates() {
74
+ const triple = platformTriple();
75
+ const names = [];
76
+ if (triple) {
77
+ names.push(`type_bridge_node.${triple}.node`, `type-bridge-node.${triple}.node`);
78
+ }
79
+ names.push("type_bridge_node.node", "type-bridge-node.node", "index.node");
80
+ // Primary: package root (dist/..) — where build-native.js places the artifact.
81
+ // Secondary: dist/ itself — robustness fallback for atypical build layouts.
82
+ const packageRoot = path.join(__dirname, "..");
83
+ const candidates = [];
84
+ for (const name of names) {
85
+ candidates.push(path.join(packageRoot, name));
86
+ }
87
+ for (const name of names) {
88
+ candidates.push(path.join(__dirname, name));
89
+ }
90
+ return candidates;
91
+ }
92
+ /**
93
+ * Loads and returns the native .node module. The result is cached after the
94
+ * first successful load; subsequent calls return the same object.
95
+ *
96
+ * Resolution order:
97
+ * 1. TYPE_BRIDGE_NODE_NATIVE_PATH env var (explicit override).
98
+ * 2. Platform-triple candidates at the package root (dist/..).
99
+ * 3. Generic-name candidates at the package root.
100
+ * 4. Same set probed inside dist/ as a robustness fallback.
101
+ *
102
+ * Throws an actionable error listing all tried paths when no candidate exists.
103
+ */
104
+ function loadNative() {
105
+ if (_cached !== null) {
106
+ return _cached;
107
+ }
108
+ const explicitPath = process.env["TYPE_BRIDGE_NODE_NATIVE_PATH"];
109
+ const candidates = explicitPath ? [explicitPath] : [];
110
+ candidates.push(...nativeCandidates());
111
+ const tried = [];
112
+ for (const candidate of candidates) {
113
+ tried.push(candidate);
114
+ if (fs.existsSync(candidate)) {
115
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
116
+ _cached = require(candidate);
117
+ return _cached;
118
+ }
119
+ }
120
+ throw new Error([
121
+ "Unable to load the type-bridge native Node module.",
122
+ "Run `npm run build:native`, or set TYPE_BRIDGE_NODE_NATIVE_PATH to the built .node artifact.",
123
+ `Tried: ${tried.join(", ")}`,
124
+ ].join(" "));
125
+ }