fastdb4ts 0.0.2 → 0.0.3

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,1857 @@
1
+ import { Feature, createFeature } from './feature.js';
2
+ import { FastdbUsageError } from './errors.js';
3
+ import { ORM } from './orm.js';
4
+ import { loadDatabaseFromBytes } from './database-buffer.js';
5
+ import { defineSchema, getClassSchema, resolveListItem } from './schema.js';
6
+ import { getInitializedFastdbModule } from './wasm-loader.js';
7
+ import { BOOL, BYTES, F32, F64, I32, STR, U8, U8N, U16, U16N, U32, WSTR, coerceBoolScalar, isListField, isRefField, } from './types.js';
8
+ const CALL_DB_COLUMNAR_PROFILE = 'fastdb.call.columnar.v1';
9
+ const CALL_DB_OBJECT_GRAPH_PROFILE = 'fastdb.call.object-graph.v1';
10
+ const CALL_DB_CODEC_ID = 'org.fastdb.call-db';
11
+ const CALL_DB_ARRAY_VALUE_FIELD = 'value';
12
+ const FEATURE_COLUMNAR_PROFILE = 'columnar.v1';
13
+ const FEATURE_OBJECT_GRAPH_PROFILE = 'object_graph.v1';
14
+ const FEATURE_COLUMNAR_CODEC_ID = 'org.fastdb.columnar';
15
+ const FEATURE_OBJECT_GRAPH_CODEC_ID = 'org.fastdb.object-graph';
16
+ const BULK_APPEND_KINDS = new Set(['bool', 'u8', 'u16', 'u32', 'i32', 'u8n', 'u16n', 'f32', 'f64']);
17
+ const VALIDATED_COLUMNAR_FEATURES = new WeakSet();
18
+ const FIELD_TYPES = {
19
+ bool: BOOL,
20
+ bytes: BYTES,
21
+ f32: F32,
22
+ f64: F64,
23
+ i32: I32,
24
+ str: STR,
25
+ u8: U8,
26
+ u8n: U8N,
27
+ u16: U16,
28
+ u16n: U16N,
29
+ u32: U32,
30
+ wstr: WSTR,
31
+ };
32
+ const DYNAMIC_FEATURE_CACHE = new WeakMap();
33
+ export function encodeFastdbFeature(binding, value) {
34
+ if (binding.profile === FEATURE_OBJECT_GRAPH_PROFILE) {
35
+ ensureCodecId(binding.codecId, FEATURE_OBJECT_GRAPH_CODEC_ID);
36
+ ensureObjectGraphFeatureRuntime(binding.feature, `fastdb feature codec "${binding.feature.name}"`);
37
+ return encodeObjectGraphFeature(ensureFeatureValue(value, binding.feature, binding.feature.name));
38
+ }
39
+ if (binding.profile !== FEATURE_COLUMNAR_PROFILE) {
40
+ throw new FastdbUsageError(`Unsupported fastdb feature codec profile "${binding.profile}".`);
41
+ }
42
+ ensureCodecId(binding.codecId, FEATURE_COLUMNAR_CODEC_ID);
43
+ ensureColumnarFeatureRuntime(binding.feature, `fastdb feature codec "${binding.feature.name}"`);
44
+ const orm = ORM.create();
45
+ try {
46
+ orm.push(value);
47
+ orm.combine();
48
+ return orm.toBuffer();
49
+ }
50
+ finally {
51
+ orm.close();
52
+ }
53
+ }
54
+ export function decodeFastdbFeature(binding, payload) {
55
+ if (binding.profile === FEATURE_OBJECT_GRAPH_PROFILE) {
56
+ ensureCodecId(binding.codecId, FEATURE_OBJECT_GRAPH_CODEC_ID);
57
+ ensureObjectGraphFeatureRuntime(binding.feature, `fastdb feature codec "${binding.feature.name}"`);
58
+ return decodeObjectGraphFeature(binding.feature, payload);
59
+ }
60
+ if (binding.profile !== FEATURE_COLUMNAR_PROFILE) {
61
+ throw new FastdbUsageError(`Unsupported fastdb feature codec profile "${binding.profile}".`);
62
+ }
63
+ ensureCodecId(binding.codecId, FEATURE_COLUMNAR_CODEC_ID);
64
+ ensureColumnarFeatureRuntime(binding.feature, `fastdb feature codec "${binding.feature.name}"`);
65
+ const orm = ORM.fromBuffer(payload);
66
+ try {
67
+ const table = orm.table(binding.feature);
68
+ if (table.length < 1) {
69
+ throw new FastdbUsageError(`fastdb call-db feature payload table "${binding.feature.name}" is empty.`);
70
+ }
71
+ return copyFeature(binding.feature, table.get(0));
72
+ }
73
+ finally {
74
+ orm.close();
75
+ }
76
+ }
77
+ export function encodeFastdbCallDb(binding, value) {
78
+ if (binding.profile === CALL_DB_OBJECT_GRAPH_PROFILE) {
79
+ ensureObjectGraphCallDb(binding);
80
+ const values = normalizeCallValues(binding, value);
81
+ return encodeObjectGraphCallDb(binding, values);
82
+ }
83
+ ensureColumnarCallDb(binding);
84
+ const values = normalizeCallValues(binding, value);
85
+ const fastPathPayload = tryEncodeColumnarCallDbFastPath(binding, values);
86
+ if (fastPathPayload !== null) {
87
+ return fastPathPayload;
88
+ }
89
+ const orm = ORM.create();
90
+ try {
91
+ for (const table of binding.tables) {
92
+ encodeCallTable(orm, table, values);
93
+ }
94
+ orm.combine();
95
+ return orm.toBuffer();
96
+ }
97
+ finally {
98
+ orm.close();
99
+ }
100
+ }
101
+ export function decodeFastdbCallDb(binding, payload) {
102
+ if (binding.profile === CALL_DB_OBJECT_GRAPH_PROFILE) {
103
+ ensureObjectGraphCallDb(binding);
104
+ return decodeObjectGraphCallDb(binding, payload);
105
+ }
106
+ ensureColumnarCallDb(binding);
107
+ const orm = ORM.fromBuffer(payload);
108
+ try {
109
+ const values = new Array(callValueCount(binding)).fill(undefined);
110
+ for (const table of binding.tables) {
111
+ decodeCallTable(orm, table, values);
112
+ }
113
+ if (binding.direction === 'input') {
114
+ return values;
115
+ }
116
+ return values.length === 1 ? values[0] : values;
117
+ }
118
+ finally {
119
+ orm.close();
120
+ }
121
+ }
122
+ export function viewFastdbCallDb(binding, payload) {
123
+ ensureCodecId(binding.codecId, CALL_DB_CODEC_ID);
124
+ if (binding.profile === CALL_DB_OBJECT_GRAPH_PROFILE) {
125
+ ensureObjectGraphCallDb(binding);
126
+ const ctx = loadObjectGraphContext(payload, objectGraphBindingFeatureTypes(binding));
127
+ try {
128
+ return new FastdbCallDbView(binding, ctx);
129
+ }
130
+ catch (error) {
131
+ ctx.db.delete();
132
+ throw error;
133
+ }
134
+ }
135
+ ensureColumnarCallDb(binding);
136
+ return new FastdbCallDbView(binding, ORM.fromBuffer(payload));
137
+ }
138
+ export class FastdbCallDbView {
139
+ binding;
140
+ storage;
141
+ closed = false;
142
+ mode;
143
+ constructor(binding, storage) {
144
+ this.binding = binding;
145
+ this.storage = storage;
146
+ if (binding.profile === CALL_DB_OBJECT_GRAPH_PROFILE) {
147
+ ensureObjectGraphCallDb(binding);
148
+ if (!isObjectGraphLoadContext(storage)) {
149
+ throw new FastdbUsageError('fastdb call-db object-graph call-db view requires an object-graph database context.');
150
+ }
151
+ this.mode = 'object-graph';
152
+ }
153
+ else {
154
+ ensureColumnarCallDb(binding);
155
+ if (!(storage instanceof ORM)) {
156
+ throw new FastdbUsageError('fastdb call-db columnar call-db view requires an ORM instance.');
157
+ }
158
+ this.mode = 'columnar';
159
+ }
160
+ }
161
+ materialize() {
162
+ this.ensureOpen();
163
+ if (this.mode === 'object-graph') {
164
+ return decodeObjectGraphCallDbFromContext(this.binding, this.objectGraphContext());
165
+ }
166
+ const values = new Array(callValueCount(this.binding)).fill(undefined);
167
+ for (const table of this.binding.tables) {
168
+ decodeCallTable(this.orm(), table, values);
169
+ }
170
+ if (this.binding.direction === 'input') {
171
+ return values;
172
+ }
173
+ return values.length === 1 ? values[0] : values;
174
+ }
175
+ table(nameOrIndex) {
176
+ const spec = this.resolveTable('feature', nameOrIndex);
177
+ return new FastdbCallDbTableView(this, spec);
178
+ }
179
+ feature(nameOrIndex) {
180
+ const spec = this.resolveTable('feature', nameOrIndex);
181
+ if (spec.cardinality !== 'one') {
182
+ throw new FastdbUsageError(`fastdb call-db feature view "${spec.name}" has cardinality "${spec.cardinality}"; use table() for batch outputs.`);
183
+ }
184
+ if (this.tableLength(spec) < 1) {
185
+ throw new FastdbUsageError(`fastdb call-db feature table "${spec.name}" is empty.`);
186
+ }
187
+ return this.tableFeature(spec, 0);
188
+ }
189
+ array(nameOrIndex) {
190
+ const spec = this.resolveTable('array', nameOrIndex);
191
+ return new FastdbCallDbArrayView(this, spec);
192
+ }
193
+ scalar(nameOrIndex) {
194
+ const { field, spec } = this.resolveScalarField(nameOrIndex);
195
+ if (this.tableLength(spec) < 1) {
196
+ throw new FastdbUsageError(`fastdb call-db scalar table "${spec.name}" is empty.`);
197
+ }
198
+ const row = this.tableFeature(spec, 0);
199
+ return materializeScalarValue(field.kind, row[field.name]);
200
+ }
201
+ close() {
202
+ if (this.closed) {
203
+ return;
204
+ }
205
+ this.closed = true;
206
+ if (this.mode === 'object-graph') {
207
+ this.objectGraphContext().db.delete();
208
+ }
209
+ else {
210
+ this.orm().close();
211
+ }
212
+ }
213
+ ensureOpen() {
214
+ if (this.closed) {
215
+ throw new FastdbUsageError('fastdb call-db call-db view is closed.');
216
+ }
217
+ }
218
+ tableLength(spec) {
219
+ if (this.mode === 'object-graph') {
220
+ const layerIdx = this.objectGraphLayerIndex(spec);
221
+ return layerIdx === null ? 0 : this.objectGraphContext().db.getLayer(layerIdx).getFeatureCount();
222
+ }
223
+ return this.tableFor(spec).length;
224
+ }
225
+ tableFeature(spec, index) {
226
+ if (this.mode === 'object-graph') {
227
+ const layerIdx = this.objectGraphLayerIndex(spec);
228
+ if (layerIdx === null) {
229
+ throw new FastdbUsageError(`fastdb call-db object-graph table "${spec.name}" was not found.`);
230
+ }
231
+ const featureType = spec.kind === 'feature' ? requireFeature(spec) : dynamicFeatureForTable(spec);
232
+ return copyObjectGraphFeature(this.objectGraphContext(), featureType, layerIdx, index);
233
+ }
234
+ return this.tableFor(spec).get(index);
235
+ }
236
+ arrayValue(spec, index) {
237
+ return this.tableFeature(spec, index).value;
238
+ }
239
+ tableColumn(spec, fieldName) {
240
+ if (this.mode === 'object-graph') {
241
+ throw new FastdbUsageError('fastdb call-db object-graph call-db views do not expose column access; use table().get(...), array(), scalar(), feature(), or materialize().');
242
+ }
243
+ const field = columnFieldForTable(spec, fieldName);
244
+ if (!field) {
245
+ return undefined;
246
+ }
247
+ if (field.kind === 'list') {
248
+ throw new FastdbUsageError(`Column accessor "${fieldName}" is a list field; read it from table rows instead of as a strided column.`);
249
+ }
250
+ if (field.kind === 'ref') {
251
+ throw new FastdbUsageError(`Column accessor "${fieldName}" is a ref field; read it from table rows instead of as a strided column.`);
252
+ }
253
+ if (canBulkAppendKind(field.kind)) {
254
+ const column = this.tableFor(spec).column[fieldName];
255
+ if (column) {
256
+ return new FastdbStridedColumnSource(column);
257
+ }
258
+ }
259
+ return new FastdbRowFieldColumnSource(this, spec, field.name, field.kind);
260
+ }
261
+ tableFor(spec) {
262
+ this.ensureOpen();
263
+ if (spec.kind === 'feature') {
264
+ return this.orm().table(requireFeature(spec), spec.name);
265
+ }
266
+ if (spec.kind === 'array' || spec.kind === 'scalars') {
267
+ return this.orm().table(dynamicFeatureForTable(spec), spec.name);
268
+ }
269
+ throw new FastdbUsageError(`fastdb call-db table "${spec.name}" is not a supported view table.`);
270
+ }
271
+ objectGraphLayerIndex(spec) {
272
+ this.ensureOpen();
273
+ const ctx = this.objectGraphContext();
274
+ if (spec.kind === 'feature') {
275
+ return layerIndexForType(ctx.db, requireFeature(spec));
276
+ }
277
+ if (spec.kind === 'array' || spec.kind === 'scalars') {
278
+ return layerIndexForName(ctx.db, spec.name);
279
+ }
280
+ throw new FastdbUsageError(`fastdb call-db object-graph table "${spec.name}" is not a supported view table.`);
281
+ }
282
+ orm() {
283
+ if (!(this.storage instanceof ORM)) {
284
+ throw new FastdbUsageError('fastdb call-db call-db view is not columnar.');
285
+ }
286
+ return this.storage;
287
+ }
288
+ objectGraphContext() {
289
+ if (!isObjectGraphLoadContext(this.storage)) {
290
+ throw new FastdbUsageError('fastdb call-db call-db view is not object-graph.');
291
+ }
292
+ return this.storage;
293
+ }
294
+ resolveTable(kind, nameOrIndex) {
295
+ this.ensureOpen();
296
+ const tables = this.binding.tables.filter((table) => table.kind === kind);
297
+ if (typeof nameOrIndex === 'number') {
298
+ const table = tables[nameOrIndex];
299
+ if (!table) {
300
+ throw new FastdbUsageError(`fastdb call-db ${kind} table index ${nameOrIndex} is out of range.`);
301
+ }
302
+ return table;
303
+ }
304
+ const table = tables.find((item) => item.name === nameOrIndex);
305
+ if (!table) {
306
+ throw new FastdbUsageError(`fastdb call-db ${kind} table "${nameOrIndex}" was not found.`);
307
+ }
308
+ return table;
309
+ }
310
+ resolveScalarField(nameOrIndex) {
311
+ this.ensureOpen();
312
+ const fields = this.binding.tables.flatMap((table) => table.kind === 'scalars'
313
+ ? (table.fields ?? []).map((field) => ({ field, spec: table }))
314
+ : []);
315
+ if (typeof nameOrIndex === 'number') {
316
+ const entry = fields[nameOrIndex];
317
+ if (!entry) {
318
+ throw new FastdbUsageError(`fastdb call-db scalar field index ${nameOrIndex} is out of range.`);
319
+ }
320
+ return entry;
321
+ }
322
+ const entry = fields.find((item) => item.field.name === nameOrIndex);
323
+ if (!entry) {
324
+ throw new FastdbUsageError(`fastdb call-db scalar field "${nameOrIndex}" was not found.`);
325
+ }
326
+ return entry;
327
+ }
328
+ }
329
+ class FastdbStridedColumnSource {
330
+ column;
331
+ constructor(column) {
332
+ this.column = column;
333
+ }
334
+ get length() {
335
+ return this.column.length;
336
+ }
337
+ get(index) {
338
+ return this.column.get(index);
339
+ }
340
+ toArray() {
341
+ return this.column.toArray();
342
+ }
343
+ forEach(fn) {
344
+ this.column.forEach((value, index) => fn(value, index));
345
+ }
346
+ }
347
+ class FastdbRowFieldColumnSource {
348
+ view;
349
+ spec;
350
+ fieldName;
351
+ kind;
352
+ constructor(view, spec, fieldName, kind) {
353
+ this.view = view;
354
+ this.spec = spec;
355
+ this.fieldName = fieldName;
356
+ this.kind = kind;
357
+ }
358
+ get length() {
359
+ return this.view.tableLength(this.spec);
360
+ }
361
+ get(index) {
362
+ const row = this.view.tableFeature(this.spec, index);
363
+ return materializeScalarValue(this.kind, row[this.fieldName]);
364
+ }
365
+ toArray() {
366
+ const values = [];
367
+ for (let index = 0; index < this.length; index += 1) {
368
+ values.push(this.get(index));
369
+ }
370
+ return values;
371
+ }
372
+ forEach(fn) {
373
+ for (let index = 0; index < this.length; index += 1) {
374
+ fn(this.get(index), index);
375
+ }
376
+ }
377
+ }
378
+ export class FastdbCallDbTableView {
379
+ view;
380
+ spec;
381
+ columnAccessor = null;
382
+ constructor(view, spec) {
383
+ this.view = view;
384
+ this.spec = spec;
385
+ }
386
+ get length() {
387
+ this.view.ensureOpen();
388
+ return this.view.tableLength(this.spec);
389
+ }
390
+ get column() {
391
+ this.view.ensureOpen();
392
+ if (this.columnAccessor !== null) {
393
+ return this.columnAccessor;
394
+ }
395
+ const tableView = this;
396
+ const accessor = new Proxy({}, {
397
+ get(_, prop) {
398
+ if (typeof prop !== 'string') {
399
+ return undefined;
400
+ }
401
+ tableView.view.ensureOpen();
402
+ const column = tableView.view.tableColumn(tableView.spec, prop);
403
+ if (!column) {
404
+ return undefined;
405
+ }
406
+ return new FastdbCallDbColumnView(tableView.view, column);
407
+ },
408
+ });
409
+ this.columnAccessor = accessor;
410
+ return this.columnAccessor;
411
+ }
412
+ get(index) {
413
+ this.view.ensureOpen();
414
+ return this.view.tableFeature(this.spec, index);
415
+ }
416
+ *[Symbol.iterator]() {
417
+ for (let i = 0; i < this.length; i += 1) {
418
+ yield this.get(i);
419
+ }
420
+ }
421
+ }
422
+ export class FastdbCallDbArrayView {
423
+ view;
424
+ spec;
425
+ constructor(view, spec) {
426
+ this.view = view;
427
+ this.spec = spec;
428
+ }
429
+ get length() {
430
+ this.view.ensureOpen();
431
+ return this.view.tableLength(this.spec);
432
+ }
433
+ get(index) {
434
+ this.view.ensureOpen();
435
+ return this.view.arrayValue(this.spec, index);
436
+ }
437
+ toArray() {
438
+ const values = [];
439
+ for (let i = 0; i < this.length; i += 1) {
440
+ values.push(this.get(i));
441
+ }
442
+ return values;
443
+ }
444
+ *[Symbol.iterator]() {
445
+ for (let i = 0; i < this.length; i += 1) {
446
+ yield this.get(i);
447
+ }
448
+ }
449
+ }
450
+ export class FastdbCallDbColumnView {
451
+ view;
452
+ column;
453
+ constructor(view, column) {
454
+ this.view = view;
455
+ this.column = column;
456
+ }
457
+ get length() {
458
+ this.view.ensureOpen();
459
+ return this.column.length;
460
+ }
461
+ get(index) {
462
+ this.view.ensureOpen();
463
+ return this.column.get(index);
464
+ }
465
+ toArray() {
466
+ this.view.ensureOpen();
467
+ return this.column.toArray();
468
+ }
469
+ forEach(fn) {
470
+ this.view.ensureOpen();
471
+ this.column.forEach(fn);
472
+ }
473
+ }
474
+ function encodeObjectGraphFeature(value) {
475
+ if (!(value instanceof Feature)) {
476
+ throw new FastdbUsageError('fastdb call-db object-graph feature encode expects a Feature value.');
477
+ }
478
+ const ctx = collectObjectGraph([value]);
479
+ return buildObjectGraphPayload(ctx);
480
+ }
481
+ function decodeObjectGraphFeature(featureType, payload) {
482
+ return withObjectGraphLoadContext(payload, [featureType], (ctx) => copyObjectGraphFeature(ctx, featureType, layerIndexForType(ctx.db, featureType), 0));
483
+ }
484
+ function encodeObjectGraphCallDb(binding, values) {
485
+ const dynamicGroups = [];
486
+ const featureRoots = [];
487
+ const explicitFeatureTables = [];
488
+ for (const table of binding.tables) {
489
+ if (table.kind === 'scalars') {
490
+ const featureType = dynamicFeatureForTable(table);
491
+ const rowValues = {};
492
+ for (const field of table.fields ?? []) {
493
+ rowValues[field.name] = valueAt(values, field.valuePosition, table.name);
494
+ }
495
+ dynamicGroups.push({
496
+ featureType,
497
+ layerName: table.name,
498
+ rows: [createDynamicFeature(featureType, rowValues)],
499
+ });
500
+ continue;
501
+ }
502
+ if (table.kind === 'array') {
503
+ const featureType = dynamicFeatureForTable(table);
504
+ const rows = asArray(valueAt(values, requiredPosition(table), table.name), table.name)
505
+ .map((item) => createDynamicFeature(featureType, { value: item }));
506
+ dynamicGroups.push({ featureType, layerName: table.name, rows });
507
+ continue;
508
+ }
509
+ if (table.kind === 'feature') {
510
+ const featureType = requireFeature(table);
511
+ explicitFeatureTables.push(featureType);
512
+ const value = valueAt(values, requiredPosition(table), table.name);
513
+ if (table.cardinality === 'many') {
514
+ for (const item of asArray(value, table.name)) {
515
+ if (!(item instanceof featureType)) {
516
+ throw new FastdbUsageError(`fastdb call-db object-graph table "${table.name}" expects ${featureType.name} rows.`);
517
+ }
518
+ featureRoots.push(item);
519
+ }
520
+ continue;
521
+ }
522
+ if (!(value instanceof featureType)) {
523
+ throw new FastdbUsageError(`fastdb call-db object-graph table "${table.name}" expects a ${featureType.name} value.`);
524
+ }
525
+ featureRoots.push(value);
526
+ continue;
527
+ }
528
+ throw new FastdbUsageError(`Unsupported fastdb call-db object-graph table kind "${table.kind}".`);
529
+ }
530
+ const ctx = collectObjectGraph(featureRoots);
531
+ const featureGroups = ctx.order.map((featureType) => ({
532
+ featureType,
533
+ layerName: featureType.name,
534
+ rows: ctx.groups.get(featureType) ?? [],
535
+ }));
536
+ for (const featureType of explicitFeatureTables) {
537
+ if (!featureGroups.some((group) => group.featureType === featureType)) {
538
+ featureGroups.push({ featureType, layerName: featureType.name, rows: [] });
539
+ }
540
+ }
541
+ return buildObjectGraphPayloadFromGroups([...dynamicGroups, ...featureGroups]);
542
+ }
543
+ function decodeObjectGraphCallDb(binding, payload) {
544
+ const featureTypes = objectGraphBindingFeatureTypes(binding);
545
+ return withObjectGraphLoadContext(payload, featureTypes, (ctx) => {
546
+ return decodeObjectGraphCallDbFromContext(binding, ctx);
547
+ });
548
+ }
549
+ function decodeObjectGraphCallDbFromContext(binding, ctx) {
550
+ const values = new Array(callValueCount(binding)).fill(undefined);
551
+ for (const table of binding.tables) {
552
+ if (table.kind === 'scalars') {
553
+ const featureType = dynamicFeatureForTable(table);
554
+ const layerIdx = layerIndexForName(ctx.db, table.name);
555
+ if (layerIdx === null) {
556
+ throw new FastdbUsageError(`fastdb call-db object-graph scalar table "${table.name}" was not found.`);
557
+ }
558
+ const layer = ctx.db.getLayer(layerIdx);
559
+ if (layer.getFeatureCount() < 1) {
560
+ throw new FastdbUsageError(`fastdb call-db object-graph scalar table "${table.name}" is empty.`);
561
+ }
562
+ const row = copyObjectGraphFeature(ctx, featureType, layerIdx, 0);
563
+ for (const field of table.fields ?? []) {
564
+ values[field.valuePosition] = materializeScalarValue(field.kind, row[field.name]);
565
+ }
566
+ continue;
567
+ }
568
+ if (table.kind === 'array') {
569
+ const featureType = dynamicFeatureForTable(table);
570
+ const layerIdx = layerIndexForName(ctx.db, table.name);
571
+ if (layerIdx === null) {
572
+ values[requiredPosition(table)] = [];
573
+ continue;
574
+ }
575
+ const layer = ctx.db.getLayer(layerIdx);
576
+ values[requiredPosition(table)] = Array.from({ length: layer.getFeatureCount() }, (_, rowIdx) => {
577
+ const row = copyObjectGraphFeature(ctx, featureType, layerIdx, rowIdx);
578
+ return materializeScalarValue(table.item?.kind ?? '', row.value);
579
+ });
580
+ continue;
581
+ }
582
+ if (table.kind !== 'feature') {
583
+ throw new FastdbUsageError(`Unsupported fastdb call-db object-graph table kind "${table.kind}".`);
584
+ }
585
+ const featureType = requireFeature(table);
586
+ const layerIdx = layerIndexForType(ctx.db, featureType);
587
+ if (table.cardinality === 'many') {
588
+ const layer = ctx.db.getLayer(layerIdx);
589
+ values[requiredPosition(table)] = Array.from({ length: layer.getFeatureCount() }, (_, rowIdx) => copyObjectGraphFeature(ctx, featureType, layerIdx, rowIdx));
590
+ }
591
+ else {
592
+ values[requiredPosition(table)] = copyObjectGraphFeature(ctx, featureType, layerIdx, 0);
593
+ }
594
+ }
595
+ if (binding.direction === 'input') {
596
+ return values;
597
+ }
598
+ return values.length === 1 ? values[0] : values;
599
+ }
600
+ function objectGraphBindingFeatureTypes(binding) {
601
+ const types = [];
602
+ const seen = new Set();
603
+ for (const table of binding.tables) {
604
+ if (table.kind !== 'feature') {
605
+ continue;
606
+ }
607
+ const featureType = requireFeature(table);
608
+ if (!seen.has(featureType)) {
609
+ types.push(featureType);
610
+ seen.add(featureType);
611
+ }
612
+ for (const dependency of table.featureDependencies ?? []) {
613
+ if (!seen.has(dependency.feature)) {
614
+ types.push(dependency.feature);
615
+ seen.add(dependency.feature);
616
+ }
617
+ }
618
+ }
619
+ return types;
620
+ }
621
+ function collectObjectGraph(roots) {
622
+ const groups = new Map();
623
+ const seen = new WeakSet();
624
+ const visit = (value) => {
625
+ if (seen.has(value)) {
626
+ return;
627
+ }
628
+ seen.add(value);
629
+ const featureType = value.constructor;
630
+ const rows = groups.get(featureType);
631
+ if (rows) {
632
+ rows.push(value);
633
+ }
634
+ else {
635
+ groups.set(featureType, [value]);
636
+ }
637
+ for (const field of objectGraphTraversalFields(featureType)) {
638
+ const fieldValue = getFeatureFieldValue(value, field.name);
639
+ if (isRefField(field.entry)) {
640
+ if (fieldValue instanceof Feature) {
641
+ visit(fieldValue);
642
+ }
643
+ continue;
644
+ }
645
+ if (Array.isArray(fieldValue)) {
646
+ for (const item of fieldValue) {
647
+ if (item instanceof Feature) {
648
+ visit(item);
649
+ }
650
+ }
651
+ }
652
+ }
653
+ };
654
+ for (const root of roots) {
655
+ visit(root);
656
+ }
657
+ const order = topoSortObjectGraphTypes(groups);
658
+ const locations = new WeakMap();
659
+ for (const [layerIdx, featureType] of order.entries()) {
660
+ const rows = groups.get(featureType) ?? [];
661
+ rows.forEach((row, featureIdx) => locations.set(row, { layerIdx, featureIdx }));
662
+ }
663
+ return { groups, locations, order };
664
+ }
665
+ function buildObjectGraphPayload(ctx) {
666
+ return buildObjectGraphPayloadFromGroups(ctx.order.map((featureType) => ({
667
+ featureType,
668
+ layerName: featureType.name,
669
+ rows: ctx.groups.get(featureType) ?? [],
670
+ })));
671
+ }
672
+ function buildObjectGraphPayloadFromGroups(groups) {
673
+ const module = getInitializedFastdbModule();
674
+ const db = new module.WxDatabaseBuild();
675
+ db.begin('');
676
+ const layerBuilders = new Map();
677
+ const locations = new WeakMap();
678
+ groups.forEach((group, layerIdx) => {
679
+ group.rows.forEach((row, featureIdx) => locations.set(row, { layerIdx, featureIdx }));
680
+ });
681
+ try {
682
+ for (const [layerIdx, group] of groups.entries()) {
683
+ const layer = db.createLayerBegin(group.layerName);
684
+ configureObjectGraphGeometry(module, layer, group.featureType);
685
+ layer.setDbIndex(layerIdx);
686
+ defineObjectGraphFields(layer, group.featureType);
687
+ layerBuilders.set(layerIdx, layer);
688
+ }
689
+ for (const [layerIdx, group] of groups.entries()) {
690
+ const layer = layerBuilders.get(layerIdx);
691
+ if (!layer) {
692
+ throw new FastdbUsageError(`Missing object-graph layer builder for ${group.layerName}.`);
693
+ }
694
+ for (const row of group.rows) {
695
+ writeObjectGraphRow(module, layer, row, locations, layerBuilders);
696
+ }
697
+ }
698
+ const stream = new module.WxMemoryStream();
699
+ try {
700
+ db.post(stream);
701
+ return module.HEAPU8.slice(stream.dataView().data, stream.dataView().data + stream.dataView().size);
702
+ }
703
+ finally {
704
+ stream.delete();
705
+ }
706
+ }
707
+ finally {
708
+ db.delete();
709
+ }
710
+ }
711
+ function configureObjectGraphGeometry(module, layer, featureType) {
712
+ if (featureBytesFieldNames(featureType).length > 0) {
713
+ layer.setGeometryType(module.gtAny, module.cfDefault, false);
714
+ return;
715
+ }
716
+ layer.setGeometryType(module.gtPoint, module.cfTx32, true);
717
+ layer.setExtent(-180, -90, 180, 90);
718
+ }
719
+ function defineObjectGraphFields(layer, featureType) {
720
+ for (const field of getClassSchema(featureType).fieldList) {
721
+ if (isListField(field.entry)) {
722
+ layer.addListField(field.name, objectGraphListElementType(field));
723
+ }
724
+ else {
725
+ layer.addField(field.name, field.entry.originType, 0, 1);
726
+ }
727
+ }
728
+ }
729
+ function writeObjectGraphRow(module, layer, row, locations, layerBuilders) {
730
+ layer.addFeatureBegin();
731
+ try {
732
+ for (const field of getClassSchema(row.constructor).fieldList) {
733
+ const value = getFeatureFieldValue(row, field.name);
734
+ if (isRefField(field.entry)) {
735
+ layer.setFieldRef(field.index, objectGraphRefPtr(value, locations, layerBuilders));
736
+ continue;
737
+ }
738
+ if (isListField(field.entry)) {
739
+ if (isFieldType(resolveListItem(field.entry))) {
740
+ const bytes = encodeNumericListBytes(value, listElementFieldType(field));
741
+ withHeapBytes(module, bytes, (ptr, size) => layer.setFieldListNumeric(field.index, ptr, size));
742
+ }
743
+ else {
744
+ const bytes = encodeObjectGraphRefList(value, locations);
745
+ withHeapBytes(module, bytes, (ptr, size) => layer.setFieldListNumeric(field.index, ptr, size));
746
+ }
747
+ continue;
748
+ }
749
+ writeObjectGraphScalarField(module, layer, field, value);
750
+ }
751
+ }
752
+ finally {
753
+ layer.addFeatureEnd();
754
+ }
755
+ }
756
+ function writeObjectGraphScalarField(module, layer, field, value) {
757
+ switch (field.entry.kind) {
758
+ case 'bool':
759
+ layer.setFieldInt(field.index, coerceBoolScalar(value) ? 1 : 0);
760
+ return;
761
+ case 'u8':
762
+ case 'u16':
763
+ case 'u32':
764
+ case 'i32':
765
+ case 'u8n':
766
+ case 'u16n':
767
+ layer.setFieldInt(field.index, Math.trunc(Number(value)));
768
+ return;
769
+ case 'f32':
770
+ case 'f64':
771
+ layer.setFieldDouble(field.index, Number(value));
772
+ return;
773
+ case 'str':
774
+ layer.setFieldString(field.index, String(value ?? ''));
775
+ return;
776
+ case 'wstr':
777
+ layer.setFieldWString(field.index, String(value ?? ''));
778
+ return;
779
+ case 'bytes': {
780
+ const bytes = normalizeBytes(value);
781
+ withHeapBytes(module, bytes, (ptr, size) => layer.setGeometryRaw(ptr, size));
782
+ return;
783
+ }
784
+ default:
785
+ throw new FastdbUsageError(`Unsupported object-graph field kind "${field.entry.kind}" on "${field.name}".`);
786
+ }
787
+ }
788
+ function objectGraphRefPtr(value, locations, layerBuilders) {
789
+ if (!(value instanceof Feature)) {
790
+ return 0;
791
+ }
792
+ const location = locations.get(value);
793
+ if (!location) {
794
+ return 0;
795
+ }
796
+ const layer = layerBuilders.get(location.layerIdx);
797
+ if (!layer) {
798
+ return 0;
799
+ }
800
+ return layer.createFeatureRef(location.featureIdx);
801
+ }
802
+ function encodeObjectGraphRefList(value, locations) {
803
+ const items = Array.isArray(value) ? value : [];
804
+ const bytes = new Uint8Array(items.length * 5);
805
+ const view = new DataView(bytes.buffer);
806
+ items.forEach((item, index) => {
807
+ if (!(item instanceof Feature)) {
808
+ return;
809
+ }
810
+ const location = locations.get(item);
811
+ if (!location) {
812
+ return;
813
+ }
814
+ const offset = index * 5;
815
+ view.setUint16(offset, location.layerIdx, true);
816
+ view.setUint8(offset + 2, location.featureIdx & 0xff);
817
+ view.setUint16(offset + 3, location.featureIdx >> 8, true);
818
+ });
819
+ return bytes;
820
+ }
821
+ function withObjectGraphLoadContext(payload, featureTypes, fn) {
822
+ const ctx = loadObjectGraphContext(payload, featureTypes);
823
+ try {
824
+ return fn(ctx);
825
+ }
826
+ finally {
827
+ ctx.db.delete();
828
+ }
829
+ }
830
+ function loadObjectGraphContext(payload, featureTypes) {
831
+ const module = getInitializedFastdbModule();
832
+ const db = loadDatabaseFromBytes(module, payload);
833
+ try {
834
+ const typeByLayerName = new Map();
835
+ for (const featureType of featureTypes) {
836
+ typeByLayerName.set(featureType.name, featureType);
837
+ for (const dependency of discoverObjectGraphTypes(featureType)) {
838
+ typeByLayerName.set(dependency.name, dependency);
839
+ }
840
+ }
841
+ return { db, module, seen: new Map(), typeByLayerName };
842
+ }
843
+ catch (error) {
844
+ db.delete();
845
+ throw error;
846
+ }
847
+ }
848
+ function isObjectGraphLoadContext(value) {
849
+ return typeof value === 'object' && value !== null && 'db' in value && 'module' in value && 'seen' in value;
850
+ }
851
+ function copyObjectGraphFeature(ctx, expectedType, layerIdx, rowIdx) {
852
+ const key = `${layerIdx}:${rowIdx}`;
853
+ const cached = ctx.seen.get(key);
854
+ if (cached) {
855
+ return cached;
856
+ }
857
+ const layer = ctx.db.getLayer(layerIdx);
858
+ const featureType = ctx.typeByLayerName.get(layer.name()) ?? expectedType;
859
+ const row = layer.tryGetFeatureAt(rowIdx);
860
+ const copy = createFeature(featureType);
861
+ ctx.seen.set(key, copy);
862
+ const cache = copy._getCache();
863
+ for (const field of getClassSchema(featureType).fieldList) {
864
+ cache[field.name] = readObjectGraphField(ctx, row, field);
865
+ }
866
+ return copy;
867
+ }
868
+ function readObjectGraphField(ctx, row, field) {
869
+ if (isRefField(field.entry)) {
870
+ const refPtr = row.getFieldAsRef(field.index);
871
+ return copyObjectGraphRef(ctx, refPtr, field.target);
872
+ }
873
+ if (isListField(field.entry)) {
874
+ const item = resolveListItem(field.entry);
875
+ if (isFieldType(item)) {
876
+ const listView = row.getFieldAsListView(field.index);
877
+ return decodeNumericListBytes(ctx.module.HEAPU8.slice(listView.data, listView.data + listView.size), item);
878
+ }
879
+ const values = [];
880
+ const count = row.getFieldListSize(field.index);
881
+ for (let index = 0; index < count; index += 1) {
882
+ values.push(copyObjectGraphRef(ctx, row.getFieldListRefAt(field.index, index), item));
883
+ }
884
+ return values;
885
+ }
886
+ return readObjectGraphScalarField(ctx.module, row, field);
887
+ }
888
+ function copyObjectGraphRef(ctx, refPtr, declaredTarget) {
889
+ const ref = decodeFeatureRef(ctx.module, refPtr);
890
+ if (ref === null) {
891
+ return null;
892
+ }
893
+ const { layerIdx, rowIdx } = ref;
894
+ const layer = ctx.db.getLayer(layerIdx);
895
+ const target = declaredTarget ?? ctx.typeByLayerName.get(layer.name());
896
+ if (!target) {
897
+ return null;
898
+ }
899
+ return copyObjectGraphFeature(ctx, target, layerIdx, rowIdx);
900
+ }
901
+ function decodeFeatureRef(module, refPtr) {
902
+ if (!refPtr) {
903
+ return null;
904
+ }
905
+ const heap = module.HEAPU8;
906
+ const layerIdx = heap[refPtr] | (heap[refPtr + 1] << 8);
907
+ const rowIdx = heap[refPtr + 2] | (heap[refPtr + 3] << 8) | (heap[refPtr + 4] << 16);
908
+ return { layerIdx, rowIdx };
909
+ }
910
+ function readObjectGraphScalarField(module, row, field) {
911
+ switch (field.entry.kind) {
912
+ case 'bool':
913
+ return row.getFieldAsInt(field.index) !== 0;
914
+ case 'u8':
915
+ case 'u16':
916
+ case 'u32':
917
+ case 'i32':
918
+ case 'u8n':
919
+ case 'u16n':
920
+ return row.getFieldAsInt(field.index);
921
+ case 'f32':
922
+ case 'f64':
923
+ return row.getFieldAsFloat(field.index);
924
+ case 'str':
925
+ return row.getFieldAsString(field.index);
926
+ case 'wstr':
927
+ return row.getFieldAsWString(field.index);
928
+ case 'bytes':
929
+ return module.HEAPU8.slice(row.geometryView().data, row.geometryView().data + row.geometryView().size);
930
+ default:
931
+ throw new FastdbUsageError(`Unsupported object-graph field kind "${field.entry.kind}" on "${field.name}".`);
932
+ }
933
+ }
934
+ function objectGraphTraversalFields(featureType) {
935
+ const fields = [];
936
+ for (const field of getClassSchema(featureType).fieldList) {
937
+ if (isRefField(field.entry)) {
938
+ fields.push(field);
939
+ continue;
940
+ }
941
+ if (!isListField(field.entry)) {
942
+ continue;
943
+ }
944
+ if (!isFieldType(resolveListItem(field.entry))) {
945
+ fields.push(field);
946
+ }
947
+ }
948
+ return fields;
949
+ }
950
+ function discoverObjectGraphTypes(root) {
951
+ const out = [];
952
+ const seen = new Set();
953
+ const visit = (featureType) => {
954
+ if (seen.has(featureType)) {
955
+ return;
956
+ }
957
+ seen.add(featureType);
958
+ out.push(featureType);
959
+ for (const field of objectGraphTraversalFields(featureType)) {
960
+ if (isRefField(field.entry) && field.target) {
961
+ visit(field.target);
962
+ }
963
+ else if (isListField(field.entry)) {
964
+ const item = resolveListItem(field.entry);
965
+ if (!isFieldType(item)) {
966
+ visit(item);
967
+ }
968
+ }
969
+ }
970
+ };
971
+ visit(root);
972
+ return out;
973
+ }
974
+ function topoSortObjectGraphTypes(groups) {
975
+ const inDegree = new Map();
976
+ const outgoing = new Map();
977
+ for (const featureType of groups.keys()) {
978
+ inDegree.set(featureType, 0);
979
+ outgoing.set(featureType, []);
980
+ }
981
+ for (const featureType of groups.keys()) {
982
+ const deps = new Set();
983
+ for (const field of objectGraphTraversalFields(featureType)) {
984
+ let dependency;
985
+ if (isRefField(field.entry)) {
986
+ dependency = field.target;
987
+ }
988
+ else if (isListField(field.entry)) {
989
+ const item = resolveListItem(field.entry);
990
+ dependency = isFieldType(item) ? undefined : item;
991
+ }
992
+ if (dependency && dependency !== featureType && groups.has(dependency)) {
993
+ deps.add(dependency);
994
+ }
995
+ }
996
+ for (const dependency of deps) {
997
+ outgoing.get(dependency)?.push(featureType);
998
+ inDegree.set(featureType, (inDegree.get(featureType) ?? 0) + 1);
999
+ }
1000
+ }
1001
+ const queue = Array.from(groups.keys()).filter((featureType) => (inDegree.get(featureType) ?? 0) === 0);
1002
+ const out = [];
1003
+ while (queue.length > 0) {
1004
+ const current = queue.shift();
1005
+ out.push(current);
1006
+ for (const dependent of outgoing.get(current) ?? []) {
1007
+ const nextDegree = (inDegree.get(dependent) ?? 0) - 1;
1008
+ inDegree.set(dependent, nextDegree);
1009
+ if (nextDegree === 0) {
1010
+ queue.push(dependent);
1011
+ }
1012
+ }
1013
+ }
1014
+ if (out.length !== groups.size) {
1015
+ throw new FastdbUsageError('fastdb call-db object-graph runtime does not support circular class-level references.');
1016
+ }
1017
+ return out;
1018
+ }
1019
+ function layerIndexForType(db, featureType) {
1020
+ for (let index = 0; index < db.getLayerCount(); index += 1) {
1021
+ if (db.getLayer(index).name() === featureType.name) {
1022
+ return index;
1023
+ }
1024
+ }
1025
+ throw new FastdbUsageError(`fastdb call-db object-graph layer "${featureType.name}" was not found.`);
1026
+ }
1027
+ function layerIndexForName(db, name) {
1028
+ for (let index = 0; index < db.getLayerCount(); index += 1) {
1029
+ if (db.getLayer(index).name() === name) {
1030
+ return index;
1031
+ }
1032
+ }
1033
+ return null;
1034
+ }
1035
+ function objectGraphListElementType(field) {
1036
+ if (!isListField(field.entry)) {
1037
+ throw new FastdbUsageError(`Field "${field.name}" is not a list field.`);
1038
+ }
1039
+ const item = resolveListItem(field.entry);
1040
+ if (isFieldType(item)) {
1041
+ if (!isSupportedNativeListKind(item.kind)) {
1042
+ throw new FastdbUsageError(`List field "${field.name}" uses unsupported item kind "${item.kind}".`);
1043
+ }
1044
+ return item.originType;
1045
+ }
1046
+ return 11;
1047
+ }
1048
+ function listElementFieldType(field) {
1049
+ if (!isListField(field.entry)) {
1050
+ throw new FastdbUsageError(`Field "${field.name}" is not a list field.`);
1051
+ }
1052
+ const item = resolveListItem(field.entry);
1053
+ if (!isFieldType(item) || !item.arrayCtor || !isSupportedNativeListKind(item.kind)) {
1054
+ throw new FastdbUsageError(`List field "${field.name}" supports only native numeric scalar list elements.`);
1055
+ }
1056
+ return item;
1057
+ }
1058
+ function encodeNumericListBytes(value, item) {
1059
+ if (value === null || value === undefined) {
1060
+ return new Uint8Array(0);
1061
+ }
1062
+ if (!item.arrayCtor) {
1063
+ throw new FastdbUsageError(`List item kind "${item.kind}" does not have a typed-array representation.`);
1064
+ }
1065
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView) && value.constructor === item.arrayCtor) {
1066
+ const view = value;
1067
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1068
+ }
1069
+ if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && !(value instanceof DataView))) {
1070
+ throw new FastdbUsageError('fastdb call-db object-graph numeric list fields expect array or typed-array values.');
1071
+ }
1072
+ const values = Array.from(value);
1073
+ const typed = new item.arrayCtor(values.length);
1074
+ for (let index = 0; index < values.length; index += 1) {
1075
+ typed[index] = item.kind === 'bool' ? (coerceBoolScalar(values[index]) ? 1 : 0) : Number(values[index]);
1076
+ }
1077
+ return new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);
1078
+ }
1079
+ function decodeNumericListBytes(bytes, item) {
1080
+ if (bytes.length === 0) {
1081
+ return [];
1082
+ }
1083
+ if (!item.arrayCtor) {
1084
+ throw new FastdbUsageError(`List item kind "${item.kind}" does not have a typed-array representation.`);
1085
+ }
1086
+ const bytesPerElement = item.arrayCtor.BYTES_PER_ELEMENT;
1087
+ if (bytes.length % bytesPerElement !== 0) {
1088
+ throw new FastdbUsageError(`fastdb call-db list payload has ${bytes.length} byte(s), not a multiple of ${bytesPerElement}.`);
1089
+ }
1090
+ const source = typedArraySource(bytes);
1091
+ const typed = new item.arrayCtor(source.buffer, source.byteOffset, bytes.length / bytesPerElement);
1092
+ if (item.kind === 'bool') {
1093
+ return Array.from(typed, (value) => coerceBoolScalar(value));
1094
+ }
1095
+ return Array.from(typed);
1096
+ }
1097
+ function typedArraySource(bytes) {
1098
+ if (bytes.buffer instanceof ArrayBuffer) {
1099
+ return { buffer: bytes.buffer, byteOffset: bytes.byteOffset };
1100
+ }
1101
+ const copy = bytes.slice();
1102
+ return { buffer: copy.buffer, byteOffset: copy.byteOffset };
1103
+ }
1104
+ function isSupportedNativeListKind(kind) {
1105
+ return kind === 'bool' || kind === 'u8' || kind === 'u16' || kind === 'u32' || kind === 'i32' || kind === 'u8n' || kind === 'u16n' || kind === 'f32' || kind === 'f64';
1106
+ }
1107
+ function normalizeBytes(value) {
1108
+ if (value === null || value === undefined) {
1109
+ return new Uint8Array(0);
1110
+ }
1111
+ if (value instanceof Uint8Array) {
1112
+ return value;
1113
+ }
1114
+ if (value instanceof ArrayBuffer) {
1115
+ return new Uint8Array(value);
1116
+ }
1117
+ if (ArrayBuffer.isView(value)) {
1118
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1119
+ }
1120
+ throw new FastdbUsageError(`fastdb call-db bytes fields expect Uint8Array or ArrayBuffer, got "${typeof value}".`);
1121
+ }
1122
+ function withHeapBytes(module, bytes, fn) {
1123
+ if (bytes.length === 0) {
1124
+ return fn(0, 0);
1125
+ }
1126
+ const ptr = module._malloc(bytes.length);
1127
+ try {
1128
+ module.HEAPU8.set(bytes, ptr);
1129
+ return fn(ptr, bytes.length);
1130
+ }
1131
+ finally {
1132
+ module._free(ptr);
1133
+ }
1134
+ }
1135
+ function isFieldType(value) {
1136
+ return typeof value === 'object' && value !== null && 'kind' in value && 'originType' in value;
1137
+ }
1138
+ function getFeatureFieldValue(feature, fieldName) {
1139
+ const cache = feature._cache;
1140
+ if (cache && fieldName in cache) {
1141
+ return cache[fieldName];
1142
+ }
1143
+ return feature[fieldName];
1144
+ }
1145
+ function ensureColumnarCallDb(binding) {
1146
+ ensureCodecId(binding.codecId, CALL_DB_CODEC_ID);
1147
+ if (binding.profile !== CALL_DB_COLUMNAR_PROFILE) {
1148
+ throw new FastdbUsageError(`Unsupported fastdb call-db call-db profile "${binding.profile}".`);
1149
+ }
1150
+ ensureCallDbTableShape(binding);
1151
+ ensureColumnarCallDbRuntime(binding);
1152
+ }
1153
+ function ensureCodecId(actual, expected) {
1154
+ if (actual !== expected) {
1155
+ throw new FastdbUsageError(`fastdb call-db runtime expected codec id "${expected}", got "${actual}".`);
1156
+ }
1157
+ }
1158
+ function ensureFeatureValue(value, featureType, context) {
1159
+ if (!(value instanceof featureType)) {
1160
+ throw new FastdbUsageError(`fastdb call-db ${context} expects a ${featureType.name} value.`);
1161
+ }
1162
+ return value;
1163
+ }
1164
+ function objectGraphFeatureForTable(table) {
1165
+ if (table.kind !== 'feature') {
1166
+ throw new FastdbUsageError(`fastdb call-db object-graph table "${table.name}" is not a feature table.`);
1167
+ }
1168
+ return requireFeature(table);
1169
+ }
1170
+ function ensureObjectGraphFeatureRuntime(featureType, context) {
1171
+ const schema = getClassSchema(featureType);
1172
+ const bytesFields = featureBytesFieldNames(featureType);
1173
+ if (bytesFields.length > 1) {
1174
+ throw new FastdbUsageError(`${context} cannot represent multiple bytes fields ${JSON.stringify(bytesFields)}; fastdb object-graph bytes use the feature raw payload.`);
1175
+ }
1176
+ for (const field of schema.fieldList) {
1177
+ if (isListField(field.entry)) {
1178
+ const item = resolveListItem(field.entry);
1179
+ if (isFieldType(item) && (!item.arrayCtor || !isSupportedNativeListKind(item.kind))) {
1180
+ throw new FastdbUsageError(`${context} cannot represent list field "${field.name}" with item kind "${item.kind}" in the object-graph runtime.`);
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ function featureBytesFieldNames(featureType) {
1186
+ return getClassSchema(featureType).fieldList
1187
+ .filter((field) => field.entry.kind === 'bytes')
1188
+ .map((field) => field.name);
1189
+ }
1190
+ function ensureObjectGraphCallDb(binding) {
1191
+ ensureCodecId(binding.codecId, CALL_DB_CODEC_ID);
1192
+ if (binding.profile !== CALL_DB_OBJECT_GRAPH_PROFILE) {
1193
+ throw new FastdbUsageError(`Unsupported fastdb call-db call-db profile "${binding.profile}".`);
1194
+ }
1195
+ ensureCallDbTableShape(binding);
1196
+ const layerNames = new Map();
1197
+ const claimLayerName = (layerName, owner, kind) => {
1198
+ const previous = layerNames.get(layerName);
1199
+ if (previous !== undefined) {
1200
+ if (previous.kind === 'dependency' && kind === 'dependency' && previous.owner === owner) {
1201
+ return;
1202
+ }
1203
+ throw new FastdbUsageError(`fastdb object-graph call-db cannot encode both "${previous.owner}" and "${owner}" as layer "${layerName}". Use distinct feature wrapper types or table names.`);
1204
+ }
1205
+ layerNames.set(layerName, { kind, owner });
1206
+ };
1207
+ for (const table of binding.tables) {
1208
+ if (table.kind === 'feature') {
1209
+ const featureType = objectGraphFeatureForTable(table);
1210
+ claimLayerName(featureType.name, `feature table ${table.name}`, 'feature-table');
1211
+ ensureObjectGraphFeatureRuntime(featureType, `fastdb call-db object-graph call-db table "${table.name}"`);
1212
+ for (const dependency of table.featureDependencies ?? []) {
1213
+ claimLayerName(dependency.feature.name, `dependency ${dependency.feature.name}`, 'dependency');
1214
+ ensureObjectGraphFeatureRuntime(dependency.feature, `fastdb call-db object-graph call-db dependency "${dependency.feature.name}"`);
1215
+ }
1216
+ continue;
1217
+ }
1218
+ if (table.kind === 'array') {
1219
+ claimLayerName(table.name, `table ${table.name}`, 'table');
1220
+ if (!table.item) {
1221
+ throw new FastdbUsageError(`fastdb call-db object-graph array table "${table.name}" is missing item metadata.`);
1222
+ }
1223
+ ensureObjectGraphScalarKind(table.item.kind, `fastdb call-db object-graph array table "${table.name}" item`);
1224
+ continue;
1225
+ }
1226
+ if (table.kind === 'scalars') {
1227
+ claimLayerName(table.name, `table ${table.name}`, 'table');
1228
+ const bytesFields = (table.fields ?? [])
1229
+ .filter((field) => field.kind === 'bytes')
1230
+ .map((field) => field.name);
1231
+ if (bytesFields.length > 1) {
1232
+ throw new FastdbUsageError(`fastdb call-db object-graph scalar table "${table.name}" cannot represent multiple bytes fields ${JSON.stringify(bytesFields)}; fastdb object-graph bytes use the feature raw payload.`);
1233
+ }
1234
+ for (const field of table.fields ?? []) {
1235
+ ensureObjectGraphScalarKind(field.kind, `fastdb call-db object-graph scalar field "${field.name}"`);
1236
+ }
1237
+ continue;
1238
+ }
1239
+ throw new FastdbUsageError(`Unsupported fastdb call-db object-graph table kind "${table.kind}".`);
1240
+ }
1241
+ }
1242
+ function ensureCallDbTableShape(binding) {
1243
+ if (typeof binding.method !== 'string' || binding.method.length === 0) {
1244
+ throw new FastdbUsageError('fastdb call-db call-db binding must include a non-empty method name.');
1245
+ }
1246
+ if (binding.direction !== 'input' && binding.direction !== 'output') {
1247
+ throw new FastdbUsageError('fastdb call-db call-db binding direction must be "input" or "output".');
1248
+ }
1249
+ if (!Array.isArray(binding.tables)) {
1250
+ throw new FastdbUsageError('fastdb call-db call-db binding tables must be an array.');
1251
+ }
1252
+ const tableNames = new Set();
1253
+ const positions = [];
1254
+ for (const entry of binding.tables) {
1255
+ if (typeof entry !== 'object' || entry === null) {
1256
+ throw new FastdbUsageError('fastdb call-db call-db table entries must be objects.');
1257
+ }
1258
+ const table = entry;
1259
+ if (typeof table.name !== 'string' || table.name.length === 0) {
1260
+ throw new FastdbUsageError('fastdb call-db call-db table entries must include a non-empty name.');
1261
+ }
1262
+ if (tableNames.has(table.name)) {
1263
+ throw new FastdbUsageError(`fastdb call-db call-db duplicate table name "${table.name}".`);
1264
+ }
1265
+ tableNames.add(table.name);
1266
+ if (table.kind === 'scalars') {
1267
+ if (table.cardinality !== 'one') {
1268
+ throw new FastdbUsageError(`fastdb call-db scalar table "${table.name}" must have cardinality "one".`);
1269
+ }
1270
+ if (!Array.isArray(table.fields)) {
1271
+ throw new FastdbUsageError(`fastdb call-db scalar table "${table.name}" must include fields metadata.`);
1272
+ }
1273
+ const scalarFieldNames = new Set();
1274
+ for (const entry of table.fields) {
1275
+ if (typeof entry !== 'object' || entry === null) {
1276
+ throw new FastdbUsageError(`fastdb call-db scalar table "${table.name}" field entries must be objects.`);
1277
+ }
1278
+ const field = entry;
1279
+ if (typeof field.name !== 'string' || field.name.length === 0) {
1280
+ throw new FastdbUsageError(`fastdb call-db scalar table "${table.name}" fields must include non-empty names.`);
1281
+ }
1282
+ if (scalarFieldNames.has(field.name)) {
1283
+ throw new FastdbUsageError(`fastdb call-db duplicate scalar field name "${field.name}".`);
1284
+ }
1285
+ scalarFieldNames.add(field.name);
1286
+ positions.push({
1287
+ owner: `scalar field "${field.name}"`,
1288
+ position: requireCallValuePosition(field.valuePosition, `fastdb call-db scalar field "${field.name}"`),
1289
+ });
1290
+ }
1291
+ continue;
1292
+ }
1293
+ if (table.kind === 'array') {
1294
+ if (table.cardinality !== 'many') {
1295
+ throw new FastdbUsageError(`fastdb call-db array table "${table.name}" must have cardinality "many".`);
1296
+ }
1297
+ if (typeof table.item !== 'object' || table.item === null) {
1298
+ throw new FastdbUsageError(`fastdb call-db array table "${table.name}" must include item metadata.`);
1299
+ }
1300
+ if (table.item.name !== CALL_DB_ARRAY_VALUE_FIELD) {
1301
+ throw new FastdbUsageError(`fastdb call-db array table "${table.name}" item name must be "${CALL_DB_ARRAY_VALUE_FIELD}".`);
1302
+ }
1303
+ positions.push({
1304
+ owner: `array table "${table.name}"`,
1305
+ position: requireCallValuePosition(table.valuePosition, `fastdb call-db array table "${table.name}"`),
1306
+ });
1307
+ continue;
1308
+ }
1309
+ if (table.kind === 'feature') {
1310
+ if (table.cardinality !== 'one' && table.cardinality !== 'many') {
1311
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" must have cardinality "one" or "many".`);
1312
+ }
1313
+ if (typeof table.featureSchemaSha256 !== 'string' || table.featureSchemaSha256.length === 0) {
1314
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" must include a non-empty feature schema hash.`);
1315
+ }
1316
+ if (table.featureDependencies !== undefined) {
1317
+ if (!Array.isArray(table.featureDependencies)) {
1318
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" dependencies must be an array.`);
1319
+ }
1320
+ for (const entry of table.featureDependencies) {
1321
+ if (typeof entry !== 'object' || entry === null) {
1322
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" dependency entries must be objects.`);
1323
+ }
1324
+ const dependency = entry;
1325
+ if (typeof dependency.featureSchemaSha256 !== 'string' || dependency.featureSchemaSha256.length === 0) {
1326
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" dependency schema hash must be non-empty.`);
1327
+ }
1328
+ }
1329
+ }
1330
+ positions.push({
1331
+ owner: `feature table "${table.name}"`,
1332
+ position: requireCallValuePosition(table.valuePosition, `fastdb call-db feature table "${table.name}"`),
1333
+ });
1334
+ continue;
1335
+ }
1336
+ throw new FastdbUsageError(`Unsupported fastdb call-db table kind "${table.kind}".`);
1337
+ }
1338
+ ensureCallValuePositions(positions);
1339
+ }
1340
+ function requireCallValuePosition(position, context) {
1341
+ if (!Number.isInteger(position) || position < 0) {
1342
+ throw new FastdbUsageError(`${context} must include a non-negative integer valuePosition.`);
1343
+ }
1344
+ return position;
1345
+ }
1346
+ function ensureCallValuePositions(positions) {
1347
+ const seen = new Map();
1348
+ const duplicates = [];
1349
+ for (const { position, owner } of positions) {
1350
+ const previous = seen.get(position);
1351
+ if (previous !== undefined) {
1352
+ duplicates.push(`${position} used by ${previous} and ${owner}`);
1353
+ continue;
1354
+ }
1355
+ seen.set(position, owner);
1356
+ }
1357
+ if (duplicates.length > 0) {
1358
+ throw new FastdbUsageError(`fastdb call-db call-db duplicate valuePosition metadata: ${duplicates.join(', ')}.`);
1359
+ }
1360
+ const actual = [...seen.keys()].sort((left, right) => left - right);
1361
+ const expected = Array.from({ length: actual.length }, (_unused, index) => index);
1362
+ if (actual.length !== expected.length || actual.some((position, index) => position !== expected[index])) {
1363
+ throw new FastdbUsageError(`fastdb call-db call-db valuePosition metadata must be contiguous from 0; got ${JSON.stringify(actual)}.`);
1364
+ }
1365
+ }
1366
+ function ensureObjectGraphScalarKind(kind, context) {
1367
+ if (kind === 'list') {
1368
+ throw new FastdbUsageError(`${context} cannot represent list scalar metadata in the TypeScript object-graph call-db runtime yet; array-table list item support is not implemented.`);
1369
+ }
1370
+ if (kind === 'ref') {
1371
+ throw new FastdbUsageError(`${context} cannot represent ref scalar metadata in object-graph call-db.`);
1372
+ }
1373
+ if (!FIELD_TYPES[kind]) {
1374
+ throw new FastdbUsageError(`Unsupported fastdb call-db object-graph scalar kind "${kind}".`);
1375
+ }
1376
+ }
1377
+ function ensureColumnarCallDbRuntime(binding) {
1378
+ for (const table of binding.tables) {
1379
+ if (table.kind === 'feature') {
1380
+ ensureColumnarFeatureRuntime(requireFeature(table), `fastdb call-db call-db feature table "${table.name}"`);
1381
+ if ((table.featureDependencies ?? []).length > 0) {
1382
+ throw new FastdbUsageError(`fastdb call-db call-db feature table "${table.name}" dependencies are only valid for object-graph call-db.`);
1383
+ }
1384
+ continue;
1385
+ }
1386
+ if (table.kind === 'array') {
1387
+ if (!table.item) {
1388
+ throw new FastdbUsageError(`fastdb call-db array table "${table.name}" is missing item metadata.`);
1389
+ }
1390
+ ensureColumnarScalarKind(table.item.kind, `fastdb call-db call-db array table "${table.name}" item`);
1391
+ continue;
1392
+ }
1393
+ if (table.kind === 'scalars') {
1394
+ const bytesFields = (table.fields ?? [])
1395
+ .filter((field) => field.kind === 'bytes')
1396
+ .map((field) => field.name);
1397
+ if (bytesFields.length > 1) {
1398
+ throw new FastdbUsageError(`fastdb call-db call-db scalar table "${table.name}" cannot represent multiple bytes fields ${JSON.stringify(bytesFields)}; fastdb columnar bytes use the feature raw payload.`);
1399
+ }
1400
+ for (const field of table.fields ?? []) {
1401
+ ensureColumnarScalarKind(field.kind, `fastdb call-db call-db scalar field "${field.name}"`);
1402
+ }
1403
+ continue;
1404
+ }
1405
+ throw new FastdbUsageError(`Unsupported fastdb call-db table kind "${table.kind}".`);
1406
+ }
1407
+ }
1408
+ function ensureColumnarFeatureRuntime(featureType, context) {
1409
+ if (VALIDATED_COLUMNAR_FEATURES.has(featureType)) {
1410
+ return;
1411
+ }
1412
+ const schema = getClassSchema(featureType);
1413
+ const bytesFields = schema.fieldList
1414
+ .filter((field) => field.entry.kind === 'bytes')
1415
+ .map((field) => field.name);
1416
+ if (bytesFields.length > 1) {
1417
+ throw new FastdbUsageError(`${context} cannot represent multiple bytes fields ${JSON.stringify(bytesFields)}; fastdb columnar bytes use the feature raw payload.`);
1418
+ }
1419
+ for (const field of schema.fieldList) {
1420
+ const kind = field.entry.kind;
1421
+ if (kind === 'list') {
1422
+ ensureSupportedColumnarListField(field, context);
1423
+ continue;
1424
+ }
1425
+ if (kind === 'ref') {
1426
+ throw new FastdbUsageError(`${context} cannot represent ref field "${field.name}"; use org.fastdb.object-graph for object references.`);
1427
+ }
1428
+ }
1429
+ VALIDATED_COLUMNAR_FEATURES.add(featureType);
1430
+ }
1431
+ function ensureSupportedColumnarListField(field, context) {
1432
+ if (!isListField(field.entry)) {
1433
+ return;
1434
+ }
1435
+ const item = resolveListItem(field.entry);
1436
+ if (!isFieldType(item)) {
1437
+ throw new FastdbUsageError(`${context} cannot represent list[ref] field "${field.name}"; use org.fastdb.object-graph for object references.`);
1438
+ }
1439
+ if (!item.arrayCtor || !isSupportedNativeListKind(item.kind)) {
1440
+ throw new FastdbUsageError(`${context} cannot represent list field "${field.name}" with item kind "${item.kind}" in the TypeScript columnar runtime.`);
1441
+ }
1442
+ }
1443
+ function ensureColumnarScalarKind(kind, context) {
1444
+ if (kind === 'list') {
1445
+ throw new FastdbUsageError(`${context} cannot represent list scalar metadata in the TypeScript FastDB runtime yet; array-table list item support is not implemented.`);
1446
+ }
1447
+ if (kind === 'ref') {
1448
+ throw new FastdbUsageError(`${context} cannot represent ref scalar metadata in columnar call-db.`);
1449
+ }
1450
+ if (!FIELD_TYPES[kind]) {
1451
+ throw new FastdbUsageError(`Unsupported fastdb call-db scalar kind "${kind}".`);
1452
+ }
1453
+ }
1454
+ function encodeCallTable(orm, table, values) {
1455
+ if (table.kind === 'scalars') {
1456
+ const featureType = dynamicFeatureForTable(table);
1457
+ const rowValues = {};
1458
+ for (const field of table.fields ?? []) {
1459
+ rowValues[field.name] = valueAt(values, field.valuePosition, table.name);
1460
+ }
1461
+ orm.push(createDynamicFeature(featureType, rowValues), table.name);
1462
+ return;
1463
+ }
1464
+ if (table.kind === 'array') {
1465
+ const featureType = dynamicFeatureForTable(table);
1466
+ const items = asArray(valueAt(values, requiredPosition(table), table.name), table.name);
1467
+ if (items.length === 0) {
1468
+ orm.ensureTable(featureType, table.name);
1469
+ return;
1470
+ }
1471
+ for (const item of items) {
1472
+ orm.push(createDynamicFeature(featureType, { value: item }), table.name);
1473
+ }
1474
+ return;
1475
+ }
1476
+ if (table.kind === 'feature') {
1477
+ const featureType = requireFeature(table);
1478
+ const value = valueAt(values, requiredPosition(table), table.name);
1479
+ if (table.cardinality === 'many') {
1480
+ const items = asArray(value, table.name);
1481
+ if (items.length === 0) {
1482
+ orm.ensureTable(featureType, table.name);
1483
+ return;
1484
+ }
1485
+ for (const item of items) {
1486
+ if (!(item instanceof Feature)) {
1487
+ throw new FastdbUsageError(`fastdb call-db table "${table.name}" expects Feature rows.`);
1488
+ }
1489
+ orm.push(item, table.name);
1490
+ }
1491
+ return;
1492
+ }
1493
+ if (!(value instanceof Feature)) {
1494
+ throw new FastdbUsageError(`fastdb call-db table "${table.name}" expects a Feature value.`);
1495
+ }
1496
+ orm.push(value, table.name);
1497
+ return;
1498
+ }
1499
+ throw new FastdbUsageError(`Unsupported fastdb call-db table kind "${table.kind}".`);
1500
+ }
1501
+ function tryEncodeColumnarCallDbFastPath(binding, values) {
1502
+ if (binding.tables.length === 0) {
1503
+ return null;
1504
+ }
1505
+ for (const table of binding.tables) {
1506
+ if (!canUseColumnarFastPath(table)) {
1507
+ return null;
1508
+ }
1509
+ }
1510
+ const plans = [];
1511
+ for (const table of binding.tables) {
1512
+ const plan = columnarFastPathPlan(table, values);
1513
+ if (plan === null) {
1514
+ return null;
1515
+ }
1516
+ plans.push(plan);
1517
+ }
1518
+ const orm = ORM.create();
1519
+ try {
1520
+ for (const plan of plans) {
1521
+ appendColumnarFastPathPlan(orm, plan);
1522
+ }
1523
+ orm.combine();
1524
+ return orm.toBuffer();
1525
+ }
1526
+ finally {
1527
+ orm.close();
1528
+ }
1529
+ }
1530
+ function canUseColumnarFastPath(table) {
1531
+ if (table.kind === 'scalars') {
1532
+ return (table.fields ?? []).every((field) => canBulkAppendKind(field.kind));
1533
+ }
1534
+ if (table.kind === 'array') {
1535
+ return Boolean(table.item && canBulkAppendKind(table.item.kind));
1536
+ }
1537
+ if (table.kind !== 'feature') {
1538
+ return false;
1539
+ }
1540
+ const schema = getClassSchema(requireFeature(table));
1541
+ return schema.fieldList.every((field) => canBulkAppendKind(field.entry.kind));
1542
+ }
1543
+ function columnarFastPathPlan(table, values) {
1544
+ if (table.kind === 'scalars') {
1545
+ return scalarFastPathPlan(table, values);
1546
+ }
1547
+ if (table.kind === 'array') {
1548
+ return arrayFastPathPlan(table, values);
1549
+ }
1550
+ if (table.kind === 'feature') {
1551
+ return featureFastPathPlan(table, values);
1552
+ }
1553
+ return null;
1554
+ }
1555
+ function scalarFastPathPlan(table, values) {
1556
+ for (const field of table.fields ?? []) {
1557
+ if (!canBulkAppendKind(field.kind)) {
1558
+ return null;
1559
+ }
1560
+ }
1561
+ const fields = (table.fields ?? []).map((field, index) => ({
1562
+ index,
1563
+ kind: field.kind,
1564
+ value: () => valueAt(values, field.valuePosition, table.name),
1565
+ }));
1566
+ return {
1567
+ fields,
1568
+ featureType: dynamicFeatureForTable(table),
1569
+ rows: [null],
1570
+ tableName: table.name,
1571
+ };
1572
+ }
1573
+ function arrayFastPathPlan(table, values) {
1574
+ if (!table.item || !canBulkAppendKind(table.item.kind)) {
1575
+ return null;
1576
+ }
1577
+ const items = asArray(valueAt(values, requiredPosition(table), table.name), table.name);
1578
+ return {
1579
+ fields: [{
1580
+ index: 0,
1581
+ kind: table.item.kind,
1582
+ value: (row) => row,
1583
+ }],
1584
+ featureType: dynamicFeatureForTable(table),
1585
+ rows: items,
1586
+ tableName: table.name,
1587
+ };
1588
+ }
1589
+ function featureFastPathPlan(table, values) {
1590
+ const featureType = requireFeature(table);
1591
+ const rows = table.cardinality === 'many'
1592
+ ? asArray(valueAt(values, requiredPosition(table), table.name), table.name)
1593
+ : [valueAt(values, requiredPosition(table), table.name)];
1594
+ if (rows.length === 0) {
1595
+ return {
1596
+ fields: [],
1597
+ featureType,
1598
+ rows,
1599
+ tableName: table.name,
1600
+ };
1601
+ }
1602
+ for (const row of rows) {
1603
+ if (!(row instanceof Feature)) {
1604
+ const expected = table.cardinality === 'many' ? 'Feature rows' : 'a Feature value';
1605
+ throw new FastdbUsageError(`fastdb call-db table "${table.name}" expects ${expected}.`);
1606
+ }
1607
+ if (!(row instanceof featureType)) {
1608
+ return null;
1609
+ }
1610
+ }
1611
+ const schema = getClassSchema(featureType);
1612
+ for (const field of schema.fieldList) {
1613
+ if (!canBulkAppendKind(field.entry.kind)) {
1614
+ return null;
1615
+ }
1616
+ }
1617
+ return {
1618
+ fields: schema.fieldList.map((field) => ({
1619
+ index: field.index,
1620
+ kind: field.entry.kind,
1621
+ value: (row) => row[field.name],
1622
+ })),
1623
+ featureType,
1624
+ rows,
1625
+ tableName: table.name,
1626
+ };
1627
+ }
1628
+ function canBulkAppendKind(kind) {
1629
+ return BULK_APPEND_KINDS.has(kind);
1630
+ }
1631
+ function appendColumnarFastPathPlan(orm, plan) {
1632
+ const table = orm.ensureTable(plan.featureType, plan.tableName);
1633
+ const origin = table.origin;
1634
+ for (const row of plan.rows) {
1635
+ origin.addFeatureBegin();
1636
+ try {
1637
+ for (const field of plan.fields) {
1638
+ writeColumnarFastPathField(origin, field.index, field.kind, field.value(row));
1639
+ }
1640
+ }
1641
+ finally {
1642
+ origin.addFeatureEnd();
1643
+ }
1644
+ }
1645
+ }
1646
+ function writeColumnarFastPathField(origin, index, kind, value) {
1647
+ if (kind === 'bool') {
1648
+ origin.setFieldInt(index, coerceBoolScalar(value) ? 1 : 0);
1649
+ return;
1650
+ }
1651
+ if (kind === 'u8' || kind === 'u16' || kind === 'u32' || kind === 'i32') {
1652
+ origin.setFieldInt(index, Math.trunc(Number(value)));
1653
+ return;
1654
+ }
1655
+ origin.setFieldDouble(index, Number(value));
1656
+ }
1657
+ function decodeCallTable(orm, table, values) {
1658
+ if (table.kind === 'scalars') {
1659
+ const featureType = dynamicFeatureForTable(table);
1660
+ const rows = orm.table(featureType, table.name);
1661
+ if (rows.length < 1) {
1662
+ throw new FastdbUsageError(`fastdb call-db scalar table "${table.name}" is empty.`);
1663
+ }
1664
+ const row = rows.get(0);
1665
+ for (const field of table.fields ?? []) {
1666
+ values[field.valuePosition] = materializeScalarValue(field.kind, row[field.name]);
1667
+ }
1668
+ return;
1669
+ }
1670
+ if (table.kind === 'array') {
1671
+ const featureType = dynamicFeatureForTable(table);
1672
+ const rows = orm.table(featureType, table.name);
1673
+ values[requiredPosition(table)] = Array.from(rows, (row) => row.value);
1674
+ return;
1675
+ }
1676
+ if (table.kind === 'feature') {
1677
+ const featureType = requireFeature(table);
1678
+ const rows = orm.table(featureType, table.name);
1679
+ if (table.cardinality === 'many') {
1680
+ values[requiredPosition(table)] = Array.from(rows, (row) => copyFeature(featureType, row));
1681
+ return;
1682
+ }
1683
+ if (rows.length < 1) {
1684
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" is empty.`);
1685
+ }
1686
+ values[requiredPosition(table)] = copyFeature(featureType, rows.get(0));
1687
+ return;
1688
+ }
1689
+ throw new FastdbUsageError(`Unsupported fastdb call-db table kind "${table.kind}".`);
1690
+ }
1691
+ function normalizeCallValues(binding, value) {
1692
+ const expected = callValueCount(binding);
1693
+ if (binding.direction === 'input') {
1694
+ if (!Array.isArray(value)) {
1695
+ throw new FastdbUsageError('fastdb call-db input call-db encode expects an array of method arguments.');
1696
+ }
1697
+ if (value.length !== expected) {
1698
+ throw new FastdbUsageError(`fastdb call-db input call-db expected ${expected} values, got ${value.length}.`);
1699
+ }
1700
+ return value;
1701
+ }
1702
+ if (expected <= 1) {
1703
+ return [value];
1704
+ }
1705
+ if (!Array.isArray(value)) {
1706
+ throw new FastdbUsageError(`fastdb call-db output call-db expected ${expected} tuple values.`);
1707
+ }
1708
+ if (value.length !== expected) {
1709
+ throw new FastdbUsageError(`fastdb call-db output call-db expected ${expected} values, got ${value.length}.`);
1710
+ }
1711
+ return value;
1712
+ }
1713
+ function callValueCount(binding) {
1714
+ ensureCallDbTableShape(binding);
1715
+ let count = 0;
1716
+ for (const table of binding.tables) {
1717
+ if (table.kind === 'scalars') {
1718
+ count += table.fields?.length ?? 0;
1719
+ continue;
1720
+ }
1721
+ count += 1;
1722
+ }
1723
+ return count;
1724
+ }
1725
+ function columnFieldForTable(table, fieldName) {
1726
+ if (table.kind === 'scalars') {
1727
+ const field = (table.fields ?? []).find((item) => item.name === fieldName);
1728
+ return field ? { name: field.name, kind: field.kind } : undefined;
1729
+ }
1730
+ if (table.kind === 'array') {
1731
+ if (fieldName !== CALL_DB_ARRAY_VALUE_FIELD || !table.item) {
1732
+ return undefined;
1733
+ }
1734
+ return { name: CALL_DB_ARRAY_VALUE_FIELD, kind: table.item.kind };
1735
+ }
1736
+ if (table.kind === 'feature') {
1737
+ const schema = getClassSchema(requireFeature(table));
1738
+ const field = schema.fieldList.find((item) => item.name === fieldName);
1739
+ return field ? { name: field.name, kind: field.entry.kind } : undefined;
1740
+ }
1741
+ return undefined;
1742
+ }
1743
+ function dynamicFeatureForTable(table) {
1744
+ const cached = DYNAMIC_FEATURE_CACHE.get(table);
1745
+ if (cached) {
1746
+ return cached;
1747
+ }
1748
+ const schema = {};
1749
+ if (table.kind === 'scalars') {
1750
+ for (const field of table.fields ?? []) {
1751
+ schema[field.name] = fieldTypeForKind(field.kind);
1752
+ }
1753
+ }
1754
+ else if (table.kind === 'array') {
1755
+ if (!table.item) {
1756
+ throw new FastdbUsageError(`fastdb call-db array table "${table.name}" is missing item metadata.`);
1757
+ }
1758
+ schema.value = fieldTypeForKind(table.item.kind);
1759
+ }
1760
+ else {
1761
+ throw new FastdbUsageError(`fastdb call-db table "${table.name}" does not use a dynamic feature.`);
1762
+ }
1763
+ class FastdbDynamicCallDbFeature extends Feature {
1764
+ static schema = defineSchema(schema);
1765
+ }
1766
+ DYNAMIC_FEATURE_CACHE.set(table, FastdbDynamicCallDbFeature);
1767
+ return FastdbDynamicCallDbFeature;
1768
+ }
1769
+ function createDynamicFeature(featureType, values) {
1770
+ return createFeature(featureType, values);
1771
+ }
1772
+ function copyFeature(featureType, source) {
1773
+ const values = {};
1774
+ for (const field of getClassSchema(featureType).fieldList) {
1775
+ values[field.name] = source[field.name];
1776
+ }
1777
+ return createFeature(featureType, values);
1778
+ }
1779
+ function materializeScalarValue(kind, value) {
1780
+ if (kind === 'bool') {
1781
+ return coerceBoolScalar(value);
1782
+ }
1783
+ return value;
1784
+ }
1785
+ function fieldTypeForKind(kind) {
1786
+ const fieldType = FIELD_TYPES[kind];
1787
+ if (!fieldType) {
1788
+ throw new FastdbUsageError(`Unsupported fastdb call-db scalar kind "${kind}".`);
1789
+ }
1790
+ return fieldType;
1791
+ }
1792
+ function requireFeature(table) {
1793
+ if (!table.feature) {
1794
+ throw new FastdbUsageError(`fastdb call-db feature table "${table.name}" is missing a feature class.`);
1795
+ }
1796
+ return table.feature;
1797
+ }
1798
+ function requiredPosition(table) {
1799
+ if (table.valuePosition === undefined) {
1800
+ throw new FastdbUsageError(`fastdb call-db table "${table.name}" is missing valuePosition metadata.`);
1801
+ }
1802
+ return table.valuePosition;
1803
+ }
1804
+ function valueAt(values, position, tableName) {
1805
+ if (position < 0 || position >= values.length) {
1806
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" references value position ${position}, but only ${values.length} values were provided.`);
1807
+ }
1808
+ return values[position];
1809
+ }
1810
+ function asArray(value, tableName) {
1811
+ if (Array.isArray(value)) {
1812
+ return value;
1813
+ }
1814
+ if (typeof value === 'string' || value instanceof String) {
1815
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" expects an array or sequence value, not a string.`);
1816
+ }
1817
+ if (typeof value === 'function') {
1818
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" expects an array or sequence value.`);
1819
+ }
1820
+ if (value instanceof ArrayBuffer || value instanceof DataView || value instanceof Map) {
1821
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" expects an array or sequence value.`);
1822
+ }
1823
+ if (ArrayBuffer.isView(value)) {
1824
+ return Array.from(value);
1825
+ }
1826
+ if (hasArrayLikeLength(value)) {
1827
+ if (!hasIndexedArrayLikeEntries(value)) {
1828
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" expects an indexed array-like sequence value.`);
1829
+ }
1830
+ return Array.from(value);
1831
+ }
1832
+ if (isIterableObject(value)) {
1833
+ return Array.from(value);
1834
+ }
1835
+ throw new FastdbUsageError(`fastdb call-db table "${tableName}" expects an array or sequence value.`);
1836
+ }
1837
+ function hasArrayLikeLength(value) {
1838
+ if (value === null || typeof value !== 'object') {
1839
+ return false;
1840
+ }
1841
+ const length = value.length;
1842
+ return typeof length === 'number' && Number.isSafeInteger(length) && length >= 0;
1843
+ }
1844
+ function hasIndexedArrayLikeEntries(value) {
1845
+ for (let index = 0; index < value.length; index += 1) {
1846
+ if (!(index in Object(value))) {
1847
+ return false;
1848
+ }
1849
+ }
1850
+ return true;
1851
+ }
1852
+ function isIterableObject(value) {
1853
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
1854
+ return false;
1855
+ }
1856
+ return typeof value[Symbol.iterator] === 'function';
1857
+ }