@northtalk/ts 0.0.0-stage → 0.2.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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/UNICODE-LICENSE.txt +39 -0
  4. package/base64-DORMd3Hv.js +6621 -0
  5. package/binary-value-CEmh60GC.d.ts +15 -0
  6. package/capabilities-CH0FkRMq.js +1301 -0
  7. package/checker-Dc1jl2WH.js +6657 -0
  8. package/core-DptnvQT9.d.ts +14 -0
  9. package/debug-CQBxKnJB.d.ts +3065 -0
  10. package/debug.d.ts +3 -0
  11. package/debug.js +2 -0
  12. package/driver.d.ts +41 -0
  13. package/driver.js +152 -0
  14. package/encoding-nlrpj-Pb.js +99 -0
  15. package/engine-BGaJ9dAk.js +326 -0
  16. package/engine-vbYInVYF.d.ts +86 -0
  17. package/errors-LYJZ_c8h.js +3735 -0
  18. package/group-B742gg4T.js +10170 -0
  19. package/http-capability-CSTkw1Yt.js +728 -0
  20. package/http.d.ts +59 -0
  21. package/http.js +465 -0
  22. package/index.d.ts +651 -0
  23. package/index.js +44 -0
  24. package/manifest-BscyH_rW.d.ts +70 -0
  25. package/manifest-DjsxDSuB.js +129 -0
  26. package/message-layer.d.ts +12 -0
  27. package/message-layer.js +4 -0
  28. package/notify.d.ts +3 -0
  29. package/notify.js +2 -0
  30. package/objects-DJ3QtCCs.d.ts +640 -0
  31. package/objects-Db7IB5vQ.js +91 -0
  32. package/operation-promises-EgZXG5N_.js +23 -0
  33. package/package.json +70 -4
  34. package/readers-BFPuosPk.d.ts +25 -0
  35. package/readers-CjJHKHvH.js +482 -0
  36. package/request-pump-binary-DdY3X-yl.js +2246 -0
  37. package/router--71qvxtY.js +343 -0
  38. package/router-Zhrw5l__.d.ts +55 -0
  39. package/session.d.ts +9 -0
  40. package/session.js +3510 -0
  41. package/setup.d.ts +3 -0
  42. package/setup.js +193 -0
  43. package/sha256-B_kyYw3Z.js +124 -0
  44. package/sqlite.d.ts +74 -0
  45. package/sqlite.js +529 -0
  46. package/store-capability-OZp4hXmj.js +390 -0
  47. package/store-hJrRULMx.js +60 -0
  48. package/store.d.ts +21 -0
  49. package/store.js +4 -0
  50. package/user-capability-BK4Asg7D.js +276 -0
  51. package/wasm.d.ts +243 -0
  52. package/wasm.js +1737 -0
@@ -0,0 +1,91 @@
1
+
2
+ import { I as objectValue, t as HostError } from "./errors-LYJZ_c8h.js";
3
+ //#region src/objects.ts
4
+ const elementCost = (cost, name) => {
5
+ const c = cost;
6
+ if (!c || typeof c !== "object" || !Number.isSafeInteger(c.fuel) || c.fuel < 0 || c.alloc !== void 0 && (!Number.isSafeInteger(c.alloc) || c.alloc < 0)) throw new HostError("invalid value", `Invalid or missing elements ${name}`);
7
+ return Object.freeze({
8
+ fuel: c.fuel,
9
+ ...c.alloc === void 0 ? {} : { alloc: c.alloc }
10
+ });
11
+ };
12
+ const elementShape = (shape) => {
13
+ const s = shape;
14
+ const kinds = s?.k === "object" ? [s.kind] : s?.k === "oneOf" && s.of.length && s.of.every((o) => o.k === "object") ? s.of.map((o) => o.kind) : null;
15
+ if (!kinds || new Set(kinds).size !== kinds.length) throw new HostError("invalid value", "An Object Collection Shape must be an Object Shape or a choice of distinct ones");
16
+ return s;
17
+ };
18
+ const objectElements = (e) => {
19
+ if (e === void 0) return null;
20
+ if (!e || typeof e.count !== "function" || typeof e.at !== "function" || typeof e.find !== "function") throw new HostError("invalid value", "An Object Collection needs count, at and find");
21
+ return Object.freeze({
22
+ shape: elementShape(e.shape),
23
+ count: e.count,
24
+ at: e.at,
25
+ find: e.find,
26
+ countCost: elementCost(e.countCost, "countCost"),
27
+ atCost: elementCost(e.atCost, "atCost"),
28
+ findCost: elementCost(e.findCost, "findCost")
29
+ });
30
+ };
31
+ const kinds = /* @__PURE__ */ new Map();
32
+ /** A restored handle uses the process's definition of its saved kind. */
33
+ const objectKind = (name) => kinds.get(name);
34
+ /** Define an Object Kind, once per process. */
35
+ const defineObjectKind = (k) => {
36
+ const kind = Object.freeze({
37
+ name: k.name,
38
+ parentKinds: Object.freeze([...k.parentKinds ?? []]),
39
+ props: new Map(Object.entries(k.props)),
40
+ elements: objectElements(k.elements)
41
+ });
42
+ kinds.set(kind.name, kind);
43
+ return kind;
44
+ };
45
+ /** A new handle and its state, for the Group that makes it. */
46
+ const makeObject = (kind, id, native) => {
47
+ const state = {};
48
+ const handle = Object.freeze({
49
+ id,
50
+ kind,
51
+ native,
52
+ value: objectValue({
53
+ kind: kind.name,
54
+ id,
55
+ handle: state
56
+ })
57
+ });
58
+ Object.assign(state, {
59
+ disposed: false,
60
+ handle,
61
+ owner: null,
62
+ parent: null
63
+ });
64
+ return state;
65
+ };
66
+ /** The Group's state of an object value. */
67
+ const stateOf = (v) => v.asObjectRef()?.handle;
68
+ /** Rebind native state while preserving every saved reference to this object. */
69
+ const rebindObject = (state, native) => {
70
+ const { kind, id } = state.handle;
71
+ state.handle = Object.freeze({
72
+ kind,
73
+ id,
74
+ native,
75
+ value: objectValue({
76
+ kind: kind.name,
77
+ id,
78
+ handle: state
79
+ })
80
+ });
81
+ };
82
+ /** Loading checks declarations without retaining Host callbacks in checked code. */
83
+ const propertyChecks = (objects, owner) => {
84
+ const props = (kind) => Object.fromEntries([...kind.props].map(([name, prop]) => [name, !!prop.set]));
85
+ return {
86
+ objectProperties: Object.fromEntries(Object.entries(objects).map(([name, object]) => [name, props(object.kind)])),
87
+ ownerProperties: owner ? props(owner.kind) : void 0
88
+ };
89
+ };
90
+ //#endregion
91
+ export { rebindObject as a, propertyChecks as i, makeObject as n, stateOf as o, objectKind as r, defineObjectKind as t };
@@ -0,0 +1,23 @@
1
+
2
+ //#region src/operation-promises.ts
3
+ const pending = /* @__PURE__ */ new WeakMap();
4
+ /** Tracks forwarding too, so the final answer/failure is queued before completion. */
5
+ const trackOperation = (group, result) => {
6
+ let operations = pending.get(group);
7
+ if (!operations) {
8
+ operations = /* @__PURE__ */ new Set();
9
+ pending.set(group, operations);
10
+ }
11
+ const done = () => {
12
+ operations.delete(completed);
13
+ };
14
+ const completed = result.then(done, done);
15
+ operations.add(completed);
16
+ };
17
+ /** Includes abandoned calls whose Host work is still finishing. */
18
+ const waitForOperations = async (group) => {
19
+ const operations = pending.get(group);
20
+ while (operations?.size) await Promise.all(operations);
21
+ };
22
+ //#endregion
23
+ export { waitForOperations as n, trackOperation as t };
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@northtalk/ts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "NorthTalk, a readable scripting language for embedding: the TS Core, its Session Host and Standard Capabilities.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "homepage": "https://github.com/odogono/odgn-talk/tree/main/impl/ts#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/odogono/odgn-talk.git",
11
+ "directory": "impl/ts"
12
+ },
13
+ "bugs": "https://github.com/odogono/odgn-talk/issues",
14
+ "keywords": [
15
+ "northtalk",
16
+ "scripting",
17
+ "language",
18
+ "interpreter",
19
+ "embedding"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": {
27
+ "types": "./index.d.ts",
28
+ "default": "./index.js"
29
+ },
30
+ "./message-layer": {
31
+ "types": "./message-layer.d.ts",
32
+ "default": "./message-layer.js"
33
+ },
34
+ "./session": {
35
+ "types": "./session.d.ts",
36
+ "default": "./session.js"
37
+ },
38
+ "./store": {
39
+ "types": "./store.d.ts",
40
+ "default": "./store.js"
41
+ },
42
+ "./notify": {
43
+ "types": "./notify.d.ts",
44
+ "default": "./notify.js"
45
+ },
46
+ "./sqlite": {
47
+ "types": "./sqlite.d.ts",
48
+ "default": "./sqlite.js"
49
+ },
50
+ "./http": {
51
+ "types": "./http.d.ts",
52
+ "default": "./http.js"
53
+ },
54
+ "./setup": {
55
+ "types": "./setup.d.ts",
56
+ "default": "./setup.js"
57
+ },
58
+ "./debug": {
59
+ "types": "./debug.d.ts",
60
+ "default": "./debug.js"
61
+ },
62
+ "./driver": {
63
+ "types": "./driver.d.ts",
64
+ "default": "./driver.js"
65
+ },
66
+ "./wasm": {
67
+ "types": "./wasm.d.ts",
68
+ "default": "./wasm.js"
69
+ },
70
+ "./package.json": "./package.json"
71
+ }
72
+ }
@@ -0,0 +1,25 @@
1
+
2
+ import { q as Value } from "./debug-CQBxKnJB.js";
3
+ //#region src/readers.d.ts
4
+ /** Finds the Host Object a reader names by its kind and id, or none. */
5
+ type ObjectResolver = (kind: string, id: string) => {
6
+ readonly value: Value;
7
+ } | Value | null | undefined;
8
+ type FunctionResolver = (display: string) => Value | undefined;
9
+ declare const readDisplay: (source: string, resolve?: ObjectResolver, resolveFunction?: FunctionResolver) => Value;
10
+ type Json = null | boolean | string | JsonNumber | Json[] | JsonObject;
11
+ declare class JsonNumber {
12
+ readonly source: string;
13
+ readonly kind = "number";
14
+ constructor(source: string);
15
+ }
16
+ declare class JsonObject {
17
+ readonly pairs: [string, Json][];
18
+ readonly kind = "object";
19
+ constructor(pairs: [string, Json][]);
20
+ }
21
+ declare const decodeValue: (source: string, resolve?: ObjectResolver, functionResolve?: (handle: string) => Value) => Value;
22
+ /** Parse raw, ordered JSON, rejecting duplicate keys before tag interpretation. */
23
+ declare const readOrderedJSON: (source: string) => Json;
24
+ //#endregion
25
+ export { decodeValue as a, JsonObject as i, Json as n, readDisplay as o, JsonNumber as r, readOrderedJSON as s, FunctionResolver as t };
@@ -0,0 +1,482 @@
1
+
2
+ import { B as range, C as hiddenCodePoint, K as text, M as map, P as nothing, Qt as parseInstant, R as quantity, _ as dec, f as bytesOf, k as listValues, l as Value, m as civilDate, o as invalidValue, u as bool, ut as assertScalarText, w as instant } from "./errors-LYJZ_c8h.js";
3
+ import { t as fromBase64 } from "./base64-DORMd3Hv.js";
4
+ //#region src/readers.ts
5
+ var Reader = class {
6
+ source;
7
+ i = 0;
8
+ constructor(source) {
9
+ this.source = source;
10
+ assertScalarText(source);
11
+ }
12
+ fail(what) {
13
+ return invalidValue(`${what} at column ${this.i + 1}`);
14
+ }
15
+ peek(s) {
16
+ return this.source.startsWith(s, this.i);
17
+ }
18
+ eat(s) {
19
+ if (!this.peek(s)) this.fail(`Expected ${s}`);
20
+ this.i += s.length;
21
+ }
22
+ match(re) {
23
+ re.lastIndex = this.i;
24
+ const result = re.exec(this.source);
25
+ if (!result || result.index !== this.i) return;
26
+ this.i += result[0].length;
27
+ return result[0];
28
+ }
29
+ done() {
30
+ if (this.i !== this.source.length) this.fail("Unexpected trailing input");
31
+ }
32
+ };
33
+ const resolved = (r) => r ? Value.isValue(r) ? r : r.value : void 0;
34
+ var DisplayReader = class extends Reader {
35
+ resolve;
36
+ resolveFunction;
37
+ constructor(source, resolve, resolveFunction) {
38
+ super(source);
39
+ this.resolve = resolve;
40
+ this.resolveFunction = resolveFunction;
41
+ }
42
+ value() {
43
+ const frames = [];
44
+ let value;
45
+ for (;;) {
46
+ if (!value) {
47
+ if (this.peek("<function ")) {
48
+ const start = this.i;
49
+ this.eat("<function ");
50
+ 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");
51
+ if (this.peek(">")) {
52
+ this.eat(">");
53
+ value = this.functionValue(start);
54
+ } else {
55
+ this.eat(" ");
56
+ if (!this.peek("{")) this.fail("Expected Function Value captures");
57
+ frames.push({
58
+ kind: "function",
59
+ start
60
+ });
61
+ continue;
62
+ }
63
+ } else if (this.peek("[")) {
64
+ this.eat("[");
65
+ if (this.peek("]")) {
66
+ this.eat("]");
67
+ value = listValues([]);
68
+ } else {
69
+ frames.push({
70
+ kind: "list",
71
+ values: []
72
+ });
73
+ continue;
74
+ }
75
+ } else if (this.peek("{")) {
76
+ this.eat("{");
77
+ if (this.peek("}")) {
78
+ this.eat("}");
79
+ value = map([]);
80
+ } else {
81
+ frames.push({
82
+ kind: "map",
83
+ pairs: [],
84
+ key: this.mapKey()
85
+ });
86
+ continue;
87
+ }
88
+ } else value = this.atom();
89
+ }
90
+ const parent = frames.at(-1);
91
+ if (!parent) return value;
92
+ if (parent.kind === "function") {
93
+ if (value.kind !== "map") this.fail("Expected Function Value captures");
94
+ this.eat(">");
95
+ frames.pop();
96
+ value = this.functionValue(parent.start);
97
+ continue;
98
+ }
99
+ if (parent.kind === "list") parent.values.push(value);
100
+ else parent.pairs.push([parent.key, value]);
101
+ value = void 0;
102
+ if (this.peek(", ")) {
103
+ this.eat(", ");
104
+ if (parent.kind === "map") parent.key = this.mapKey();
105
+ } else {
106
+ this.eat(parent.kind === "list" ? "]" : "}");
107
+ frames.pop();
108
+ value = parent.kind === "list" ? listValues(parent.values) : map(parent.pairs);
109
+ }
110
+ }
111
+ }
112
+ functionValue(start) {
113
+ const display = this.source.slice(start, this.i);
114
+ const value = this.resolveFunction?.(display);
115
+ if (value?.kind !== "function" || value.toString() !== display) return this.fail(`No Host-held Function Value ${display}`);
116
+ return value;
117
+ }
118
+ mapKey() {
119
+ const key = this.peek("\"") ? this.textPieces() : this.match(/[A-Z_a-z]\w*/y);
120
+ if (key === void 0) this.fail("Expected map key");
121
+ this.eat(": ");
122
+ return key;
123
+ }
124
+ atom() {
125
+ if (this.match(/nothing(?!\w)/y)) return nothing;
126
+ const b = this.match(/(?:true|false)(?!\w)/y);
127
+ if (b) return bool(b === "true");
128
+ if (this.peek("\"") || /^(?:quote|newline|tab|fromCodePoint\()/.test(this.source.slice(this.i))) return text(this.textPieces());
129
+ if (this.peek("<<")) return this.bytes();
130
+ if (this.peek("<object ")) {
131
+ this.eat("<object ");
132
+ const kind = this.match(/[A-Z_a-z][\w-]*/y) ?? this.fail("Expected a kind");
133
+ this.eat(" ");
134
+ const id = this.textPieces();
135
+ this.eat(">");
136
+ return resolved(this.resolve?.(kind, id)) ?? this.fail(`No Host Object ${kind} ${id}`);
137
+ }
138
+ const date = this.match(/\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z?)?(?![\w.:-])/y);
139
+ if (date !== void 0) return dateValue(date, this.fail.bind(this));
140
+ const start = this.i;
141
+ const from = this.rangeEnd();
142
+ if (from === void 0) return this.fail("Unsupported or malformed display value");
143
+ if (!this.peek("..")) return from;
144
+ this.eat("..");
145
+ const to = this.rangeEnd();
146
+ if (to === void 0) return this.fail("Expected the end of a range");
147
+ const value = range(from, to);
148
+ if (value.toString() !== this.source.slice(start, this.i)) this.fail("Expected a canonical display range");
149
+ return value;
150
+ }
151
+ bytes() {
152
+ this.eat("<<");
153
+ const out = [];
154
+ while (!this.peek(">>")) {
155
+ if (out.length) this.eat(", ");
156
+ const byte = this.match(/0x[\dA-F]{2}/y);
157
+ if (byte === void 0) this.fail("Expected a byte");
158
+ out.push(Number.parseInt(byte.slice(2), 16));
159
+ }
160
+ this.eat(">>");
161
+ return bytesOf(Uint8Array.from(out));
162
+ }
163
+ rangeEnd() {
164
+ const start = this.i;
165
+ const number = this.match(/-?\d+(?:\.\d+)?/y);
166
+ if (number === void 0) return;
167
+ const value = dec(number);
168
+ if (value.toString() !== number) this.fail("Expected canonical display number");
169
+ const unit = this.match(/ [\d*/A-Z^a-z]+(?!=)/y);
170
+ if (unit === void 0) return value;
171
+ const q = quantity(value, unit.slice(1));
172
+ if (q.toString() !== this.source.slice(start, this.i)) this.fail("Expected a Quantity in normal form");
173
+ return q;
174
+ }
175
+ textPieces() {
176
+ const pieces = [];
177
+ for (;;) {
178
+ if (this.peek("\"")) {
179
+ this.i++;
180
+ const end = this.source.indexOf("\"", this.i);
181
+ if (end < 0) this.fail("Unterminated display text");
182
+ const run = this.source.slice(this.i, end);
183
+ if (Array.from(run).some((ch) => hiddenCodePoint(ch.codePointAt(0)))) this.fail("Hidden scalar in quoted display text");
184
+ pieces.push(run);
185
+ this.i = end + 1;
186
+ } else {
187
+ const constant = this.match(/(?:quote|newline|tab)(?![\w(])/y);
188
+ if (constant) pieces.push(constant === "quote" ? "\"" : constant === "newline" ? "\n" : " ");
189
+ else {
190
+ const cp = this.match(/fromCodePoint\(\d+\)/y);
191
+ if (!cp) this.fail("Expected text piece");
192
+ const n = Number(cp.slice(14, -1));
193
+ if (!Number.isInteger(n) || n < 0 || n > 1114111 || n >= 55296 && n <= 57343) this.fail("Not a Unicode scalar");
194
+ pieces.push(String.fromCodePoint(n));
195
+ }
196
+ }
197
+ if (!this.peek(" & ")) break;
198
+ this.eat(" & ");
199
+ }
200
+ return pieces.join("");
201
+ }
202
+ };
203
+ const readDisplay = (source, resolve, resolveFunction) => {
204
+ const reader = new DisplayReader(source, resolve, resolveFunction);
205
+ const value = reader.value();
206
+ reader.done();
207
+ return value;
208
+ };
209
+ var JsonNumber = class {
210
+ source;
211
+ kind = "number";
212
+ constructor(source) {
213
+ this.source = source;
214
+ }
215
+ };
216
+ var JsonObject = class {
217
+ pairs;
218
+ kind = "object";
219
+ constructor(pairs) {
220
+ this.pairs = pairs;
221
+ }
222
+ };
223
+ const isJsonObject = (j) => typeof j === "object" && j !== null && !Array.isArray(j) && j.kind === "object";
224
+ const isJsonNumber = (j) => typeof j === "object" && j !== null && !Array.isArray(j) && j.kind === "number";
225
+ const plainRun = /[^\u0000-\u001f"\\]+/y;
226
+ var JsonReader = class extends Reader {
227
+ whitespace() {
228
+ this.match(/[\u0009\u000a\u000d ]*/y);
229
+ }
230
+ string() {
231
+ this.eat("\"");
232
+ let result = "";
233
+ while (this.i < this.source.length) {
234
+ result += this.match(plainRun) ?? "";
235
+ if (this.i >= this.source.length) break;
236
+ const ch = this.source[this.i++];
237
+ if (ch === "\"") {
238
+ assertScalarText(result);
239
+ return result;
240
+ }
241
+ if (ch.charCodeAt(0) < 32) this.fail("Control in JSON string");
242
+ if (ch !== "\\") {
243
+ result += ch;
244
+ continue;
245
+ }
246
+ const escape = this.source[this.i++];
247
+ const simple = {
248
+ "\"": "\"",
249
+ "\\": "\\",
250
+ "/": "/",
251
+ b: "\b",
252
+ f: "\f",
253
+ n: "\n",
254
+ r: "\r",
255
+ t: " "
256
+ };
257
+ if (Object.hasOwn(simple, escape)) result += simple[escape];
258
+ else if (escape === "u") {
259
+ const digits = this.match(/[\dA-Fa-f]{4}/y);
260
+ if (!digits) this.fail("Invalid JSON Unicode escape");
261
+ result += String.fromCharCode(Number.parseInt(digits, 16));
262
+ } else this.fail("Invalid JSON escape");
263
+ }
264
+ return this.fail("Unterminated JSON string");
265
+ }
266
+ value() {
267
+ const frames = [];
268
+ let value = null, ready = false;
269
+ const mapKey = (frame) => {
270
+ this.whitespace();
271
+ frame.key = this.string();
272
+ if (frame.keys.has(frame.key)) this.fail("Duplicate JSON key");
273
+ frame.keys.add(frame.key);
274
+ this.whitespace();
275
+ this.eat(":");
276
+ };
277
+ for (;;) {
278
+ if (!ready) {
279
+ this.whitespace();
280
+ if (this.peek("[")) {
281
+ this.eat("[");
282
+ this.whitespace();
283
+ if (this.peek("]")) {
284
+ this.eat("]");
285
+ value = [];
286
+ } else {
287
+ frames.push({
288
+ kind: "list",
289
+ values: []
290
+ });
291
+ continue;
292
+ }
293
+ } else if (this.peek("{")) {
294
+ this.eat("{");
295
+ this.whitespace();
296
+ if (this.peek("}")) {
297
+ this.eat("}");
298
+ value = new JsonObject([]);
299
+ } else {
300
+ const frame = {
301
+ kind: "map",
302
+ pairs: [],
303
+ keys: /* @__PURE__ */ new Set(),
304
+ key: ""
305
+ };
306
+ mapKey(frame);
307
+ frames.push(frame);
308
+ continue;
309
+ }
310
+ } else value = this.atom();
311
+ }
312
+ const parent = frames.at(-1);
313
+ if (!parent) return value;
314
+ if (parent.kind === "list") parent.values.push(value);
315
+ else parent.pairs.push([parent.key, value]);
316
+ this.whitespace();
317
+ if (this.peek(",")) {
318
+ this.eat(",");
319
+ ready = false;
320
+ if (parent.kind === "map") mapKey(parent);
321
+ } else {
322
+ this.eat(parent.kind === "list" ? "]" : "}");
323
+ frames.pop();
324
+ value = parent.kind === "list" ? parent.values : new JsonObject(parent.pairs);
325
+ ready = true;
326
+ }
327
+ }
328
+ }
329
+ atom() {
330
+ if (this.peek("\"")) return this.string();
331
+ if (this.match(/null/y)) return null;
332
+ const b = this.match(/true|false/y);
333
+ if (b) return b === "true";
334
+ const n = this.match(/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[Ee][+-]?\d+)?/y);
335
+ if (n) return new JsonNumber(n);
336
+ return this.fail("Expected JSON value");
337
+ }
338
+ };
339
+ const fromJson = (value, resolve, functionResolve, tagDecode) => {
340
+ let result = nothing;
341
+ const tasks = [];
342
+ const enqueue = (node, assign) => {
343
+ tasks.push(() => {
344
+ if (node === null) {
345
+ assign(nothing);
346
+ return;
347
+ }
348
+ if (typeof node === "boolean") {
349
+ assign(bool(node));
350
+ return;
351
+ }
352
+ if (typeof node === "string") {
353
+ assign(text(node));
354
+ return;
355
+ }
356
+ if (Array.isArray(node)) {
357
+ const values = new Array(node.length);
358
+ tasks.push(() => assign(listValues(values)));
359
+ for (let i = node.length - 1; i >= 0; i--) enqueue(node[i], (v) => {
360
+ values[i] = v;
361
+ });
362
+ return;
363
+ }
364
+ if (node.kind === "number") {
365
+ const v = dec(node.source);
366
+ if (v.toString() !== node.source || node.source.includes(".") || abs(v.asDecimal().toBigInt()) >= 2n ** 53n) invalidValue("Non-canonical Value Encoding number");
367
+ assign(v);
368
+ return;
369
+ }
370
+ let pairs = node.pairs;
371
+ if (pairs.some(([key]) => key.startsWith("$"))) {
372
+ if (pairs.length !== 1) invalidValue("Value Encoding tag must be the only key");
373
+ const [tag, data] = pairs[0];
374
+ if (tag === "$sessionFunction" && typeof data === "string" && functionResolve) {
375
+ assign(functionResolve(data));
376
+ return;
377
+ }
378
+ const adapted = tag === "$function" || tag === "$pattern" ? tagDecode?.(tag, data) : void 0;
379
+ if (adapted) {
380
+ assign(adapted);
381
+ return;
382
+ }
383
+ if (tag === "$dec" && typeof data === "string") {
384
+ const v = dec(data);
385
+ if (v.toString() !== data || !data.includes(".") && abs(v.asDecimal().toBigInt()) < 2n ** 53n) invalidValue("Non-canonical $dec");
386
+ assign(v);
387
+ return;
388
+ }
389
+ if (tag === "$quantity" && Array.isArray(data) && data.length === 2 && typeof data[0] === "string" && typeof data[1] === "string") {
390
+ const n = dec(data[0]);
391
+ const unit = data[1];
392
+ if (n.toString() !== data[0]) invalidValue("Non-canonical $quantity number");
393
+ const q = quantity(n, unit);
394
+ if (q.kind !== "quantity" || encodedUnit(q) !== unit) invalidValue("A $quantity Unit not in normal form");
395
+ assign(q);
396
+ return;
397
+ }
398
+ if ((tag === "$instant" || tag === "$date") && typeof data === "string") {
399
+ const v = dateValue(data, invalidValue);
400
+ if (v.kind !== (tag === "$instant" ? "instant" : "civil date")) invalidValue(`Malformed ${tag}`);
401
+ assign(v);
402
+ return;
403
+ }
404
+ if (tag === "$bytes" && typeof data === "string") {
405
+ const b = fromBase64(data);
406
+ if (!b) invalidValue("A $bytes that is not canonical padded Base64");
407
+ assign(bytesOf(b));
408
+ return;
409
+ }
410
+ if (tag === "$object" && Array.isArray(data) && data.length === 2 && typeof data[0] === "string" && typeof data[1] === "string") {
411
+ const v = resolved(resolve?.(data[0], data[1]));
412
+ if (!v) invalidValue(`No Host Object ${data[0]} ${data[1]}`);
413
+ assign(v);
414
+ return;
415
+ }
416
+ if (tag === "$range" && Array.isArray(data) && data.length === 2) {
417
+ const ends = [nothing, nothing];
418
+ tasks.push(() => assign(range(ends[0], ends[1])));
419
+ enqueue(data[1], (v) => {
420
+ ends[1] = v;
421
+ });
422
+ enqueue(data[0], (v) => {
423
+ ends[0] = v;
424
+ });
425
+ return;
426
+ }
427
+ if (tag !== "$map" || !Array.isArray(data)) invalidValue(`Unsupported or malformed Value Encoding tag ${tag}`);
428
+ pairs = data.map((pair) => {
429
+ if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string") invalidValue("Malformed $map entry");
430
+ return [pair[0], pair[1]];
431
+ });
432
+ if (!pairs.some(([key]) => key.startsWith("$"))) invalidValue("A $map without a $ key");
433
+ }
434
+ const entries = pairs.map(([key]) => [key, nothing]);
435
+ tasks.push(() => assign(map(entries)));
436
+ for (let i = pairs.length - 1; i >= 0; i--) enqueue(pairs[i][1], (v) => {
437
+ entries[i][1] = v;
438
+ });
439
+ });
440
+ };
441
+ enqueue(value, (v) => {
442
+ result = v;
443
+ });
444
+ while (tasks.length) tasks.pop()();
445
+ return result;
446
+ };
447
+ const dateValue = (s, fail) => {
448
+ const v = s.endsWith("Z") ? instant(parseInstant(s)) : civilDate(s);
449
+ if (v.toString() !== s) fail("Expected a date in its display form");
450
+ return v;
451
+ };
452
+ const encodedUnit = (q) => q.asQuantity().unit;
453
+ const abs = (n) => n < 0n ? -n : n;
454
+ const decodeValue = (source, resolve, functionResolve) => {
455
+ const reader = new JsonReader(source);
456
+ const value = reader.value();
457
+ reader.whitespace();
458
+ reader.done();
459
+ return fromJson(value, resolve, functionResolve);
460
+ };
461
+ /**
462
+ * The members of one JSON object, each value in the Value Encoding, as a
463
+ * Store's contents are written to a file (chapter 12, `:store`).
464
+ */
465
+ const decodeValueMembers = (source, resolve) => {
466
+ const reader = new JsonReader(source);
467
+ const value = reader.value();
468
+ reader.whitespace();
469
+ reader.done();
470
+ if (value === null || typeof value !== "object" || Array.isArray(value) || value.kind !== "object") return invalidValue("Expected one JSON object");
471
+ return value.pairs.map(([key, member]) => [key, fromJson(member, resolve)]);
472
+ };
473
+ /** Parse raw, ordered JSON, rejecting duplicate keys before tag interpretation. */
474
+ const readOrderedJSON = (source) => {
475
+ const reader = new JsonReader(source);
476
+ const value = reader.value();
477
+ reader.whitespace();
478
+ reader.done();
479
+ return value;
480
+ };
481
+ //#endregion
482
+ export { fromJson as a, readDisplay as c, decodeValueMembers as i, readOrderedJSON as l, JsonObject as n, isJsonNumber as o, decodeValue as r, isJsonObject as s, JsonNumber as t };