pojoc 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,10 +8,23 @@ npm install pojoc
8
8
  pojoc build player.pojoc --target typescript -o generated
9
9
  ```
10
10
 
11
- Use the exports of the generated module for schema-specific encoding,
12
- decoding, and seeking. The runtime has zero runtime dependencies and ships
13
- as JavaScript ES modules with TypeScript declarations. The `pojoc/v1`
14
- entry point identifies the schema descriptor format used by the generator.
11
+ Use the generated module to create, encode, and decode values.
12
+
13
+ ```ts
14
+ import { create, decode, encode } from "./generated/player.ts";
15
+
16
+ const player = create();
17
+ const bytes = encode(player); // Uint8Array
18
+ const roundTrip = decode(bytes); // Player
19
+ ```
20
+
21
+ `create()` fills in omitted fields from the schema defaults. Optional fields
22
+ have type `T | null`. Pass `null` to encode an absent value.
23
+
24
+ The runtime ships as JavaScript ES modules with TypeScript declarations and
25
+ zero runtime dependencies. Generated modules import shared primitives from
26
+ `pojoc/v1/compiler`. The [schema reference](../../docs/schema.md) covers
27
+ type mappings, defaults, and field access.
15
28
 
16
29
  ## Publishing
17
30
 
@@ -0,0 +1,30 @@
1
+ import type { Cursor, ReadTable } from "./types.js";
2
+ import type { SchemaSpec } from "./legacy_types.js";
3
+ import { type AccessField, type AccessLayout } from "./schema.js";
4
+ declare function skipField(r: Cursor, header: number, entry: AccessField, schemas: SchemaSpec[], scope: number): void;
5
+ declare function readAccessField(r: Cursor, header: number, entry: AccessField, schemas: SchemaSpec[], scope: number, table: ReadTable): unknown;
6
+ declare function compileView(layout: AccessLayout, intern: boolean, schemas: SchemaSpec[], scope: number): {
7
+ new (cursor: Cursor): {
8
+ "__#private@#positions": number[];
9
+ "__#private@#values": unknown[];
10
+ "__#private@#access"?: {
11
+ table: ReadTable;
12
+ header: number;
13
+ start: number;
14
+ };
15
+ "__#private@#cursor": Cursor;
16
+ "__#private@#read"(entry: AccessField): unknown;
17
+ };
18
+ getter(entry: AccessField): (this: {
19
+ "__#private@#positions": number[];
20
+ "__#private@#values": unknown[];
21
+ "__#private@#access"?: {
22
+ table: ReadTable;
23
+ header: number;
24
+ start: number;
25
+ };
26
+ "__#private@#cursor": Cursor;
27
+ "__#private@#read"(entry: AccessField): unknown;
28
+ }) => unknown;
29
+ };
30
+ export { skipField, readAccessField, compileView };
package/dist/access.js ADDED
@@ -0,0 +1,174 @@
1
+ import { emptyTable, limitCollection, readByte, readLength, readTableOffsets, readVarint, readVarint32, tableLength, takeBytes, } from "./wire.js";
2
+ import { arrayOf, fixedWidths } from "./scalars.js";
3
+ import { accessLayout, present, versionLayout, } from "./schema.js";
4
+ import { readValue, validate } from "./payload.js";
5
+ function skipRecord(r, fields, schemas, scope) {
6
+ const layout = accessLayout(fields);
7
+ const header = takeBytes(r, layout.bitmapBytes);
8
+ takeBytes(r, layout.fixedWidth);
9
+ for (let i = layout.fixedCount; i < layout.fields.length; i++) {
10
+ skipField(r, header, layout.fields[i], schemas, scope);
11
+ }
12
+ }
13
+ function skipValue(r, ty, schemas, scope, historical = false) {
14
+ if (typeof ty === "string") {
15
+ if (ty === "string")
16
+ takeBytes(r, readLength(r));
17
+ else if (ty === "varint32")
18
+ readVarint32(r);
19
+ else if (ty === "varint64")
20
+ readVarint(r);
21
+ else if (ty === "intern")
22
+ readLength(r);
23
+ else
24
+ takeBytes(r, fixedWidths[ty]);
25
+ return;
26
+ }
27
+ const schema = schemas[scope];
28
+ switch (ty[0]) {
29
+ case "bytes":
30
+ case "bits":
31
+ case "enum":
32
+ takeBytes(r, ty[1]);
33
+ return;
34
+ case "union":
35
+ takeBytes(r, ty[1]);
36
+ takeBytes(r, readLength(r));
37
+ return;
38
+ case "vfloat":
39
+ takeBytes(r, ty[3]);
40
+ return;
41
+ case "optional":
42
+ if (readByte(r))
43
+ skipValue(r, ty[1], schemas, scope, historical);
44
+ return;
45
+ case "constraint":
46
+ case "box":
47
+ return skipValue(r, ty[1], schemas, scope, historical);
48
+ case "record":
49
+ return skipRecord(r, schema.records[historical ? ty[1] : ty[2]], schemas, scope);
50
+ case "import": {
51
+ const childScope = schema.imports[ty[1]];
52
+ const child = versionLayout(schemas[childScope], ty[2]);
53
+ if (child.intern) {
54
+ const count = tableLength(r);
55
+ for (let i = 0; i < count; i++)
56
+ takeBytes(r, readLength(r));
57
+ }
58
+ return skipRecord(r, child.fields, schemas, childScope);
59
+ }
60
+ case "tuple":
61
+ for (const item of ty[1])
62
+ skipValue(r, item, schemas, scope);
63
+ return;
64
+ case "array":
65
+ case "delta": {
66
+ const count = ty[2] ?? readLength(r);
67
+ const ctor = ty[0] === "array" && arrayOf(ty[1]);
68
+ if (ctor) {
69
+ takeBytes(r, count * ctor.BYTES_PER_ELEMENT);
70
+ return;
71
+ }
72
+ limitCollection(count);
73
+ const element = ty[1];
74
+ if (ty[0] === "array" &&
75
+ typeof element !== "string" &&
76
+ element[0] === "record") {
77
+ const record = schema.cursorRecordReaders?.[element[2]];
78
+ if (record && typeof record !== "function") {
79
+ takeBytes(r, count * record.width);
80
+ return;
81
+ }
82
+ }
83
+ for (let i = 0; i < count; i++) {
84
+ if (ty[0] === "delta")
85
+ readVarint(r);
86
+ else
87
+ skipValue(r, element, schemas, scope);
88
+ }
89
+ return;
90
+ }
91
+ case "map": {
92
+ const count = ty[3] ?? readLength(r);
93
+ limitCollection(count);
94
+ for (let i = 0; i < count; i++) {
95
+ skipValue(r, ty[1], schemas, scope);
96
+ skipValue(r, ty[2], schemas, scope);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ function skipField(r, header, entry, schemas, scope) {
102
+ if (present(r, header, entry.bit))
103
+ skipValue(r, entry.ty, schemas, scope, entry.field.cast);
104
+ }
105
+ function readAccessField(r, header, entry, schemas, scope, table) {
106
+ if (!present(r, header, entry.bit))
107
+ return null;
108
+ const { ty, field } = entry;
109
+ const value = readValue(r, ty, schemas, scope, table, field.cast);
110
+ validate(ty, value, field.name);
111
+ return value;
112
+ }
113
+ function compileView(layout, intern, schemas, scope) {
114
+ class View {
115
+ #positions = [];
116
+ #values = [];
117
+ #access;
118
+ #cursor;
119
+ constructor(cursor) {
120
+ this.#cursor = cursor;
121
+ }
122
+ static getter(entry) {
123
+ return function () {
124
+ return this.#read(entry);
125
+ };
126
+ }
127
+ #read(entry) {
128
+ const { index, offset } = entry;
129
+ if (Object.hasOwn(this.#values, index))
130
+ return this.#values[index];
131
+ const r = this.#cursor;
132
+ if (!this.#access) {
133
+ const frameStart = r.pos;
134
+ try {
135
+ const table = intern ? readTableOffsets(r) : emptyTable;
136
+ const header = takeBytes(r, layout.bitmapBytes);
137
+ const start = takeBytes(r, layout.fixedWidth);
138
+ this.#positions.push(r.pos);
139
+ this.#access = { table, header, start };
140
+ }
141
+ catch (error) {
142
+ r.pos = frameStart;
143
+ throw error;
144
+ }
145
+ }
146
+ const { table, header, start } = this.#access;
147
+ const positions = this.#positions;
148
+ const tailIndex = index - layout.fixedCount;
149
+ if (offset >= 0) {
150
+ r.pos = start + offset;
151
+ }
152
+ else {
153
+ r.pos = positions[positions.length - 1];
154
+ for (let i = positions.length - 1; i < tailIndex; i++) {
155
+ skipField(r, header, layout.fields[i + layout.fixedCount], schemas, scope);
156
+ positions.push(r.pos);
157
+ }
158
+ r.pos = positions[tailIndex];
159
+ }
160
+ const value = readAccessField(r, header, entry, schemas, scope, table);
161
+ if (offset < 0 && tailIndex + 1 === positions.length)
162
+ positions.push(r.pos);
163
+ this.#values[index] = value;
164
+ return value;
165
+ }
166
+ }
167
+ for (const entry of layout.fields) {
168
+ Object.defineProperty(View.prototype, entry.field.name, {
169
+ get: View.getter(entry),
170
+ });
171
+ }
172
+ return View;
173
+ }
174
+ export { skipField, readAccessField, compileView };
@@ -0,0 +1,12 @@
1
+ import type { Input, Version } from "./types.js";
2
+ import type { SchemaSpec } from "./legacy_types.js";
3
+ import { type Envelope } from "./wire.js";
4
+ declare function encodePlanned<T>(value: T, version: Version, schemas: SchemaSpec[], scope: number): Uint8Array;
5
+ declare function decodePlanned<T>(reader: Envelope, current: bigint, schemas: SchemaSpec[], scope: number): T;
6
+ declare function createPlanned<T>(value: Partial<T>, schemas: SchemaSpec[], scope: number): T;
7
+ type OpenFrame = (input: Input, offset: number) => Envelope;
8
+ type DecodeFrame<T> = (reader: Envelope) => T;
9
+ declare function openPlanned<T>(r: Envelope, current: bigint, schemas: SchemaSpec[], scope: number, decodeFrame: DecodeFrame<T>): Readonly<T>;
10
+ declare function selectPlanned<T, K extends keyof T & string>(keys: readonly K[], current: bigint, schemas: SchemaSpec[], scope: number, openFrame: OpenFrame, decodeFrame: DecodeFrame<T>): (input: Input, offset?: number) => Pick<T, K>;
11
+ declare function seekPlanned(input: Input, path: string, current: bigint, schemas: SchemaSpec[], scope: number, openFrame: OpenFrame, decodeFrame: DecodeFrame<unknown>): unknown;
12
+ export { createPlanned, decodePlanned, encodePlanned, openPlanned, selectPlanned, seekPlanned, };
package/dist/codec.js ADDED
@@ -0,0 +1,127 @@
1
+ import { finishDecode, versionNumber } from "./compiled.js";
2
+ import { emptyTable, invalid, readTableOffsets, takeBytes, } from "./wire.js";
3
+ import { beginWrite, finishEnvelope, takeWrite, writeVarint, } from "./writer.js";
4
+ import { accessLayout, object, setField, versionLayout, } from "./schema.js";
5
+ import { defaults } from "./versions.js";
6
+ import { readPayload, writePayload } from "./payload.js";
7
+ import { compileView, readAccessField, skipField } from "./access.js";
8
+ function encodePlanned(value, version, schemas, scope) {
9
+ const n = versionNumber(version);
10
+ const schema = schemas[scope];
11
+ const writer = beginWrite(schema.runtime === "bun" || schema.runtime === "node");
12
+ writeVarint(writer, n);
13
+ const length = takeWrite(writer, 5);
14
+ writePayload(writer, schemas, scope, n.toString(), object(value));
15
+ return finishEnvelope(writer, length);
16
+ }
17
+ function decodePlanned(reader, current, schemas, scope) {
18
+ const version = reader.version === current
19
+ ? schemas[scope].latest
20
+ : reader.version.toString();
21
+ return finishDecode(reader, readPayload(reader, schemas, scope, version));
22
+ }
23
+ function createPlanned(value, schemas, scope) {
24
+ const schema = schemas[scope];
25
+ return defaults(versionLayout(schema, schema.latest).fields, object(value), schemas, scope);
26
+ }
27
+ const views = new WeakMap();
28
+ function openPlanned(r, current, schemas, scope, decodeFrame) {
29
+ if (r.version !== current)
30
+ return Object.freeze(decodeFrame(r));
31
+ let byScope = views.get(schemas);
32
+ if (!byScope)
33
+ views.set(schemas, (byScope = new Map()));
34
+ let view = byScope.get(scope);
35
+ if (!view) {
36
+ const schema = schemas[scope];
37
+ const latest = versionLayout(schema, schema.latest);
38
+ view = compileView(accessLayout(latest.fields), latest.intern, schemas, scope);
39
+ byScope.set(scope, view);
40
+ }
41
+ return new view(r);
42
+ }
43
+ function selectPlanned(keys, current, schemas, scope, openFrame, decodeFrame) {
44
+ const schema = schemas[scope];
45
+ const latest = versionLayout(schema, schema.latest);
46
+ const layout = accessLayout(latest.fields);
47
+ const fields = Array.from(new Set(keys), (key) => {
48
+ const entry = layout.byName.get(key);
49
+ if (!entry)
50
+ invalid(`Unknown Pojoc field ${key}`);
51
+ return entry;
52
+ }).sort((a, b) => a.index - b.index);
53
+ return function projectFields(input, offset = 0) {
54
+ const r = openFrame(input, offset);
55
+ const result = {};
56
+ if (r.version !== current) {
57
+ const value = decodeFrame(r);
58
+ for (const { field } of fields)
59
+ setField(result, field.name, value[field.name]);
60
+ return result;
61
+ }
62
+ if (fields.length === 0)
63
+ return result;
64
+ const table = latest.intern ? readTableOffsets(r) : emptyTable;
65
+ const header = takeBytes(r, layout.bitmapBytes);
66
+ const start = takeBytes(r, layout.fixedWidth);
67
+ let tail = r.pos;
68
+ let next = layout.fixedCount;
69
+ for (const entry of fields) {
70
+ if (entry.offset >= 0) {
71
+ r.pos = start + entry.offset;
72
+ }
73
+ else {
74
+ r.pos = tail;
75
+ while (next < entry.index)
76
+ skipField(r, header, layout.fields[next++], schemas, scope);
77
+ }
78
+ setField(result, entry.field.name, readAccessField(r, header, entry, schemas, scope, table));
79
+ if (entry.offset < 0) {
80
+ tail = r.pos;
81
+ next++;
82
+ }
83
+ }
84
+ return result;
85
+ };
86
+ }
87
+ function seekPlanned(input, path, current, schemas, scope, openFrame, decodeFrame) {
88
+ const schema = schemas[scope];
89
+ const latest = versionLayout(schema, schema.latest);
90
+ const names = path.split(".");
91
+ const hops = [];
92
+ let layout = accessLayout(latest.fields);
93
+ for (let i = 0; i < names.length; i++) {
94
+ const entry = layout.byName.get(names[i]);
95
+ if (!entry?.field.seek)
96
+ invalid(`Unknown seekable Pojoc path ${path}`);
97
+ hops.push({ layout, entry });
98
+ if (i + 1 < names.length) {
99
+ const ty = entry.field.ty;
100
+ if (entry.field.lazy || typeof ty === "string" || ty[0] !== "record")
101
+ invalid(`Invalid nested path ${path}`);
102
+ layout = accessLayout(schema.records[ty[2]]);
103
+ }
104
+ }
105
+ const r = openFrame(input, 0);
106
+ if (r.version !== current) {
107
+ let value = decodeFrame(r);
108
+ for (const name of names)
109
+ value = object(value)[name];
110
+ return value;
111
+ }
112
+ const table = latest.intern ? readTableOffsets(r) : emptyTable;
113
+ for (let i = 0; i < hops.length; i++) {
114
+ const { layout, entry } = hops[i];
115
+ const header = takeBytes(r, layout.bitmapBytes);
116
+ const start = takeBytes(r, layout.fixedWidth);
117
+ if (entry.offset >= 0)
118
+ r.pos = start + entry.offset;
119
+ else {
120
+ for (let j = layout.fixedCount; j < entry.index; j++)
121
+ skipField(r, header, layout.fields[j], schemas, scope);
122
+ }
123
+ if (i + 1 === hops.length)
124
+ return readAccessField(r, header, entry, schemas, scope, table);
125
+ }
126
+ }
127
+ export { createPlanned, decodePlanned, encodePlanned, openPlanned, selectPlanned, seekPlanned, };
@@ -0,0 +1,43 @@
1
+ import type { Cursor, Obj, ReadTable, Version } from "./types.js";
2
+ import { type WriteCursor, type WriteInterner } from "./writer.js";
3
+ type WriteTable = WriteInterner | undefined;
4
+ type ReadItem<T = unknown> = (r: Cursor, table: ReadTable) => T;
5
+ type WriteItem = (w: WriteCursor, value: unknown, table: WriteTable) => void;
6
+ declare function object(value: unknown): Obj;
7
+ declare function setField(target: Obj, name: string, value: unknown): void;
8
+ declare function versionNumber(version: Version): bigint;
9
+ declare function unsupported(version: bigint): never;
10
+ declare function finishDecode<T>(r: Cursor, value: Obj): T;
11
+ declare function writePayloadWithTable(w: WriteCursor, value: Obj, intern: boolean, write: (w: WriteCursor, value: Obj, table: WriteTable) => void): void;
12
+ declare function encodeCompiledPayload(value: unknown, version: number | readonly number[], intern: boolean, write: (w: WriteCursor, value: Obj, table: WriteTable) => void): Uint8Array<ArrayBuffer>;
13
+ declare function encodeFixedPayload(value: unknown, header: Uint8Array<ArrayBuffer>, frameSize: number, write: (w: WriteCursor, value: Obj, table: WriteTable) => void): Uint8Array<ArrayBuffer>;
14
+ declare function readFixedRecords<T>(r: Cursor, count: number, width: number, read: (r: Cursor, pos: number) => T): T[];
15
+ type FixedRecordView<Row> = {
16
+ readonly length: number;
17
+ get<Key extends keyof Row>(index: number, key: Key): Row[Key];
18
+ };
19
+ declare function fixedRecordView(r: Cursor, count: number, width: number, read: (r: Cursor, pos: number, key: PropertyKey) => unknown): FixedRecordView<Obj>;
20
+ declare function materializedRecordView<Row extends object>(rows: readonly Row[]): FixedRecordView<Row>;
21
+ declare function readItems<T>(r: Cursor, count: number, table: ReadTable, read: ReadItem<T>): T[];
22
+ declare function readPairs(r: Cursor, size: number | null, table: ReadTable, key: ReadItem, item: ReadItem): Map<unknown, unknown> | [unknown, unknown][];
23
+ declare function readVariant(r: Cursor, size: number, table: ReadTable, kind: string, read: ReadItem): {
24
+ kind: string;
25
+ value: unknown;
26
+ };
27
+ declare function writeVariant(w: WriteCursor, value: unknown, table: WriteTable, width: number, discriminant: unknown, write?: WriteItem): void;
28
+ declare function writeFixedBytes(w: WriteCursor, value: unknown, width: number, bitsetWidth?: number): void;
29
+ declare function writeVFloat(w: WriteCursor, value: unknown, width: number, min: number, step: number): void;
30
+ declare function arrayItems(w: WriteCursor, value: unknown, count: number | null): ArrayLike<unknown>;
31
+ declare function writePacked(w: WriteCursor, value: unknown, ctor: {
32
+ new (length: number): Exclude<ArrayBufferView, DataView>;
33
+ }): boolean;
34
+ declare function writePairs(w: WriteCursor, value: unknown, table: WriteTable, size: number | null, key: WriteItem, item: WriteItem): void;
35
+ declare function skipTable(r: Cursor): void;
36
+ declare function skipDelta(r: Cursor, count: number): void;
37
+ declare function validateRange(value: unknown, min: number | null, max: number | null, field: string): void;
38
+ declare function castScalar(value: unknown, fromFloat: boolean, to: string): unknown;
39
+ declare function arrayDefault(count: number, make: (index: number) => unknown): unknown[];
40
+ declare function adaptArray(value: unknown, count: number | null, make: () => unknown): unknown[];
41
+ declare function adaptMap(value: unknown, count: number, pad: boolean, make: () => [unknown, unknown]): [unknown, unknown][];
42
+ export type { FixedRecordView, ReadItem, WriteItem, WriteTable };
43
+ export { object, setField, versionNumber, unsupported, finishDecode, writePayloadWithTable, encodeCompiledPayload, encodeFixedPayload, readFixedRecords, fixedRecordView, materializedRecordView, readItems, readPairs, readVariant, writeVariant, writeFixedBytes, writeVFloat, arrayItems, writePacked, writePairs, skipTable, skipDelta, validateRange, castScalar, arrayDefault, adaptArray, adaptMap, };