fastdb4ts 0.0.1 → 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.
@@ -1,9 +1,12 @@
1
1
  import { createFeature, Feature } from './feature.js';
2
2
  import { getClassSchema, resolveListItem, } from './schema.js';
3
3
  import { FastdbRuntimeError, FastdbUsageError } from './errors.js';
4
+ import { loadDatabaseFromBytes } from './database-buffer.js';
4
5
  import { getInitializedFastdbModule } from './wasm-loader.js';
5
- import { isListField, isRefField } from './types.js';
6
+ import { coerceBoolScalar, isListField, isRefField } from './types.js';
6
7
  const NUMERIC_LIST_LAYER_PREFIX = '__fastser_list__|';
8
+ const TEXT_ENCODER = new TextEncoder();
9
+ const TEXT_DECODER = new TextDecoder();
7
10
  const SERIALIZER_SCHEMA_CACHE = new WeakMap();
8
11
  export class FastSerializer {
9
12
  static dumps(obj) {
@@ -43,8 +46,7 @@ export class FastSerializer {
43
46
  numericListLayers.set(`${ctor.name}:${field.name}`, { kind, layer: aux });
44
47
  }
45
48
  }
46
- const orderedObjects = [...ctx.objects].sort((left, right) => left.layerIdx - right.layerIdx || left.featureIdx - right.featureIdx);
47
- for (const wrapper of orderedObjects) {
49
+ for (const wrapper of ctx.objects) {
48
50
  const ctor = wrapper.obj.constructor;
49
51
  const schema = getSerializerSchema(ctor);
50
52
  const layer = layerBuilders.get(wrapper.layerIdx);
@@ -84,7 +86,7 @@ export class FastSerializer {
84
86
  }
85
87
  switch (field.entry.kind) {
86
88
  case 'bool':
87
- layer.setFieldInt(dbFieldIndex, value ? 1 : 0);
89
+ layer.setFieldInt(dbFieldIndex, coerceBoolScalar(value) ? 1 : 0);
88
90
  break;
89
91
  case 'u8':
90
92
  case 'u16':
@@ -123,8 +125,7 @@ export class FastSerializer {
123
125
  }
124
126
  static loads(data, rootType) {
125
127
  const module = getInitializedFastdbModule();
126
- const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
127
- const db = withHeapBytes(module, bytes, (ptr, size) => module.WxDatabase.loadFromHeap(ptr, size));
128
+ const db = loadDatabaseFromBytes(module, data);
128
129
  if (db.getLayerCount() === 0) {
129
130
  return null;
130
131
  }
@@ -158,7 +159,7 @@ class DumpContext {
158
159
  this.objToRef.set(obj, { layerIdx, featureIdx });
159
160
  this.objects.push({ obj, layerIdx, featureIdx });
160
161
  const schema = getSerializerSchema(ctor);
161
- for (const field of schema.fieldList) {
162
+ for (const field of schema.refTraversalFields) {
162
163
  const value = getFeatureFieldValue(obj, field.name);
163
164
  if (value === null || value === undefined) {
164
165
  continue;
@@ -169,16 +170,12 @@ class DumpContext {
169
170
  }
170
171
  continue;
171
172
  }
172
- if (!isListField(field.entry) || !Array.isArray(value) || value.length === 0) {
173
- continue;
174
- }
175
- const item = resolveListItem(field.entry);
176
- if (isFieldType(item)) {
177
- continue;
178
- }
179
- for (const nested of value) {
180
- if (nested instanceof Feature) {
181
- this.register(nested);
173
+ // Must be list-of-Feature
174
+ if (Array.isArray(value)) {
175
+ for (const nested of value) {
176
+ if (nested instanceof Feature) {
177
+ this.register(nested);
178
+ }
182
179
  }
183
180
  }
184
181
  }
@@ -196,19 +193,26 @@ class LoadContext {
196
193
  objectCache = new Map();
197
194
  typeMap = new Map();
198
195
  numericListValues;
196
+ layerNameCache = new Map();
199
197
  constructor(db, module) {
200
198
  this.db = db;
201
199
  this.module = module;
202
200
  this.numericListValues = loadNumericListValues(db, module);
203
201
  }
204
202
  getObject(layerIdx, featureIdx, expectedType) {
205
- const key = `${layerIdx}:${featureIdx}`;
203
+ // Numeric key avoids string allocation: layerIdx is always < 65536
204
+ const key = (layerIdx << 20) | featureIdx;
206
205
  const cached = this.objectCache.get(key);
207
206
  if (cached) {
208
207
  return cached;
209
208
  }
210
209
  const layer = this.db.getLayer(layerIdx);
211
- const ctor = this.typeMap.get(layer.name()) ?? expectedType;
210
+ let layerName = this.layerNameCache.get(layerIdx);
211
+ if (layerName === undefined) {
212
+ layerName = layer.name();
213
+ this.layerNameCache.set(layerIdx, layerName);
214
+ }
215
+ const ctor = this.typeMap.get(layerName) ?? expectedType;
212
216
  const row = layer.tryGetFeatureAt(featureIdx);
213
217
  const obj = createFeature(ctor);
214
218
  this.objectCache.set(key, obj);
@@ -293,6 +297,9 @@ function getSerializerSchema(ctor) {
293
297
  else if (isFieldType(item) && item.kind === 'f64') {
294
298
  numericFieldKinds.set(field.name, 'f64');
295
299
  }
300
+ else if (isFieldType(item) && item.kind === 'i32') {
301
+ numericFieldKinds.set(field.name, 'i32');
302
+ }
296
303
  dbFieldIndexBySchema.set(field.index, -1);
297
304
  continue;
298
305
  }
@@ -303,10 +310,24 @@ function getSerializerSchema(ctor) {
303
310
  dbFieldIndexBySchema.set(field.index, dbFieldIndex);
304
311
  dbFieldIndex += 1;
305
312
  }
313
+ // Pre-compute fields that need traversal during register() — only ref fields and list-of-Feature fields
314
+ const refTraversalFields = [];
315
+ for (const field of classSchema.fieldList) {
316
+ if (isRefField(field.entry)) {
317
+ refTraversalFields.push(field);
318
+ }
319
+ else if (isListField(field.entry)) {
320
+ const item = resolveListItem(field.entry);
321
+ if (!isFieldType(item)) {
322
+ refTraversalFields.push(field);
323
+ }
324
+ }
325
+ }
306
326
  const schema = {
307
327
  fieldList: classSchema.fieldList,
308
328
  numericFieldKinds,
309
329
  dbFieldIndexBySchema,
330
+ refTraversalFields,
310
331
  };
311
332
  SERIALIZER_SCHEMA_CACHE.set(ctor, schema);
312
333
  return schema;
@@ -370,7 +391,7 @@ function packList(writer, field, value, ctx) {
370
391
  case 'str':
371
392
  case 'wstr':
372
393
  for (const entry of list) {
373
- const bytes = new TextEncoder().encode(String(entry));
394
+ const bytes = TEXT_ENCODER.encode(String(entry));
374
395
  writer.writeU32(bytes.length);
375
396
  writer.writeBytes(bytes);
376
397
  }
@@ -412,7 +433,7 @@ function unpackList(reader, field, ctx) {
412
433
  case 'str':
413
434
  case 'wstr':
414
435
  for (let i = 0; i < count; i += 1) {
415
- out.push(new TextDecoder().decode(reader.readBytes(reader.readU32())));
436
+ out.push(TEXT_DECODER.decode(reader.readBytes(reader.readU32())));
416
437
  }
417
438
  return out;
418
439
  default:
@@ -430,26 +451,38 @@ function writeNumericListChunk(module, layer, ownerFeatureId, value, kind) {
430
451
  const list = Array.isArray(value) ? value : [];
431
452
  layer.addFeatureBegin();
432
453
  layer.setFieldInt(0, ownerFeatureId);
433
- let payload = new Uint8Array(0);
434
- if (list.length > 0) {
435
- if (kind === 'u32') {
436
- const view = new DataView(new ArrayBuffer(list.length * 4));
437
- list.forEach((entry, index) => {
438
- const iv = Number(entry);
439
- if (!Number.isInteger(iv) || iv < 0 || iv > 0xffffffff) {
440
- throw new FastdbUsageError(`List[U32] item out of range: ${entry}`);
441
- }
442
- view.setUint32(index * 4, iv, true);
443
- });
444
- payload = new Uint8Array(view.buffer);
454
+ let payload;
455
+ if (list.length === 0) {
456
+ payload = new Uint8Array(0);
457
+ }
458
+ else if (kind === 'u32') {
459
+ const typed = new Uint32Array(list.length);
460
+ for (let i = 0; i < list.length; i++) {
461
+ const iv = Number(list[i]);
462
+ if (!Number.isInteger(iv) || iv < 0 || iv > 0xffffffff) {
463
+ throw new FastdbUsageError(`List[U32] item out of range: ${list[i]}`);
464
+ }
465
+ typed[i] = iv;
445
466
  }
446
- else {
447
- const view = new DataView(new ArrayBuffer(list.length * 8));
448
- list.forEach((entry, index) => {
449
- view.setFloat64(index * 8, Number(entry), true);
450
- });
451
- payload = new Uint8Array(view.buffer);
467
+ payload = new Uint8Array(typed.buffer);
468
+ }
469
+ else if (kind === 'i32') {
470
+ const typed = new Int32Array(list.length);
471
+ for (let i = 0; i < list.length; i++) {
472
+ const iv = Math.trunc(Number(list[i]));
473
+ if (iv < -0x80000000 || iv > 0x7fffffff) {
474
+ throw new FastdbUsageError(`list[int] item ${list[i]} out of i32 range [-2147483648, 2147483647].`);
475
+ }
476
+ typed[i] = iv;
452
477
  }
478
+ payload = new Uint8Array(typed.buffer);
479
+ }
480
+ else {
481
+ const typed = new Float64Array(list.length);
482
+ for (let i = 0; i < list.length; i++) {
483
+ typed[i] = Number(list[i]);
484
+ }
485
+ payload = new Uint8Array(typed.buffer);
453
486
  }
454
487
  if (payload.length > 0) {
455
488
  withHeapBytes(module, payload, (ptr, size) => {
@@ -481,9 +514,20 @@ function decodeNumericListChunk(chunk, kind) {
481
514
  }
482
515
  const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
483
516
  const out = [];
484
- const step = kind === 'u32' ? 4 : 8;
485
- for (let offset = 0; offset < chunk.length; offset += step) {
486
- out.push(kind === 'u32' ? view.getUint32(offset, true) : view.getFloat64(offset, true));
517
+ if (kind === 'u32') {
518
+ for (let offset = 0; offset < chunk.length; offset += 4) {
519
+ out.push(view.getUint32(offset, true));
520
+ }
521
+ }
522
+ else if (kind === 'i32') {
523
+ for (let offset = 0; offset < chunk.length; offset += 4) {
524
+ out.push(view.getInt32(offset, true));
525
+ }
526
+ }
527
+ else {
528
+ for (let offset = 0; offset < chunk.length; offset += 8) {
529
+ out.push(view.getFloat64(offset, true));
530
+ }
487
531
  }
488
532
  return out;
489
533
  }
@@ -499,7 +543,7 @@ function parseNumericListLayerName(layerName) {
499
543
  return null;
500
544
  }
501
545
  const [className, fieldName, kind] = parts;
502
- if (kind !== 'u32' && kind !== 'f64') {
546
+ if (kind !== 'u32' && kind !== 'f64' && kind !== 'i32') {
503
547
  return null;
504
548
  }
505
549
  return { className, fieldName, kind };
@@ -540,77 +584,103 @@ function getFeatureFieldValue(feature, fieldName) {
540
584
  return feature[fieldName];
541
585
  }
542
586
  class ByteWriter {
543
- chunks = [];
544
- totalSize = 0;
587
+ buf;
588
+ view;
589
+ offset = 0;
590
+ constructor(initialCapacity = 256) {
591
+ this.buf = new ArrayBuffer(initialCapacity);
592
+ this.view = new DataView(this.buf);
593
+ }
545
594
  writeU16(value) {
546
- const bytes = new Uint8Array(2);
547
- new DataView(bytes.buffer).setUint16(0, value, true);
548
- this.push(bytes);
595
+ this.ensureCapacity(2);
596
+ this.view.setUint16(this.offset, value, true);
597
+ this.offset += 2;
549
598
  }
550
599
  writeU32(value) {
551
- const bytes = new Uint8Array(4);
552
- new DataView(bytes.buffer).setUint32(0, value, true);
553
- this.push(bytes);
600
+ this.ensureCapacity(4);
601
+ this.view.setUint32(this.offset, value, true);
602
+ this.offset += 4;
554
603
  }
555
604
  writeI32(value) {
556
- const bytes = new Uint8Array(4);
557
- new DataView(bytes.buffer).setInt32(0, value, true);
558
- this.push(bytes);
605
+ this.ensureCapacity(4);
606
+ this.view.setInt32(this.offset, value, true);
607
+ this.offset += 4;
559
608
  }
560
609
  writeF64(value) {
561
- const bytes = new Uint8Array(8);
562
- new DataView(bytes.buffer).setFloat64(0, value, true);
563
- this.push(bytes);
610
+ this.ensureCapacity(8);
611
+ this.view.setFloat64(this.offset, value, true);
612
+ this.offset += 8;
564
613
  }
565
614
  writeBytes(bytes) {
566
615
  if (bytes.length === 0) {
567
616
  return;
568
617
  }
569
- this.push(bytes);
618
+ this.ensureCapacity(bytes.length);
619
+ new Uint8Array(this.buf).set(bytes, this.offset);
620
+ this.offset += bytes.length;
570
621
  }
571
622
  finish() {
572
- const out = new Uint8Array(this.totalSize);
573
- let offset = 0;
574
- for (const chunk of this.chunks) {
575
- out.set(chunk, offset);
576
- offset += chunk.length;
577
- }
578
- return out;
623
+ return new Uint8Array(this.buf, 0, this.offset);
579
624
  }
580
- push(bytes) {
581
- this.chunks.push(bytes);
582
- this.totalSize += bytes.length;
625
+ ensureCapacity(needed) {
626
+ const required = this.offset + needed;
627
+ if (required <= this.buf.byteLength) {
628
+ return;
629
+ }
630
+ let newSize = this.buf.byteLength * 2;
631
+ while (newSize < required) {
632
+ newSize *= 2;
633
+ }
634
+ const newBuf = new ArrayBuffer(newSize);
635
+ new Uint8Array(newBuf).set(new Uint8Array(this.buf, 0, this.offset));
636
+ this.buf = newBuf;
637
+ this.view = new DataView(this.buf);
583
638
  }
584
639
  }
585
640
  class ByteReader {
586
641
  bytes;
587
642
  offset = 0;
643
+ view;
588
644
  constructor(bytes) {
589
645
  this.bytes = bytes;
646
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
647
+ }
648
+ checkRead(size) {
649
+ if (this.offset + size > this.bytes.byteLength) {
650
+ throw new FastdbRuntimeError(`ByteReader: attempted to read ${size} byte(s) at offset ${this.offset}, ` +
651
+ `but buffer length is ${this.bytes.byteLength}. The buffer may be truncated or corrupted.`);
652
+ }
590
653
  }
591
654
  readU16() {
592
- const value = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength).getUint16(this.offset, true);
655
+ this.checkRead(2);
656
+ const value = this.view.getUint16(this.offset, true);
593
657
  this.offset += 2;
594
658
  return value;
595
659
  }
596
660
  readU32() {
597
- const value = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength).getUint32(this.offset, true);
661
+ this.checkRead(4);
662
+ const value = this.view.getUint32(this.offset, true);
598
663
  this.offset += 4;
599
664
  return value;
600
665
  }
601
666
  readI32() {
602
- const value = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength).getInt32(this.offset, true);
667
+ this.checkRead(4);
668
+ const value = this.view.getInt32(this.offset, true);
603
669
  this.offset += 4;
604
670
  return value;
605
671
  }
606
672
  readF64() {
607
- const value = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength).getFloat64(this.offset, true);
673
+ this.checkRead(8);
674
+ const value = this.view.getFloat64(this.offset, true);
608
675
  this.offset += 8;
609
676
  return value;
610
677
  }
611
678
  readBytes(size) {
679
+ this.checkRead(size);
612
680
  const out = this.bytes.slice(this.offset, this.offset + size);
613
681
  this.offset += size;
614
682
  return out;
615
683
  }
616
684
  }
685
+ // Exported for unit testing only — not part of the public API.
686
+ export { ByteReader, ByteWriter };
package/dist/table.js CHANGED
@@ -49,6 +49,9 @@ export class Table {
49
49
  if (!def) {
50
50
  return undefined;
51
51
  }
52
+ if (def.entry.kind === 'list') {
53
+ throw new FastdbRuntimeError(`Column accessor "${prop}" is a list field; read it from table rows instead of as a strided column.`);
54
+ }
52
55
  return new StridedColumn(table.module, layer, def.index, def.entry.originType);
53
56
  },
54
57
  });
package/dist/types.d.ts CHANGED
@@ -23,6 +23,7 @@ export type ListItemDef = FieldTypeDef<ScalarFieldKind> | FeatureClassLike | (()
23
23
  export interface ListFieldDef extends FieldTypeDef<'list'> {
24
24
  item: ListItemDef;
25
25
  }
26
+ export declare function coerceBoolScalar(value: unknown): boolean;
26
27
  export declare const BOOL: FieldTypeDef<"bool">;
27
28
  export declare const U8: FieldTypeDef<"u8">;
28
29
  export declare const U16: FieldTypeDef<"u16">;
package/dist/types.js CHANGED
@@ -1,3 +1,34 @@
1
+ import { FastdbUsageError } from './errors.js';
2
+ const TRUE_BOOL_STRINGS = new Set(['1', 'true', 't', 'yes', 'y', 'on']);
3
+ const FALSE_BOOL_STRINGS = new Set(['0', 'false', 'f', 'no', 'n', 'off']);
4
+ export function coerceBoolScalar(value) {
5
+ if (typeof value === 'boolean') {
6
+ return value;
7
+ }
8
+ if (typeof value === 'string') {
9
+ const normalized = value.trim().toLowerCase();
10
+ if (TRUE_BOOL_STRINGS.has(normalized)) {
11
+ return true;
12
+ }
13
+ if (FALSE_BOOL_STRINGS.has(normalized)) {
14
+ return false;
15
+ }
16
+ throw new FastdbUsageError(`cannot coerce ${JSON.stringify(value)} to fastdb bool scalar; expected bool, 0/1, or true/false string.`);
17
+ }
18
+ if (typeof value === 'number') {
19
+ if (value === 0 || value === 1) {
20
+ return value === 1;
21
+ }
22
+ throw new FastdbUsageError(`cannot coerce ${String(value)} to fastdb bool scalar; expected bool, 0/1, or true/false string.`);
23
+ }
24
+ if (typeof value === 'bigint') {
25
+ if (value === 0n || value === 1n) {
26
+ return value === 1n;
27
+ }
28
+ throw new FastdbUsageError(`cannot coerce ${String(value)} to fastdb bool scalar; expected bool, 0/1, or true/false string.`);
29
+ }
30
+ throw new FastdbUsageError(`cannot coerce ${String(value)} to fastdb bool scalar; expected bool, 0/1, or true/false string.`);
31
+ }
1
32
  function makeFieldType(kind, originType, options) {
2
33
  return Object.freeze({
3
34
  kind,