@northtalk/ts 0.0.0-stage → 0.1.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.
@@ -0,0 +1,479 @@
1
+ import { E as listValues, F as quantity, Gt as parseInstant, L as range, S as instant, V as text, a as invalidValue, at as assertScalarText, c as bool, f as civilDate, h as dec, j as nothing, k as map, s as Value, u as bytesOf, x as hiddenCodePoint } from "./errors-DHwz1Vho.js";
2
+ import { s as fromBase64 } from "./encoding-DWlbPq-e.js";
3
+ //#region src/readers.ts
4
+ var Reader = class {
5
+ source;
6
+ i = 0;
7
+ constructor(source) {
8
+ this.source = source;
9
+ assertScalarText(source);
10
+ }
11
+ fail(what) {
12
+ return invalidValue(`${what} at column ${this.i + 1}`);
13
+ }
14
+ peek(s) {
15
+ return this.source.startsWith(s, this.i);
16
+ }
17
+ eat(s) {
18
+ if (!this.peek(s)) this.fail(`Expected ${s}`);
19
+ this.i += s.length;
20
+ }
21
+ match(re) {
22
+ re.lastIndex = this.i;
23
+ const result = re.exec(this.source);
24
+ if (!result || result.index !== this.i) return;
25
+ this.i += result[0].length;
26
+ return result[0];
27
+ }
28
+ done() {
29
+ if (this.i !== this.source.length) this.fail("Unexpected trailing input");
30
+ }
31
+ };
32
+ const resolved = (r) => r ? Value.isValue(r) ? r : r.value : void 0;
33
+ var DisplayReader = class extends Reader {
34
+ resolve;
35
+ resolveFunction;
36
+ constructor(source, resolve, resolveFunction) {
37
+ super(source);
38
+ this.resolve = resolve;
39
+ this.resolveFunction = resolveFunction;
40
+ }
41
+ value() {
42
+ const frames = [];
43
+ let value;
44
+ for (;;) {
45
+ if (!value) {
46
+ if (this.peek("<function ")) {
47
+ const start = this.i;
48
+ this.eat("<function ");
49
+ if (!this.match(/[A-Z_a-z][\w-]*(?:\+\d+)?:(?:[A-Z_a-z][\w-]*:)?(?:\d+:\d+|[A-Z_a-z][\w-]*)/y)) this.fail("Expected a Function Value location");
50
+ if (this.peek(">")) {
51
+ this.eat(">");
52
+ value = this.functionValue(start);
53
+ } else {
54
+ this.eat(" ");
55
+ if (!this.peek("{")) this.fail("Expected Function Value captures");
56
+ frames.push({
57
+ kind: "function",
58
+ start
59
+ });
60
+ continue;
61
+ }
62
+ } else if (this.peek("[")) {
63
+ this.eat("[");
64
+ if (this.peek("]")) {
65
+ this.eat("]");
66
+ value = listValues([]);
67
+ } else {
68
+ frames.push({
69
+ kind: "list",
70
+ values: []
71
+ });
72
+ continue;
73
+ }
74
+ } else if (this.peek("{")) {
75
+ this.eat("{");
76
+ if (this.peek("}")) {
77
+ this.eat("}");
78
+ value = map([]);
79
+ } else {
80
+ frames.push({
81
+ kind: "map",
82
+ pairs: [],
83
+ key: this.mapKey()
84
+ });
85
+ continue;
86
+ }
87
+ } else value = this.atom();
88
+ }
89
+ const parent = frames.at(-1);
90
+ if (!parent) return value;
91
+ if (parent.kind === "function") {
92
+ if (value.kind !== "map") this.fail("Expected Function Value captures");
93
+ this.eat(">");
94
+ frames.pop();
95
+ value = this.functionValue(parent.start);
96
+ continue;
97
+ }
98
+ if (parent.kind === "list") parent.values.push(value);
99
+ else parent.pairs.push([parent.key, value]);
100
+ value = void 0;
101
+ if (this.peek(", ")) {
102
+ this.eat(", ");
103
+ if (parent.kind === "map") parent.key = this.mapKey();
104
+ } else {
105
+ this.eat(parent.kind === "list" ? "]" : "}");
106
+ frames.pop();
107
+ value = parent.kind === "list" ? listValues(parent.values) : map(parent.pairs);
108
+ }
109
+ }
110
+ }
111
+ functionValue(start) {
112
+ const display = this.source.slice(start, this.i);
113
+ const value = this.resolveFunction?.(display);
114
+ if (value?.kind !== "function" || value.toString() !== display) return this.fail(`No Host-held Function Value ${display}`);
115
+ return value;
116
+ }
117
+ mapKey() {
118
+ const key = this.peek("\"") ? this.textPieces() : this.match(/[A-Z_a-z]\w*/y);
119
+ if (key === void 0) this.fail("Expected map key");
120
+ this.eat(": ");
121
+ return key;
122
+ }
123
+ atom() {
124
+ if (this.match(/nothing(?!\w)/y)) return nothing;
125
+ const b = this.match(/(?:true|false)(?!\w)/y);
126
+ if (b) return bool(b === "true");
127
+ if (this.peek("\"") || /^(?:quote|newline|tab|fromCodePoint\()/.test(this.source.slice(this.i))) return text(this.textPieces());
128
+ if (this.peek("<<")) return this.bytes();
129
+ if (this.peek("<object ")) {
130
+ this.eat("<object ");
131
+ const kind = this.match(/[A-Z_a-z][\w-]*/y) ?? this.fail("Expected a kind");
132
+ this.eat(" ");
133
+ const id = this.textPieces();
134
+ this.eat(">");
135
+ return resolved(this.resolve?.(kind, id)) ?? this.fail(`No Host Object ${kind} ${id}`);
136
+ }
137
+ const date = this.match(/\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z?)?(?![\w.:-])/y);
138
+ if (date !== void 0) return dateValue(date, this.fail.bind(this));
139
+ const start = this.i;
140
+ const from = this.rangeEnd();
141
+ if (from === void 0) return this.fail("Unsupported or malformed display value");
142
+ if (!this.peek("..")) return from;
143
+ this.eat("..");
144
+ const to = this.rangeEnd();
145
+ if (to === void 0) return this.fail("Expected the end of a range");
146
+ const value = range(from, to);
147
+ if (value.toString() !== this.source.slice(start, this.i)) this.fail("Expected a canonical display range");
148
+ return value;
149
+ }
150
+ bytes() {
151
+ this.eat("<<");
152
+ const out = [];
153
+ while (!this.peek(">>")) {
154
+ if (out.length) this.eat(", ");
155
+ const byte = this.match(/0x[\dA-F]{2}/y);
156
+ if (byte === void 0) this.fail("Expected a byte");
157
+ out.push(Number.parseInt(byte.slice(2), 16));
158
+ }
159
+ this.eat(">>");
160
+ return bytesOf(Uint8Array.from(out));
161
+ }
162
+ rangeEnd() {
163
+ const start = this.i;
164
+ const number = this.match(/-?\d+(?:\.\d+)?/y);
165
+ if (number === void 0) return;
166
+ const value = dec(number);
167
+ if (value.toString() !== number) this.fail("Expected canonical display number");
168
+ const unit = this.match(/ [\d*/A-Z^a-z]+(?!=)/y);
169
+ if (unit === void 0) return value;
170
+ const q = quantity(value, unit.slice(1));
171
+ if (q.toString() !== this.source.slice(start, this.i)) this.fail("Expected a Quantity in normal form");
172
+ return q;
173
+ }
174
+ textPieces() {
175
+ const pieces = [];
176
+ for (;;) {
177
+ if (this.peek("\"")) {
178
+ this.i++;
179
+ const end = this.source.indexOf("\"", this.i);
180
+ if (end < 0) this.fail("Unterminated display text");
181
+ const run = this.source.slice(this.i, end);
182
+ if (Array.from(run).some((ch) => hiddenCodePoint(ch.codePointAt(0)))) this.fail("Hidden scalar in quoted display text");
183
+ pieces.push(run);
184
+ this.i = end + 1;
185
+ } else {
186
+ const constant = this.match(/(?:quote|newline|tab)(?![\w(])/y);
187
+ if (constant) pieces.push(constant === "quote" ? "\"" : constant === "newline" ? "\n" : " ");
188
+ else {
189
+ const cp = this.match(/fromCodePoint\(\d+\)/y);
190
+ if (!cp) this.fail("Expected text piece");
191
+ const n = Number(cp.slice(14, -1));
192
+ if (!Number.isInteger(n) || n < 0 || n > 1114111 || n >= 55296 && n <= 57343) this.fail("Not a Unicode scalar");
193
+ pieces.push(String.fromCodePoint(n));
194
+ }
195
+ }
196
+ if (!this.peek(" & ")) break;
197
+ this.eat(" & ");
198
+ }
199
+ return pieces.join("");
200
+ }
201
+ };
202
+ const readDisplay = (source, resolve, resolveFunction) => {
203
+ const reader = new DisplayReader(source, resolve, resolveFunction);
204
+ const value = reader.value();
205
+ reader.done();
206
+ return value;
207
+ };
208
+ var JsonNumber = class {
209
+ source;
210
+ kind = "number";
211
+ constructor(source) {
212
+ this.source = source;
213
+ }
214
+ };
215
+ var JsonObject = class {
216
+ pairs;
217
+ kind = "object";
218
+ constructor(pairs) {
219
+ this.pairs = pairs;
220
+ }
221
+ };
222
+ const plainRun = /[^\u0000-\u001f"\\]+/y;
223
+ var JsonReader = class extends Reader {
224
+ whitespace() {
225
+ this.match(/[\u0009\u000a\u000d ]*/y);
226
+ }
227
+ string() {
228
+ this.eat("\"");
229
+ let result = "";
230
+ while (this.i < this.source.length) {
231
+ result += this.match(plainRun) ?? "";
232
+ if (this.i >= this.source.length) break;
233
+ const ch = this.source[this.i++];
234
+ if (ch === "\"") {
235
+ assertScalarText(result);
236
+ return result;
237
+ }
238
+ if (ch.charCodeAt(0) < 32) this.fail("Control in JSON string");
239
+ if (ch !== "\\") {
240
+ result += ch;
241
+ continue;
242
+ }
243
+ const escape = this.source[this.i++];
244
+ const simple = {
245
+ "\"": "\"",
246
+ "\\": "\\",
247
+ "/": "/",
248
+ b: "\b",
249
+ f: "\f",
250
+ n: "\n",
251
+ r: "\r",
252
+ t: " "
253
+ };
254
+ if (Object.hasOwn(simple, escape)) result += simple[escape];
255
+ else if (escape === "u") {
256
+ const digits = this.match(/[\dA-Fa-f]{4}/y);
257
+ if (!digits) this.fail("Invalid JSON Unicode escape");
258
+ result += String.fromCharCode(Number.parseInt(digits, 16));
259
+ } else this.fail("Invalid JSON escape");
260
+ }
261
+ return this.fail("Unterminated JSON string");
262
+ }
263
+ value() {
264
+ const frames = [];
265
+ let value = null, ready = false;
266
+ const mapKey = (frame) => {
267
+ this.whitespace();
268
+ frame.key = this.string();
269
+ if (frame.keys.has(frame.key)) this.fail("Duplicate JSON key");
270
+ frame.keys.add(frame.key);
271
+ this.whitespace();
272
+ this.eat(":");
273
+ };
274
+ for (;;) {
275
+ if (!ready) {
276
+ this.whitespace();
277
+ if (this.peek("[")) {
278
+ this.eat("[");
279
+ this.whitespace();
280
+ if (this.peek("]")) {
281
+ this.eat("]");
282
+ value = [];
283
+ } else {
284
+ frames.push({
285
+ kind: "list",
286
+ values: []
287
+ });
288
+ continue;
289
+ }
290
+ } else if (this.peek("{")) {
291
+ this.eat("{");
292
+ this.whitespace();
293
+ if (this.peek("}")) {
294
+ this.eat("}");
295
+ value = new JsonObject([]);
296
+ } else {
297
+ const frame = {
298
+ kind: "map",
299
+ pairs: [],
300
+ keys: /* @__PURE__ */ new Set(),
301
+ key: ""
302
+ };
303
+ mapKey(frame);
304
+ frames.push(frame);
305
+ continue;
306
+ }
307
+ } else value = this.atom();
308
+ }
309
+ const parent = frames.at(-1);
310
+ if (!parent) return value;
311
+ if (parent.kind === "list") parent.values.push(value);
312
+ else parent.pairs.push([parent.key, value]);
313
+ this.whitespace();
314
+ if (this.peek(",")) {
315
+ this.eat(",");
316
+ ready = false;
317
+ if (parent.kind === "map") mapKey(parent);
318
+ } else {
319
+ this.eat(parent.kind === "list" ? "]" : "}");
320
+ frames.pop();
321
+ value = parent.kind === "list" ? parent.values : new JsonObject(parent.pairs);
322
+ ready = true;
323
+ }
324
+ }
325
+ }
326
+ atom() {
327
+ if (this.peek("\"")) return this.string();
328
+ if (this.match(/null/y)) return null;
329
+ const b = this.match(/true|false/y);
330
+ if (b) return b === "true";
331
+ const n = this.match(/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[Ee][+-]?\d+)?/y);
332
+ if (n) return new JsonNumber(n);
333
+ return this.fail("Expected JSON value");
334
+ }
335
+ };
336
+ const fromJson = (value, resolve, functionResolve, tagDecode) => {
337
+ let result = nothing;
338
+ const tasks = [];
339
+ const enqueue = (node, assign) => {
340
+ tasks.push(() => {
341
+ if (node === null) {
342
+ assign(nothing);
343
+ return;
344
+ }
345
+ if (typeof node === "boolean") {
346
+ assign(bool(node));
347
+ return;
348
+ }
349
+ if (typeof node === "string") {
350
+ assign(text(node));
351
+ return;
352
+ }
353
+ if (Array.isArray(node)) {
354
+ const values = new Array(node.length);
355
+ tasks.push(() => assign(listValues(values)));
356
+ for (let i = node.length - 1; i >= 0; i--) enqueue(node[i], (v) => {
357
+ values[i] = v;
358
+ });
359
+ return;
360
+ }
361
+ if (node.kind === "number") {
362
+ const v = dec(node.source);
363
+ if (v.toString() !== node.source || node.source.includes(".") || abs(v.asDecimal().toBigInt()) >= 2n ** 53n) invalidValue("Non-canonical Value Encoding number");
364
+ assign(v);
365
+ return;
366
+ }
367
+ let pairs = node.pairs;
368
+ if (pairs.some(([key]) => key.startsWith("$"))) {
369
+ if (pairs.length !== 1) invalidValue("Value Encoding tag must be the only key");
370
+ const [tag, data] = pairs[0];
371
+ if (tag === "$sessionFunction" && typeof data === "string" && functionResolve) {
372
+ assign(functionResolve(data));
373
+ return;
374
+ }
375
+ const adapted = tag === "$function" || tag === "$pattern" ? tagDecode?.(tag, data) : void 0;
376
+ if (adapted) {
377
+ assign(adapted);
378
+ return;
379
+ }
380
+ if (tag === "$dec" && typeof data === "string") {
381
+ const v = dec(data);
382
+ if (v.toString() !== data || !data.includes(".") && abs(v.asDecimal().toBigInt()) < 2n ** 53n) invalidValue("Non-canonical $dec");
383
+ assign(v);
384
+ return;
385
+ }
386
+ if (tag === "$quantity" && Array.isArray(data) && data.length === 2 && typeof data[0] === "string" && typeof data[1] === "string") {
387
+ const n = dec(data[0]);
388
+ const unit = data[1];
389
+ if (n.toString() !== data[0]) invalidValue("Non-canonical $quantity number");
390
+ const q = quantity(n, unit);
391
+ if (q.kind !== "quantity" || encodedUnit(q) !== unit) invalidValue("A $quantity Unit not in normal form");
392
+ assign(q);
393
+ return;
394
+ }
395
+ if ((tag === "$instant" || tag === "$date") && typeof data === "string") {
396
+ const v = dateValue(data, invalidValue);
397
+ if (v.kind !== (tag === "$instant" ? "instant" : "civil date")) invalidValue(`Malformed ${tag}`);
398
+ assign(v);
399
+ return;
400
+ }
401
+ if (tag === "$bytes" && typeof data === "string") {
402
+ const b = fromBase64(data);
403
+ if (!b) invalidValue("A $bytes that is not canonical padded Base64");
404
+ assign(bytesOf(b));
405
+ return;
406
+ }
407
+ if (tag === "$object" && Array.isArray(data) && data.length === 2 && typeof data[0] === "string" && typeof data[1] === "string") {
408
+ const v = resolved(resolve?.(data[0], data[1]));
409
+ if (!v) invalidValue(`No Host Object ${data[0]} ${data[1]}`);
410
+ assign(v);
411
+ return;
412
+ }
413
+ if (tag === "$range" && Array.isArray(data) && data.length === 2) {
414
+ const ends = [nothing, nothing];
415
+ tasks.push(() => assign(range(ends[0], ends[1])));
416
+ enqueue(data[1], (v) => {
417
+ ends[1] = v;
418
+ });
419
+ enqueue(data[0], (v) => {
420
+ ends[0] = v;
421
+ });
422
+ return;
423
+ }
424
+ if (tag !== "$map" || !Array.isArray(data)) invalidValue(`Unsupported or malformed Value Encoding tag ${tag}`);
425
+ pairs = data.map((pair) => {
426
+ if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string") invalidValue("Malformed $map entry");
427
+ return [pair[0], pair[1]];
428
+ });
429
+ if (!pairs.some(([key]) => key.startsWith("$"))) invalidValue("A $map without a $ key");
430
+ }
431
+ const entries = pairs.map(([key]) => [key, nothing]);
432
+ tasks.push(() => assign(map(entries)));
433
+ for (let i = pairs.length - 1; i >= 0; i--) enqueue(pairs[i][1], (v) => {
434
+ entries[i][1] = v;
435
+ });
436
+ });
437
+ };
438
+ enqueue(value, (v) => {
439
+ result = v;
440
+ });
441
+ while (tasks.length) tasks.pop()();
442
+ return result;
443
+ };
444
+ const dateValue = (s, fail) => {
445
+ const v = s.endsWith("Z") ? instant(parseInstant(s)) : civilDate(s);
446
+ if (v.toString() !== s) fail("Expected a date in its display form");
447
+ return v;
448
+ };
449
+ const encodedUnit = (q) => q.asQuantity().unit;
450
+ const abs = (n) => n < 0n ? -n : n;
451
+ const decodeValue = (source, resolve, functionResolve) => {
452
+ const reader = new JsonReader(source);
453
+ const value = reader.value();
454
+ reader.whitespace();
455
+ reader.done();
456
+ return fromJson(value, resolve, functionResolve);
457
+ };
458
+ /**
459
+ * The members of one JSON object, each value in the Value Encoding, as a
460
+ * Store's contents are written to a file (chapter 12, `:store`).
461
+ */
462
+ const decodeValueMembers = (source, resolve) => {
463
+ const reader = new JsonReader(source);
464
+ const value = reader.value();
465
+ reader.whitespace();
466
+ reader.done();
467
+ if (value === null || typeof value !== "object" || Array.isArray(value) || value.kind !== "object") return invalidValue("Expected one JSON object");
468
+ return value.pairs.map(([key, member]) => [key, fromJson(member, resolve)]);
469
+ };
470
+ /** Parse raw, ordered JSON, rejecting duplicate keys before tag interpretation. */
471
+ const readOrderedJSON = (source) => {
472
+ const reader = new JsonReader(source);
473
+ const value = reader.value();
474
+ reader.whitespace();
475
+ reader.done();
476
+ return value;
477
+ };
478
+ //#endregion
479
+ export { readOrderedJSON as a, readDisplay as i, decodeValueMembers as n, fromJson as r, decodeValue as t };
@@ -0,0 +1,57 @@
1
+ import { Rt as Grant, Tt as ObjectKind, Xt as Shape, at as Value, j as Library } from "./debug-D8Z_u244.js";
2
+ //#region src/encoding.d.ts
3
+ /**
4
+ * A Message Layer adapter's own spelling of a Function Value or a Text
5
+ * Pattern, which the Value Encoding doesn't hold.
6
+ */
7
+ type AdapterEncoder = (v: Value) => string;
8
+ declare const encodeValue: (value: Value, adapter?: AdapterEncoder) => string;
9
+ //#endregion
10
+ //#region src/json.d.ts
11
+ /** Read exact decimal digits, NFC strings and insertion-ordered maps. */
12
+ declare const decodeJson: (source: string) => Value;
13
+ /** Compact JSON, with canonical numbers and chapter 7's string escapes. */
14
+ declare const encodeJson: (value: Value) => string;
15
+ //#endregion
16
+ //#region src/manifest.d.ts
17
+ type MessageDecl = {
18
+ args?: readonly Shape[];
19
+ description?: string;
20
+ /** NorthTalk source, each sending this message. */
21
+ examples?: readonly string[];
22
+ name: string;
23
+ receivers?: readonly ObjectKind[];
24
+ };
25
+ type ManifestSpec = {
26
+ grants: Readonly<Record<string, Grant<any>>>;
27
+ kind: string;
28
+ libraries?: readonly Library[];
29
+ messages?: readonly MessageDecl[];
30
+ objectKinds?: readonly ObjectKind[];
31
+ objects?: Readonly<Record<string, ObjectKind>>;
32
+ version: string;
33
+ };
34
+ /** Chapter 9's deterministic JSON file, ending in LF; never calls the Host. */
35
+ declare const exportManifest: (m: ManifestSpec) => string;
36
+ //#endregion
37
+ //#region src/readers.d.ts
38
+ /** Finds the Host Object a reader names by its kind and id, or none. */
39
+ type ObjectResolver = (kind: string, id: string) => {
40
+ readonly value: Value;
41
+ } | Value | null | undefined;
42
+ type FunctionResolver = (display: string) => Value | undefined;
43
+ declare const readDisplay: (source: string, resolve?: ObjectResolver, resolveFunction?: FunctionResolver) => Value;
44
+ type Json = null | boolean | string | JsonNumber | Json[] | JsonObject;
45
+ declare class JsonNumber {
46
+ readonly source: string;
47
+ readonly kind = "number";
48
+ constructor(source: string);
49
+ }
50
+ declare class JsonObject {
51
+ readonly pairs: [string, Json][];
52
+ readonly kind = "object";
53
+ constructor(pairs: [string, Json][]);
54
+ }
55
+ declare const decodeValue: (source: string, resolve?: ObjectResolver, functionResolve?: (handle: string) => Value) => Value;
56
+ //#endregion
57
+ export { ManifestSpec as a, decodeJson as c, readDisplay as i, encodeJson as l, Json as n, MessageDecl as o, decodeValue as r, exportManifest as s, FunctionResolver as t, encodeValue as u };