@the-w1zard/singularity 1.0.13 → 1.0.15

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.
Files changed (70) hide show
  1. package/README.html +450 -0
  2. package/README.md +135 -3
  3. package/dist/bus_db_rpc/RULE_OF_2_same_node.d.ts +139 -0
  4. package/dist/bus_db_rpc/RULE_OF_2_same_node.d.ts.map +1 -0
  5. package/dist/bus_db_rpc/RULE_OF_2_same_node.js +502 -0
  6. package/dist/class.d.ts +161 -0
  7. package/dist/class.d.ts.map +1 -0
  8. package/dist/class.js +804 -0
  9. package/dist/comps/DISRUPTOR_CRYPTO.d.ts +47 -0
  10. package/dist/comps/DISRUPTOR_CRYPTO.d.ts.map +1 -0
  11. package/dist/comps/RULE_OF_2_same_app.d.ts +175 -0
  12. package/dist/comps/RULE_OF_2_same_app.d.ts.map +1 -0
  13. package/dist/comps/RULE_OF_2_same_app.js +482 -0
  14. package/dist/comps/binary.d.ts +71 -0
  15. package/dist/comps/binary.d.ts.map +1 -0
  16. package/dist/comps/byte_id.d.ts +12 -0
  17. package/dist/comps/byte_id.d.ts.map +1 -0
  18. package/dist/comps/cell-worker.d.ts +9 -0
  19. package/dist/comps/cell-worker.d.ts.map +1 -0
  20. package/dist/comps/cell.d.ts +349 -0
  21. package/dist/comps/cell.d.ts.map +1 -0
  22. package/dist/comps/create_live_self.d.ts +22 -0
  23. package/dist/comps/create_live_self.d.ts.map +1 -0
  24. package/dist/comps/queue.d.ts +103 -0
  25. package/dist/comps/queue.d.ts.map +1 -0
  26. package/dist/comps/serializer.d.ts +30 -0
  27. package/dist/comps/serializer.d.ts.map +1 -0
  28. package/dist/comps/serializer.js +131 -0
  29. package/dist/comps/vm-types.d.ts +20 -0
  30. package/dist/comps/vm-types.d.ts.map +1 -0
  31. package/dist/db/binary.d.ts +76 -0
  32. package/dist/db/binary.d.ts.map +1 -0
  33. package/dist/db/binary.js +441 -0
  34. package/dist/db/client.d.ts +28 -0
  35. package/dist/db/client.d.ts.map +1 -0
  36. package/dist/db/client.js +82 -0
  37. package/dist/db/db.d.ts +141 -0
  38. package/dist/db/db.d.ts.map +1 -0
  39. package/dist/db/db.js +898 -0
  40. package/dist/db/op.d.ts +13 -0
  41. package/dist/db/op.d.ts.map +1 -0
  42. package/dist/db/op.js +11 -0
  43. package/dist/db/storage-worker.d.ts +2 -0
  44. package/dist/db/storage-worker.d.ts.map +1 -0
  45. package/dist/db/storage-worker.js +152 -0
  46. package/dist/db/types.d.ts +134 -0
  47. package/dist/db/types.d.ts.map +1 -0
  48. package/dist/db/types.js +14 -0
  49. package/dist/db/wal.d.ts +30 -0
  50. package/dist/db/wal.d.ts.map +1 -0
  51. package/dist/db/wal.js +217 -0
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/signals.js +10740 -5498
  55. package/dist/slab.d.ts +95 -0
  56. package/dist/slab.d.ts.map +1 -0
  57. package/dist/slab.js +575 -0
  58. package/dist/slab.types.d.ts +5 -0
  59. package/dist/slab.types.d.ts.map +1 -0
  60. package/dist/slab.types.js +1 -0
  61. package/dist/test.d.ts +152 -0
  62. package/dist/test.d.ts.map +1 -0
  63. package/dist/test.js +1183 -0
  64. package/dist/testt.d.ts +61 -0
  65. package/dist/testt.d.ts.map +1 -0
  66. package/dist/testt.js +143 -0
  67. package/dist/y.d.ts +152 -0
  68. package/dist/y.d.ts.map +1 -0
  69. package/dist/y.js +36 -65
  70. package/package.json +20 -19
@@ -0,0 +1,131 @@
1
+ export const HEADER_SIZE_BYTES = 64; // Int32 Array Indices (4 bytes per element)
2
+ export const HEADER_IDX_WRITE_HEAD = 0; // Byte offset 0
3
+ export const HEADER_IDX_READ_HEAD = 1; // Byte offset 4
4
+ export const HEADER_IDX_MUTEX = 2; // Byte offset 8
5
+ export const HEADER_IDX_CAPACITY = 3; // Byte offset 12
6
+ export const MUTEX_UNLOCKED = 0; // Mutex States
7
+ export const MUTEX_LOCKED = 1;
8
+ export const SENTINEL_WRAP_MARKER = 0xFFFFFFFF; // 0xFFFFFFFF (Uint32 max) written to length prefix slot when p wraps to offset 0
9
+ export function createSharedDepotBuffer(capacityBytes) {
10
+ // Enforce 64-byte alignment on capacity
11
+ const alignedCapacity = Math.ceil(capacityBytes / 64) * 64;
12
+ const totalSizeBytes = HEADER_SIZE_BYTES + alignedCapacity;
13
+ const sab = new SharedArrayBuffer(totalSizeBytes);
14
+ const headerView = new Int32Array(sab, 0, 4);
15
+ // Initialize Header State
16
+ Atomics.store(headerView, HEADER_IDX_WRITE_HEAD, 0);
17
+ Atomics.store(headerView, HEADER_IDX_READ_HEAD, 0);
18
+ Atomics.store(headerView, HEADER_IDX_MUTEX, MUTEX_UNLOCKED);
19
+ Atomics.store(headerView, HEADER_IDX_CAPACITY, alignedCapacity);
20
+ return sab;
21
+ }
22
+ export function mapDepotBuffer(sab) {
23
+ // Map control slots (first 16 bytes containing 4 x Int32 values)
24
+ const headerInt32 = new Int32Array(sab, 0, 4);
25
+ // Read capacity directly from header slot
26
+ const capacity = Atomics.load(headerInt32, HEADER_IDX_CAPACITY);
27
+ // Map p slice strictly starting at byte 64
28
+ const payloadUint8 = new Uint8Array(sab, HEADER_SIZE_BYTES, capacity);
29
+ return {
30
+ headerInt32,
31
+ payloadUint8,
32
+ capacity
33
+ };
34
+ }
35
+ export function validateHeader(sab) {
36
+ if (sab.byteLength < HEADER_SIZE_BYTES)
37
+ return false;
38
+ const headerInt32 = new Int32Array(sab, 0, 4);
39
+ const capacity = Atomics.load(headerInt32, HEADER_IDX_CAPACITY);
40
+ // Buffer length must equal 64 bytes header + registered capacity
41
+ return sab.byteLength === HEADER_SIZE_BYTES + capacity;
42
+ }
43
+ export function calculateFrameFootprint(payloadSizeBytes) {
44
+ const rawEnvelopeBytes = 4 + payloadSizeBytes;
45
+ return Math.ceil(rawEnvelopeBytes / 4) * 4;
46
+ }
47
+ const FLYWEIGHT_FRAME = {
48
+ topicId: 0,
49
+ topicName: undefined,
50
+ p: new Uint8Array(0)
51
+ };
52
+ export class BinaryEncoder {
53
+ static topicToIdMap = new Map();
54
+ static idToTopicMap = new Map();
55
+ static hashTopic(topic) {
56
+ let hash = 0x811c9dc5;
57
+ for (let i = 0; i < topic.length; i++) {
58
+ hash ^= topic.charCodeAt(i);
59
+ hash = Math.imul(hash, 0x01000193) >>> 0;
60
+ }
61
+ return hash;
62
+ }
63
+ static getTopicId(topic) {
64
+ const existingId = this.topicToIdMap.get(topic);
65
+ if (existingId !== undefined) {
66
+ return existingId;
67
+ }
68
+ const topicId = this.hashTopic(topic);
69
+ const collisionTopic = this.idToTopicMap.get(topicId);
70
+ if (collisionTopic !== undefined && collisionTopic !== topic) {
71
+ throw new Error(`Topic hash collision detected between "${topic}" and "${collisionTopic}" (ID: ${topicId})`);
72
+ }
73
+ this.topicToIdMap.set(topic, topicId);
74
+ this.idToTopicMap.set(topicId, topic);
75
+ return topicId;
76
+ }
77
+ static getTopicName(topicId) {
78
+ return this.idToTopicMap.get(topicId);
79
+ }
80
+ static registerTopics(topics) {
81
+ for (const topic of topics) {
82
+ this.getTopicId(topic);
83
+ }
84
+ }
85
+ static resetRegistry() {
86
+ this.topicToIdMap.clear();
87
+ this.idToTopicMap.clear();
88
+ }
89
+ }
90
+ export class BinaryFrameSerializer {
91
+ static textEncoder = new TextEncoder();
92
+ // Reusable scratch buffer & DataView for header manipulations (Zero GC)
93
+ static headerBuffer = new ArrayBuffer(4);
94
+ static headerView = new DataView(BinaryFrameSerializer.headerBuffer);
95
+ static headerBytes = new Uint8Array(BinaryFrameSerializer.headerBuffer);
96
+ static encodeFrame(topic, p) {
97
+ const topicId = BinaryEncoder.getTopicId(topic);
98
+ let payloadBytes;
99
+ if (p instanceof Uint8Array) {
100
+ payloadBytes = p;
101
+ }
102
+ else if (typeof p === "string") {
103
+ payloadBytes = this.textEncoder.encode(p);
104
+ }
105
+ else {
106
+ payloadBytes = this.textEncoder.encode(JSON.stringify(p));
107
+ }
108
+ const frame = new Uint8Array(4 + payloadBytes.byteLength);
109
+ // 1. Write Uint32 Topic ID (Little-Endian) via byte copies (Zero DataView allocation)
110
+ this.headerView.setUint32(0, topicId, true);
111
+ frame.set(this.headerBytes, 0);
112
+ // 2. Copy Payload Bytes
113
+ frame.set(payloadBytes, 4);
114
+ return frame;
115
+ }
116
+ static decodeFrame(frameBytes) {
117
+ if (frameBytes.byteLength < 4) {
118
+ throw new Error("Invalid frame: buffer smaller than minimum header size (4 bytes).");
119
+ }
120
+ // Direct byte copy into static DataView to read Uint32 safely without memory allocation
121
+ this.headerBytes[0] = frameBytes[0];
122
+ this.headerBytes[1] = frameBytes[1];
123
+ this.headerBytes[2] = frameBytes[2];
124
+ this.headerBytes[3] = frameBytes[3];
125
+ const topicId = this.headerView.getUint32(0, true);
126
+ FLYWEIGHT_FRAME.topicId = topicId;
127
+ FLYWEIGHT_FRAME.topicName = BinaryEncoder.getTopicName(topicId);
128
+ FLYWEIGHT_FRAME.p = frameBytes.subarray(4); // Zero-copy view
129
+ return FLYWEIGHT_FRAME;
130
+ }
131
+ }
@@ -0,0 +1,20 @@
1
+ export declare const enum VM_OP {
2
+ PUSH_CONST = 0,
3
+ PUSH_CELL = 1,
4
+ ADD = 2,
5
+ SUB = 3,
6
+ MUL = 4,
7
+ DIV = 5,
8
+ RET = 7,
9
+ SUM_RANGE = 6,
10
+ AVG_RANGE = 8,
11
+ MIN_RANGE = 9,
12
+ MAX_RANGE = 10,
13
+ COUNT_RANGE = 11
14
+ }
15
+ export interface Program {
16
+ code: Int32Array;
17
+ consts: Float64Array;
18
+ ranges: Int32Array[];
19
+ }
20
+ //# sourceMappingURL=vm-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vm-types.d.ts","sourceRoot":"","sources":["../../src/comps/vm-types.ts"],"names":[],"mappings":"AACA,0BAAkB,KAAK;IACtB,UAAU,IAAI;IAAE,SAAS,IAAI;IAAE,GAAG,IAAI;IAAE,GAAG,IAAI;IAAE,GAAG,IAAI;IAAE,GAAG,IAAI;IAAE,GAAG,IAAI;IAC1E,SAAS,IAAI;IAAE,SAAS,IAAI;IAAE,SAAS,IAAI;IAAE,SAAS,KAAK;IAAE,WAAW,KAAK;CAC7E;AACD,MAAM,WAAW,OAAO;IAAG,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,YAAY,CAAC;IAAC,MAAM,EAAE,UAAU,EAAE,CAAA;CAAE"}
@@ -0,0 +1,76 @@
1
+ export declare function encodeUtf8(value: string): Uint8Array;
2
+ export declare function decodeUtf8(bytes: Uint8Array): string;
3
+ export declare function concatBytes(parts: Uint8Array[]): Uint8Array;
4
+ export declare function readUint32(bytes: Uint8Array, offset: number): number;
5
+ export declare function writeUint32(bytes: Uint8Array, offset: number, value: number): void;
6
+ export declare function readBigUint64(bytes: Uint8Array, offset: number): bigint;
7
+ export declare function writeBigUint64(bytes: Uint8Array, offset: number, value: bigint): void;
8
+ export declare function crc32(bytes: Uint8Array, start?: number, end?: number): number;
9
+ export type AvroWriteFn = (w: FastAvroWriter, v: A) => V;
10
+ export type AvroReadFn = (r: FastAvroReader) => A;
11
+ export type AVROField = {
12
+ name: S;
13
+ type: AVROSchema;
14
+ };
15
+ export type AVROSchema = S | AVROSchema[] | {
16
+ type?: S | AVROSchema[];
17
+ name?: S;
18
+ namespace?: S;
19
+ fields?: AVROField[];
20
+ items?: AVROSchema;
21
+ values?: AVROSchema;
22
+ symbols?: AR<S>;
23
+ size?: N;
24
+ };
25
+ export declare class FastAvroWriter {
26
+ buf: Buffer;
27
+ pos: N;
28
+ reset(): V;
29
+ private ensure;
30
+ byte(v: N): V;
31
+ bytes(v: Uint8Array): V;
32
+ long(value: N): V;
33
+ float(value: N): V;
34
+ double(value: N): V;
35
+ string(v: S): V;
36
+ finish(): Buffer;
37
+ }
38
+ export declare class FastAvroReader {
39
+ private readonly buf;
40
+ pos: N;
41
+ constructor(buf: Buffer);
42
+ byte(): N;
43
+ bytes(length: N): Buffer;
44
+ long(): N;
45
+ float(): N;
46
+ double(): N;
47
+ string(): S;
48
+ done(): B;
49
+ }
50
+ export declare class BINARY_AVRO_CODEGEN {
51
+ private readonly names;
52
+ private readonly writeRoot;
53
+ private readonly readRoot;
54
+ private readonly writeError;
55
+ private readonly readError;
56
+ private readonly writer;
57
+ private readonly errorSchema;
58
+ constructor(schema: AVROSchema);
59
+ private collect;
60
+ private resolve;
61
+ private kindOf;
62
+ private genMatch;
63
+ private genWrite;
64
+ private genRead;
65
+ encode_msg(msg: AVROValue): Buffer;
66
+ decode_msg(raw: A): AVROValue;
67
+ }
68
+ export declare const SAFE_ZIGZAG_LIMIT: number;
69
+ export declare const SIG_BUS_SCHEMA: AVROSchema;
70
+ export declare const WAL_KVDB_SCHEMA: AVROSchema;
71
+ export declare const KV_PAYLOAD_SCHEMA: AVROSchema;
72
+ export declare const ERROR_INFO_SCHEMA: AVROSchema;
73
+ export declare const AVRO_ERROR_SCHEMA: AVROSchema;
74
+ export declare const ENVELOPE_CODEC: BINARY_AVRO_CODEGEN;
75
+ export declare const PAYLOAD_CODEC: BINARY_AVRO_CODEGEN;
76
+ //# sourceMappingURL=binary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binary.d.ts","sourceRoot":"","sources":["../../src/db/binary.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAEpD;AACD,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEpD;AACD,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,UAAU,CAgB3D;AACD,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEpE;AACD,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAKlF;AACD,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,E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;AACF,eAAO,MAAM,iBAAiB,EAAE,UAO/B,CAAC;AACF,eAAO,MAAM,iBAAiB,EAAE,UAQ/B,CAAC;AACF,eAAO,MAAM,cAAc,qBAA2C,CAAC;AACvE,eAAO,MAAM,aAAa,qBAA6C,CAAC"}
@@ -0,0 +1,441 @@
1
+ // BIANRY
2
+ // #region ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
3
+ export function encodeUtf8(value) {
4
+ return new TextEncoder().encode(value);
5
+ }
6
+ export function decodeUtf8(bytes) {
7
+ return new TextDecoder().decode(bytes);
8
+ }
9
+ export function concatBytes(parts) {
10
+ let length = 0;
11
+ for (const part of parts) {
12
+ length += part.length;
13
+ }
14
+ const output = new Uint8Array(length);
15
+ let offset = 0;
16
+ for (const part of parts) {
17
+ output.set(part, offset);
18
+ offset += part.length;
19
+ }
20
+ return output;
21
+ }
22
+ export function readUint32(bytes, offset) {
23
+ return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;
24
+ }
25
+ export function writeUint32(bytes, offset, value) {
26
+ bytes[offset] = value & 0xff;
27
+ bytes[offset + 1] = (value >>> 8) & 0xff;
28
+ bytes[offset + 2] = (value >>> 16) & 0xff;
29
+ bytes[offset + 3] = (value >>> 24) & 0xff;
30
+ }
31
+ export function readBigUint64(bytes, offset) {
32
+ let value = 0n;
33
+ for (let i = 7; i >= 0; i--) {
34
+ value = (value << 8n) | BigInt(bytes[offset + i]);
35
+ }
36
+ return value;
37
+ }
38
+ export function writeBigUint64(bytes, offset, value) {
39
+ for (let i = 0; i < 8; i++) {
40
+ bytes[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);
41
+ }
42
+ }
43
+ // #endregion
44
+ // CRC
45
+ // #region ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
46
+ const CRC_TABLE = new Uint32Array(256);
47
+ for (let i = 0; i < 256; i++) {
48
+ let value = i;
49
+ for (let bit = 0; bit < 8; bit++) {
50
+ value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
51
+ }
52
+ CRC_TABLE[i] = value >>> 0;
53
+ }
54
+ export function crc32(bytes, start = 0, end = bytes.length) {
55
+ let crc = 0xffffffff;
56
+ for (let i = start; i < end; i++) {
57
+ crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
58
+ }
59
+ return (crc ^ 0xffffffff) >>> 0;
60
+ }
61
+ export class FastAvroWriter {
62
+ buf = Buffer.alloc(256);
63
+ pos = 0;
64
+ reset() { this.pos = 0; }
65
+ ensure(length) {
66
+ if (this.pos + length <= this.buf.length)
67
+ return;
68
+ let size = this.buf.length;
69
+ while (size < this.pos + length)
70
+ size *= 2;
71
+ const next = Buffer.alloc(size);
72
+ this.buf.copy(next, 0, 0, this.pos);
73
+ this.buf = next;
74
+ }
75
+ byte(v) { this.ensure(1); this.buf[this.pos++] = v; }
76
+ bytes(v) { this.ensure(v.length); this.buf.set(v, this.pos); this.pos += v.length; }
77
+ long(value) {
78
+ this.ensure(10);
79
+ if (Math.abs(value) <= SAFE_ZIGZAG_LIMIT) {
80
+ let n = value >= 0 ? value * 2 : (-value * 2 - 1);
81
+ while (n >= 128) {
82
+ this.buf[this.pos++] = (n % 128) | 0x80;
83
+ n = Math.floor(n / 128);
84
+ }
85
+ this.buf[this.pos++] = n;
86
+ return;
87
+ }
88
+ let n = BigInt(value);
89
+ n = n >= 0n ? n << 1n : ((-n) << 1n) - 1n;
90
+ while (n >= 0x80n) {
91
+ this.buf[this.pos++] = Number(n & 0x7fn) | 0x80;
92
+ n >>= 7n;
93
+ }
94
+ this.buf[this.pos++] = Number(n);
95
+ }
96
+ float(value) { this.ensure(4); this.buf.writeFloatLE(value, this.pos); this.pos += 4; }
97
+ double(value) { this.ensure(8); this.buf.writeDoubleLE(value, this.pos); this.pos += 8; }
98
+ string(v) {
99
+ const len = Buffer.byteLength(v, "utf8");
100
+ this.long(len);
101
+ this.ensure(len);
102
+ this.buf.write(v, this.pos, "utf8");
103
+ this.pos += len;
104
+ }
105
+ finish() { return Buffer.from(this.buf.subarray(0, this.pos)); }
106
+ }
107
+ export class FastAvroReader {
108
+ buf;
109
+ pos = 0;
110
+ constructor(buf) {
111
+ this.buf = buf;
112
+ }
113
+ byte() { return this.buf[this.pos++]; }
114
+ bytes(length) { const out = Buffer.from(this.buf.subarray(this.pos, this.pos + length)); this.pos += length; return out; }
115
+ long() {
116
+ let result = 0, shift = 0, b;
117
+ do {
118
+ b = this.buf[this.pos++];
119
+ result += (b & 0x7f) * Math.pow(2, shift);
120
+ shift += 7;
121
+ } while (b & 0x80);
122
+ return result % 2 === 0 ? result / 2 : -(result + 1) / 2;
123
+ }
124
+ float() { const n = this.buf.readFloatLE(this.pos); this.pos += 4; return n; }
125
+ double() { const n = this.buf.readDoubleLE(this.pos); this.pos += 8; return n; }
126
+ string() { const len = this.long(); const s = this.buf.toString("utf8", this.pos, this.pos + len); this.pos += len; return s; }
127
+ done() { return this.pos === this.buf.length; }
128
+ }
129
+ export class BINARY_AVRO_CODEGEN {
130
+ names = Object.create(null);
131
+ writeRoot;
132
+ readRoot;
133
+ writeError;
134
+ readError;
135
+ writer = new FastAvroWriter();
136
+ errorSchema = AVRO_ERROR_SCHEMA;
137
+ constructor(schema) {
138
+ if (Array.isArray(schema))
139
+ throw new Error("Avro: root schema cannot be a union");
140
+ this.collect(schema);
141
+ this.collect(this.errorSchema);
142
+ // Everything below runs exactly ONCE, here, at construction — the generated
143
+ // source text is the whole point: no schema-walking left at encode/decode time.
144
+ const writeBody = this.genWrite(schema, "value").join("\n");
145
+ const readBody = `return ${this.genRead(schema)};`;
146
+ this.writeRoot = new Function("w", "value", writeBody);
147
+ this.readRoot = new Function("r", readBody);
148
+ const errWriteBody = this.genWrite(this.errorSchema, "value").join("\n");
149
+ const errReadBody = `return ${this.genRead(this.errorSchema)};`;
150
+ this.writeError = new Function("w", "value", errWriteBody);
151
+ this.readError = new Function("r", errReadBody);
152
+ }
153
+ // ---- compile-time schema bookkeeping (never runs after construction) ----
154
+ collect(schema) {
155
+ if (Array.isArray(schema)) {
156
+ for (const b of schema)
157
+ this.collect(b);
158
+ return;
159
+ }
160
+ if (typeof schema === "string")
161
+ return;
162
+ if (schema.name)
163
+ this.names[schema.name] = schema;
164
+ if (Array.isArray(schema.type))
165
+ this.collect(schema.type);
166
+ else if (typeof schema.type === "object")
167
+ this.collect(schema.type);
168
+ else if (typeof schema.type === "string" && ![
169
+ "null", "boolean", "int", "long", "float", "double",
170
+ "bytes", "string", "record", "array", "map", "enum", "fixed",
171
+ ].includes(schema.type)) {
172
+ if (!this.names[schema.type])
173
+ throw new Error(`Avro: unknown named type ${schema.type}`);
174
+ }
175
+ if (schema.fields)
176
+ for (const field of schema.fields)
177
+ this.collect(field.type);
178
+ if (schema.items)
179
+ this.collect(schema.items);
180
+ if (schema.values)
181
+ this.collect(schema.values);
182
+ }
183
+ resolve(schema) {
184
+ if (typeof schema === "string" && this.names[schema])
185
+ return this.names[schema];
186
+ return schema;
187
+ }
188
+ kindOf(schema) {
189
+ schema = this.resolve(schema);
190
+ if (typeof schema === "string")
191
+ return schema;
192
+ if (Array.isArray(schema))
193
+ return "union";
194
+ return typeof schema.type === "string" ? schema.type : this.kindOf(schema.type);
195
+ }
196
+ // ---- codegen: produces an inline boolean-expression STRING testing a union branch ----
197
+ genMatch(schema, expr) {
198
+ schema = this.resolve(schema);
199
+ if (typeof schema === "string") {
200
+ switch (schema) {
201
+ case "null": return `(${expr} === null || ${expr} === undefined)`;
202
+ case "boolean": return `typeof ${expr} === "boolean"`;
203
+ case "int": return `typeof ${expr} === "number" && Number.isInteger(${expr})`;
204
+ case "long":
205
+ case "float":
206
+ case "double": return `typeof ${expr} === "number"`;
207
+ case "string": return `typeof ${expr} === "string"`;
208
+ case "bytes": return `${expr} instanceof Uint8Array`;
209
+ default: return "false";
210
+ }
211
+ }
212
+ if (Array.isArray(schema)) {
213
+ return schema.map(s => this.genMatch(s, expr)).join(" || ");
214
+ }
215
+ if (typeof schema.type !== "string")
216
+ return this.genMatch(schema.type, expr);
217
+ switch (schema.type) {
218
+ case "fixed": return `${expr} instanceof Uint8Array && ${expr}.length === ${schema.size}`;
219
+ case "enum": return `${JSON.stringify(schema.symbols)}.includes(${expr})`;
220
+ case "array": return `Array.isArray(${expr})`;
221
+ case "map":
222
+ case "record": return `${expr} !== null && typeof ${expr} === "object" && !Array.isArray(${expr})`;
223
+ default: return this.genMatch(schema.type, expr);
224
+ }
225
+ }
226
+ // ---- codegen: produces an array of JS STATEMENT strings that write `expr` into `w` ----
227
+ genWrite(schema, expr) {
228
+ schema = this.resolve(schema);
229
+ if (Array.isArray(schema)) {
230
+ if (schema.length === 2) {
231
+ const nullIdx = schema.findIndex((s) => this.kindOf(s) === "null");
232
+ if (nullIdx !== -1) {
233
+ const otherIdx = nullIdx === 0 ? 1 : 0;
234
+ // common case: an optional field — special-cased to skip the generic
235
+ // branch-scan entirely, since this covers most unions you'll ever write.
236
+ return [`if (${expr} === null || ${expr} === undefined) { w.long(${nullIdx}); } else { w.long(${otherIdx}); ${this.genWrite(schema[otherIdx], expr).join(" ")} }`];
237
+ }
238
+ }
239
+ const branches = schema.map((s, i) => `if (${this.genMatch(s, expr)}) { w.long(${i}); ${this.genWrite(s, expr).join(" ")} }`);
240
+ return [branches.join(" else ") + " else { throw new Error('Avro: no matching union branch'); }"];
241
+ }
242
+ if (typeof schema === "string") {
243
+ switch (schema) {
244
+ case "null": return [];
245
+ case "boolean": return [`w.byte(${expr} ? 1 : 0);`];
246
+ case "int":
247
+ case "long": return [`w.long(${expr});`];
248
+ case "float": return [`w.float(${expr});`];
249
+ case "double": return [`w.double(${expr});`];
250
+ case "string": return [`w.string(${expr});`];
251
+ case "bytes": return [`w.long(${expr}.length); w.bytes(${expr});`];
252
+ default: throw new Error(`Avro: unknown type ${schema}`);
253
+ }
254
+ }
255
+ if (typeof schema.type !== "string")
256
+ return this.genWrite(schema.type, expr);
257
+ switch (schema.type) {
258
+ case "null": return [];
259
+ case "boolean": return [`w.byte(${expr} ? 1 : 0);`];
260
+ case "int":
261
+ case "long": return [`w.long(${expr});`];
262
+ case "float": return [`w.float(${expr});`];
263
+ case "double": return [`w.double(${expr});`];
264
+ case "string": return [`w.string(${expr});`];
265
+ case "bytes": return [`w.long(${expr}.length); w.bytes(${expr});`];
266
+ case "fixed": {
267
+ const size = schema.size;
268
+ return [`if (!(${expr} instanceof Uint8Array) || ${expr}.length !== ${size}) throw new Error("Avro: invalid fixed value"); w.bytes(${expr});`];
269
+ }
270
+ case "enum": {
271
+ const symbols = JSON.stringify(schema.symbols);
272
+ return [`{ const i = ${symbols}.indexOf(${expr}); if (i < 0) throw new Error("Avro: invalid enum symbol " + ${expr}); w.long(i); }`];
273
+ }
274
+ case "record": {
275
+ const lines = [];
276
+ for (const f of schema.fields)
277
+ lines.push(...this.genWrite(f.type, `${expr}[${JSON.stringify(f.name)}]`));
278
+ return lines;
279
+ }
280
+ case "array": {
281
+ const inner = this.genWrite(schema.items, "arr[i]").join(" ");
282
+ return [`{ const arr = ${expr}; if (arr.length) { w.long(arr.length); for (let i = 0; i < arr.length; i++) { ${inner} } } w.long(0); }`];
283
+ }
284
+ case "map": {
285
+ const inner = this.genWrite(schema.values, "obj[k]").join(" ");
286
+ return [`{ const obj = ${expr}; const keys = Object.keys(obj); if (keys.length) { w.long(keys.length); for (let i = 0; i < keys.length; i++) { const k = keys[i]; w.string(k); ${inner} } } w.long(0); }`];
287
+ }
288
+ default: throw new Error(`Avro: unsupported schema type ${schema.type}`);
289
+ }
290
+ }
291
+ // ---- codegen: produces a single JS EXPRESSION string that reads one value from `r` ----
292
+ genRead(schema) {
293
+ schema = this.resolve(schema);
294
+ if (Array.isArray(schema)) {
295
+ const cases = schema.map((s, i) => `case ${i}: return ${this.genRead(s)};`).join(" ");
296
+ return `(function(){ const i = r.long(); switch(i){ ${cases} default: throw new Error("Avro: invalid union index"); } })()`;
297
+ }
298
+ if (typeof schema === "string") {
299
+ switch (schema) {
300
+ case "null": return "null";
301
+ case "boolean": return "(r.byte() === 1)";
302
+ case "int":
303
+ case "long": return "r.long()";
304
+ case "float": return "r.float()";
305
+ case "double": return "r.double()";
306
+ case "string": return "r.string()";
307
+ case "bytes": return "r.bytes(r.long())";
308
+ default: throw new Error(`Avro: unknown type ${schema}`);
309
+ }
310
+ }
311
+ if (typeof schema.type !== "string")
312
+ return this.genRead(schema.type);
313
+ switch (schema.type) {
314
+ case "null": return "null";
315
+ case "boolean": return "(r.byte() === 1)";
316
+ case "int":
317
+ case "long": return "r.long()";
318
+ case "float": return "r.float()";
319
+ case "double": return "r.double()";
320
+ case "string": return "r.string()";
321
+ case "bytes": return "r.bytes(r.long())";
322
+ case "fixed": return `r.bytes(${schema.size})`;
323
+ case "enum": return `(${JSON.stringify(schema.symbols)})[r.long()]`;
324
+ case "record": {
325
+ const assigns = schema.fields.map((f) => `o[${JSON.stringify(f.name)}] = ${this.genRead(f.type)};`).join(" ");
326
+ return `(function(){ const o = {}; ${assigns} return o; })()`;
327
+ }
328
+ case "array": return `(function(){ const out = []; let c; while ((c = r.long()) !== 0) { for (let i = 0; i < c; i++) out.push(${this.genRead(schema.items)}); } return out; })()`;
329
+ case "map": return `(function(){ const out = {}; let c; while ((c = r.long()) !== 0) { for (let i = 0; i < c; i++) { const k = r.string(); out[k] = ${this.genRead(schema.values)}; } } return out; })()`;
330
+ default: throw new Error(`Avro: unsupported schema type ${schema.type}`);
331
+ }
332
+ }
333
+ // ---- public API: identical contract to BINARY_AVRO_FAST / the original BINARY_AVRO ----
334
+ encode_msg(msg) {
335
+ if (msg instanceof Uint8Array)
336
+ return msg;
337
+ try {
338
+ this.writer.reset();
339
+ this.writer.long(0);
340
+ this.writeRoot(this.writer, msg);
341
+ return this.writer.finish();
342
+ }
343
+ catch (err) {
344
+ console.log("[AVRO_PIPE] Failed to encode outbound packet:", err);
345
+ this.writer.reset();
346
+ this.writer.long(1);
347
+ this.writeError(this.writer, {
348
+ type: "error",
349
+ error: err instanceof Error ? err.message : "Encoding failed",
350
+ id: String(msg?.id ?? "unknown"),
351
+ });
352
+ return this.writer.finish();
353
+ }
354
+ }
355
+ decode_msg(raw) {
356
+ if (!(raw instanceof Uint8Array)) {
357
+ console.error("[AVRO_PIPE] Protocol violation: Expected encoded Uint8Array data stream.");
358
+ return null;
359
+ }
360
+ try {
361
+ const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
362
+ const r = new FastAvroReader(buf);
363
+ const branch = r.long();
364
+ if (branch !== 0 && branch !== 1)
365
+ throw new Error("Avro: invalid envelope branch");
366
+ const value = branch === 0 ? this.readRoot(r) : this.readError(r);
367
+ if (!r.done())
368
+ throw new Error("Avro: trailing bytes");
369
+ return value;
370
+ }
371
+ catch (err) {
372
+ console.error("[AVRO_PIPE] Failed to decode inbound packet:", err);
373
+ return null;
374
+ }
375
+ }
376
+ }
377
+ export const SAFE_ZIGZAG_LIMIT = Number.MAX_SAFE_INTEGER / 2;
378
+ export const SIG_BUS_SCHEMA = {
379
+ type: "record",
380
+ name: "SIGBusMessage",
381
+ fields: [
382
+ { name: "v", type: "int" }, // protocol/schema version
383
+ { name: "kind", type: "int" }, // 0 request, 1 response, 2 event, 3 control
384
+ { name: "id", type: "string" },
385
+ { name: "r", type: "string" },
386
+ { name: "m", type: "string" },
387
+ { name: "s", type: "string" },
388
+ { name: "k", type: "string" },
389
+ { name: "p", type: "bytes" }, // payload, optionally Avro/MessagePack encoded
390
+ { name: "ts", type: "long" },
391
+ { name: "ack", type: "boolean" },
392
+ { name: "replyTo", type: ["null", "string"] },
393
+ { name: "stream", type: ["null", "boolean"] },
394
+ { name: "end", type: ["null", "boolean"] },
395
+ { name: "ttl", type: ["null", "long"] },
396
+ ]
397
+ };
398
+ export const WAL_KVDB_SCHEMA = {
399
+ type: "record",
400
+ name: "SIGBusMessage",
401
+ fields: [
402
+ { name: "op", type: "int" },
403
+ { name: "id", type: "string" },
404
+ { name: "r", type: "string" },
405
+ { name: "m", type: "string" },
406
+ { name: "s", type: "string" },
407
+ { name: "k", type: "string" },
408
+ { name: "p", type: "bytes" },
409
+ { name: "replyTo", type: "string" },
410
+ { name: "error", type: "string" }
411
+ ]
412
+ };
413
+ export const KV_PAYLOAD_SCHEMA = {
414
+ type: "record",
415
+ name: "KVPayload",
416
+ fields: [
417
+ { name: "key", type: "string" },
418
+ { name: "value", type: "bytes" },
419
+ { name: "ok", type: "boolean" }
420
+ ]
421
+ };
422
+ export const ERROR_INFO_SCHEMA = {
423
+ type: "record",
424
+ name: "ErrorInfo",
425
+ fields: [
426
+ { name: "message", type: "string" },
427
+ { name: "code", type: "int" }
428
+ ]
429
+ };
430
+ export const AVRO_ERROR_SCHEMA = {
431
+ type: "record",
432
+ name: "AVROError",
433
+ fields: [
434
+ { name: "type", type: "string" },
435
+ { name: "error", type: "string" },
436
+ { name: "id", type: "string" },
437
+ ],
438
+ };
439
+ export const ENVELOPE_CODEC = new BINARY_AVRO_CODEGEN(WAL_KVDB_SCHEMA);
440
+ export const PAYLOAD_CODEC = new BINARY_AVRO_CODEGEN(KV_PAYLOAD_SCHEMA);
441
+ // #endregion