@northtalk/ts 0.1.0 → 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 (54) hide show
  1. package/README.md +9 -5
  2. package/{encoding-DWlbPq-e.js → base64-DORMd3Hv.js} +197 -1368
  3. package/binary-value-CEmh60GC.d.ts +15 -0
  4. package/capabilities-CH0FkRMq.js +1301 -0
  5. package/checker-Dc1jl2WH.js +6657 -0
  6. package/core-DptnvQT9.d.ts +14 -0
  7. package/{debug-D8Z_u244.d.ts → debug-CQBxKnJB.d.ts} +1147 -780
  8. package/debug.d.ts +2 -1
  9. package/debug.js +2 -1
  10. package/driver.d.ts +16 -2
  11. package/driver.js +98 -20
  12. package/encoding-nlrpj-Pb.js +99 -0
  13. package/{engine-CgCMdGGd.js → engine-BGaJ9dAk.js} +7 -5
  14. package/{engine-BPFnHT9N.d.ts → engine-vbYInVYF.d.ts} +3 -3
  15. package/{errors-DHwz1Vho.js → errors-LYJZ_c8h.js} +91 -17
  16. package/{group-B4eyJKTA.js → group-B742gg4T.js} +1490 -7278
  17. package/{sqlite-capability-CrCej3Po.js → http-capability-CSTkw1Yt.js} +255 -5
  18. package/http.d.ts +59 -0
  19. package/http.js +465 -0
  20. package/index.d.ts +23 -17
  21. package/index.js +19 -12
  22. package/manifest-BscyH_rW.d.ts +70 -0
  23. package/{manifest-DKe2Je6Z.js → manifest-DjsxDSuB.js} +11 -90
  24. package/message-layer.d.ts +12 -0
  25. package/message-layer.js +4 -0
  26. package/notify.d.ts +2 -1
  27. package/notify.js +2 -1
  28. package/{objects-MeXIDDFo.d.ts → objects-DJ3QtCCs.d.ts} +23 -8
  29. package/objects-Db7IB5vQ.js +91 -0
  30. package/operation-promises-EgZXG5N_.js +23 -0
  31. package/package.json +9 -1
  32. package/readers-BFPuosPk.d.ts +25 -0
  33. package/{readers-DyjxJEkL.js → readers-CjJHKHvH.js} +6 -3
  34. package/request-pump-binary-DdY3X-yl.js +2246 -0
  35. package/{router-DHPJNvbt.js → router--71qvxtY.js} +8 -6
  36. package/{router-DpDpAJjz.d.ts → router-Zhrw5l__.d.ts} +6 -5
  37. package/session.d.ts +2 -1
  38. package/session.js +58 -24
  39. package/setup.d.ts +2 -1
  40. package/setup.js +8 -4
  41. package/{sha256-0jiTgVJu.js → sha256-B_kyYw3Z.js} +1 -0
  42. package/sqlite.d.ts +3 -4
  43. package/sqlite.js +6 -5
  44. package/{store-capability-CDoVafZL.js → store-capability-OZp4hXmj.js} +10 -7
  45. package/{store-DrYjcoru.js → store-hJrRULMx.js} +3 -2
  46. package/store.d.ts +3 -2
  47. package/store.js +3 -2
  48. package/{user-capability-Cv0oJhhv.js → user-capability-BK4Asg7D.js} +8 -5
  49. package/wasm.d.ts +42 -22
  50. package/wasm.js +330 -46
  51. package/core-eU5KaYkz.d.ts +0 -23
  52. package/readers-Oh4tO2dK.d.ts +0 -57
  53. package/sqlite-capability-C7-SYdD7.d.ts +0 -87
  54. package/user-capability-CLkDsrCX.d.ts +0 -40
package/debug.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- import { a as DebugSnapshot, dt as isReadable, i as DebugPause, n as DebugFrame, o as DebugSource, r as DebugInstruction, s as RepeatedEffect, t as DebugController, yt as sourceForm } from "./debug-D8Z_u244.js";
1
+
2
+ import { $ as isReadable, a as DebugSnapshot, i as DebugPause, n as DebugFrame, o as DebugSource, r as DebugInstruction, s as RepeatedEffect, st as sourceForm, t as DebugController } from "./debug-CQBxKnJB.js";
2
3
  export { type DebugController, type DebugFrame, type DebugInstruction, type DebugPause, type DebugSnapshot, type DebugSource, type RepeatedEffect, isReadable, sourceForm };
package/debug.js CHANGED
@@ -1 +1,2 @@
1
- export { w as isReadable, B as sourceForm } from "./errors-DHwz1Vho.js";
1
+
2
+ export { D as isReadable, G as sourceForm } from "./errors-LYJZ_c8h.js";
package/driver.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { b as PumpOptions, m as Group, x as PumpResult } from "./debug-D8Z_u244.js";
1
+ /// <reference lib="esnext.disposable" />
2
+ import { Jt as Group, b as PumpResult, m as GroupOptions, y as PumpOptions } from "./debug-CQBxKnJB.js";
2
3
  //#region src/driver.d.ts
3
4
  export type AutoDriveOptions = {
4
5
  /** Epoch microseconds. The default reads `Date.now()`; readings never go backwards. */
@@ -16,12 +17,25 @@ export type AutoDriveOptions = {
16
17
  setDeadline?: (at: bigint, fire: () => void) => () => void;
17
18
  };
18
19
  export type Drive = {
20
+ /** Closes with the default reason, "Host shutdown". */
21
+ [Symbol.asyncDispose](): Promise<void>;
22
+ /** Stops all Scripts, drains, awaits Host run Promises, then cancels scheduling. */
23
+ close(reason?: string): Promise<void>;
19
24
  /** Resolves once no Pump is scheduled or running. A Group waiting only on a deadline counts as settled. */
20
25
  idle(): Promise<void>;
21
26
  /** The Group's onReady: schedules a Pump, once, on a later macrotask. */
22
27
  ready(): void;
23
- /** Cancels the scheduled Pump and the deadline timer; later readiness is ignored. */
28
+ /** Cancels scheduling without stopping Scripts. Does not interrupt an active close. */
24
29
  stop(): void;
25
30
  };
31
+ /** Group and driver options. The factory owns the Group's readiness callback. */
32
+ export type DrivenGroupOptions = Omit<GroupOptions, 'onReady'> & AutoDriveOptions;
33
+ /** Creates a Group on `core` ready to drive queued Inputs from the Host's event loop. */
34
+ export declare const newDrivenGroup: <G extends Group>(core: {
35
+ newGroup(o: GroupOptions): G;
36
+ }, o: DrivenGroupOptions) => {
37
+ drive: Drive;
38
+ group: G;
39
+ };
26
40
  export declare const autoDrive: (group: Group, o?: AutoDriveOptions) => Drive;
27
41
  //#endregion
package/driver.js CHANGED
@@ -1,5 +1,24 @@
1
+
2
+ import { Xt as nowMicros } from "./errors-LYJZ_c8h.js";
3
+ import { n as waitForOperations } from "./operation-promises-EgZXG5N_.js";
1
4
  //#region src/driver.ts
5
+ /** Creates a Group on `core` ready to drive queued Inputs from the Host's event loop. */
6
+ const newDrivenGroup = (core, o) => {
7
+ const { name, seed, trace, ...options } = o;
8
+ const group = core.newGroup({
9
+ name,
10
+ seed,
11
+ trace,
12
+ onReady: () => drive.ready()
13
+ });
14
+ const drive = autoDrive(group, options);
15
+ return {
16
+ group,
17
+ drive
18
+ };
19
+ };
2
20
  const MAX_DELAY_MS = 2 ** 31 - 1;
21
+ const asyncDispose = Symbol.asyncDispose ?? Symbol.for("Symbol.asyncDispose");
3
22
  const timeoutDeadline = (read) => (at, fire) => {
4
23
  let handle;
5
24
  const arm = () => {
@@ -10,23 +29,28 @@ const timeoutDeadline = (read) => (at, fire) => {
10
29
  return () => clearTimeout(handle);
11
30
  };
12
31
  const autoDrive = (group, o = {}) => {
13
- const read = o.clock ?? (() => BigInt(Date.now()) * 1000n);
32
+ const read = o.clock ?? nowMicros;
14
33
  const setDeadline = o.setDeadline ?? timeoutDeadline(read);
15
34
  let last = 0n;
16
35
  let scheduled;
17
36
  let cancelDeadline;
18
37
  let stopped = false;
38
+ let pumping = false;
39
+ let closing = false;
40
+ let closePromise;
41
+ let finishClose;
19
42
  let waiters = [];
20
43
  const settle = () => {
21
- if (scheduled === void 0) {
44
+ if (scheduled === void 0 && !pumping) {
22
45
  const done = waiters;
23
46
  waiters = [];
24
47
  for (const resolve of done) resolve();
25
48
  }
26
49
  };
27
50
  const clearDeadline = () => {
28
- cancelDeadline?.();
51
+ const cancel = cancelDeadline;
29
52
  cancelDeadline = void 0;
53
+ cancel?.();
30
54
  };
31
55
  const pump = () => {
32
56
  scheduled = void 0;
@@ -34,12 +58,13 @@ const autoDrive = (group, o = {}) => {
34
58
  settle();
35
59
  return;
36
60
  }
37
- clearDeadline();
38
- const reading = read();
39
- const now = reading > last ? reading : last;
40
- last = now;
61
+ pumping = true;
41
62
  let again = false;
42
63
  try {
64
+ clearDeadline();
65
+ const reading = read();
66
+ const now = reading > last ? reading : last;
67
+ last = now;
43
68
  const result = group.pump(now, o.pump);
44
69
  o.onPump?.(result);
45
70
  again = result.state === "sliced" || result.state === "rewound";
@@ -48,27 +73,80 @@ const autoDrive = (group, o = {}) => {
48
73
  ready();
49
74
  });
50
75
  } catch (error) {
51
- o.onError?.(error);
76
+ let failure = error;
77
+ try {
78
+ o.onError?.(error);
79
+ } catch (callbackError) {
80
+ if (!closing) throw callbackError;
81
+ failure = callbackError;
82
+ }
83
+ if (closing) finishClose?.({ error: failure });
84
+ } finally {
85
+ pumping = false;
86
+ if (again) ready();
87
+ settle();
52
88
  }
53
- if (again) ready();
54
- settle();
55
89
  };
56
90
  const ready = () => {
57
91
  if (!stopped && scheduled === void 0) scheduled = setTimeout(pump, 0);
58
92
  };
59
- return {
60
- ready,
61
- idle: () => scheduled === void 0 ? Promise.resolve() : new Promise((resolve) => waiters.push(resolve)),
62
- stop: () => {
63
- stopped = true;
64
- if (scheduled !== void 0) {
65
- clearTimeout(scheduled);
66
- scheduled = void 0;
67
- }
93
+ const idle = () => scheduled === void 0 && !pumping ? Promise.resolve() : new Promise((resolve) => waiters.push(resolve));
94
+ const stop = () => {
95
+ stopped = true;
96
+ if (scheduled !== void 0) {
97
+ clearTimeout(scheduled);
98
+ scheduled = void 0;
99
+ }
100
+ try {
68
101
  clearDeadline();
102
+ } finally {
69
103
  settle();
70
104
  }
71
105
  };
106
+ const close = (reason = "Host shutdown") => {
107
+ if (closePromise) return closePromise;
108
+ closing = true;
109
+ stopped = false;
110
+ closePromise = new Promise((resolve, reject) => {
111
+ finishClose = (failure) => {
112
+ if (!closing) return;
113
+ closing = false;
114
+ try {
115
+ stop();
116
+ } catch (error) {
117
+ reject(error);
118
+ return;
119
+ }
120
+ if (failure) reject(failure.error);
121
+ else resolve();
122
+ };
123
+ });
124
+ const drain = async () => {
125
+ try {
126
+ for (const name of group.scriptNames()) group.script(name).stop(reason);
127
+ ready();
128
+ await idle();
129
+ if (!closing) return;
130
+ await waitForOperations(group);
131
+ if (!closing) return;
132
+ await idle();
133
+ finishClose?.();
134
+ } catch (error) {
135
+ finishClose?.({ error });
136
+ }
137
+ };
138
+ drain();
139
+ return closePromise;
140
+ };
141
+ return {
142
+ close,
143
+ idle,
144
+ ready,
145
+ stop: () => {
146
+ if (!closing) stop();
147
+ },
148
+ [asyncDispose]: () => close()
149
+ };
72
150
  };
73
151
  //#endregion
74
- export { autoDrive };
152
+ export { autoDrive, newDrivenGroup };
@@ -0,0 +1,99 @@
1
+
2
+ import { H as requireValue, o as invalidValue } from "./errors-LYJZ_c8h.js";
3
+ import { n as toBase64 } from "./base64-DORMd3Hv.js";
4
+ //#region src/standard-capability-checks.ts
5
+ const checks = /* @__PURE__ */ new WeakMap();
6
+ const registerStandardChecks = (op, rules) => {
7
+ checks.set(op, rules);
8
+ };
9
+ const standardChecks = (op) => checks.get(op);
10
+ //#endregion
11
+ //#region src/encoding.ts
12
+ /** The spec's JSON string form: every U+0000..U+001F uses lowercase \u00xx. */
13
+ const quoteJSON = (s) => "\"" + s.replaceAll(/[\u0000-\u001f"\\]/g, (ch) => ch === "\"" ? String.raw`\"` : ch === "\\" ? "\\\\" : String.raw`\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`) + "\"";
14
+ const encodeValue = (value, adapter) => {
15
+ requireValue(value);
16
+ const pending = [value];
17
+ const output = [];
18
+ while (pending.length) {
19
+ const next = pending.pop();
20
+ if (typeof next === "string") {
21
+ output.push(next);
22
+ continue;
23
+ }
24
+ switch (next.kind) {
25
+ case "nothing":
26
+ output.push("null");
27
+ break;
28
+ case "boolean":
29
+ output.push(next.asBool() ? "true" : "false");
30
+ break;
31
+ case "text":
32
+ output.push(quoteJSON(next.asText()));
33
+ break;
34
+ case "number": {
35
+ const canonical = next.asDecimal().toString();
36
+ output.push(!canonical.includes(".") && BigInt(canonical) > -(2n ** 53n) && BigInt(canonical) < 2n ** 53n ? canonical : `{"$dec":${quoteJSON(canonical)}}`);
37
+ break;
38
+ }
39
+ case "instant":
40
+ output.push(`{"$instant":${quoteJSON(next.toString())}}`);
41
+ break;
42
+ case "civil date":
43
+ output.push(`{"$date":${quoteJSON(next.toString())}}`);
44
+ break;
45
+ case "object": {
46
+ const o = next.asObjectRef();
47
+ output.push(`{"$object":[${quoteJSON(o.kind)},${quoteJSON(o.id)}]}`);
48
+ break;
49
+ }
50
+ case "bytes":
51
+ output.push(`{"$bytes":${quoteJSON(toBase64(next.bytesView()))}}`);
52
+ break;
53
+ case "quantity": {
54
+ const q = next.asQuantity();
55
+ output.push(`{"$quantity":[${quoteJSON(q.number.toString())},${quoteJSON(q.unit)}]}`);
56
+ break;
57
+ }
58
+ case "range": {
59
+ const { from, to } = next.asRange();
60
+ output.push("{\"$range\":[");
61
+ pending.push("]}", to, ",", from);
62
+ break;
63
+ }
64
+ case "list":
65
+ output.push("[");
66
+ pending.push("]");
67
+ for (let i = next.length; i >= 1; i--) {
68
+ if (i < next.length) pending.push(",");
69
+ pending.push(next.index(i));
70
+ }
71
+ break;
72
+ case "map": {
73
+ const entries = next.entries();
74
+ const tagged = entries.some(([k]) => k.startsWith("$"));
75
+ output.push(tagged ? "{\"$map\":[" : "{");
76
+ pending.push(tagged ? "]}" : "}");
77
+ for (let i = entries.length - 1; i >= 0; i--) {
78
+ const [k, v] = entries[i];
79
+ if (i < entries.length - 1) pending.push(",");
80
+ if (tagged) pending.push("]", v, `[${quoteJSON(k)},`);
81
+ else pending.push(v, `${quoteJSON(k)}:`);
82
+ }
83
+ break;
84
+ }
85
+ case "function":
86
+ case "pattern":
87
+ if (adapter) {
88
+ output.push(adapter(next));
89
+ break;
90
+ }
91
+ invalidValue(`The Value Encoding of a ${next.kind} isn't implemented yet`);
92
+ break;
93
+ default: invalidValue(`The Value Encoding of a ${next.kind} isn't implemented yet`);
94
+ }
95
+ }
96
+ return output.join("");
97
+ };
98
+ //#endregion
99
+ export { standardChecks as i, quoteJSON as n, registerStandardChecks as r, encodeValue as t };
@@ -1,8 +1,10 @@
1
- import { E as listValues, V as text, a as invalidValue, h as dec, j as nothing } from "./errors-DHwz1Vho.js";
2
- import { Q as sizeOf, n as quoteJSON, t as encodeValue, ut as compareText } from "./encoding-DWlbPq-e.js";
3
- import { n as decodeValueMembers } from "./readers-DyjxJEkL.js";
4
- import { n as hostScriptError, t as add } from "./store-capability-CDoVafZL.js";
5
- import { n as createRouter, t as changed } from "./router-DHPJNvbt.js";
1
+
2
+ import { K as text, P as nothing, _ as dec, k as listValues, o as invalidValue } from "./errors-LYJZ_c8h.js";
3
+ import { Y as sizeOf, st as compareText } from "./base64-DORMd3Hv.js";
4
+ import { i as decodeValueMembers } from "./readers-CjJHKHvH.js";
5
+ import { n as quoteJSON, t as encodeValue } from "./encoding-nlrpj-Pb.js";
6
+ import { n as hostScriptError, t as add } from "./store-capability-OZp4hXmj.js";
7
+ import { n as createRouter, t as changed } from "./router--71qvxtY.js";
6
8
  //#region src/store/engine.ts
7
9
  /** The Session Store's quotas (chapter 12, The Session Store). */
8
10
  const sessionQuotas = Object.freeze({
@@ -1,6 +1,6 @@
1
- import { At as Call, Kt as SegmentContext, Pt as EffectResult, at as Value, zt as GrantContext } from "./debug-D8Z_u244.js";
2
- import { r as StoreImpl } from "./user-capability-CLkDsrCX.js";
3
- import { i as WatchLimits, n as RouterOptions, t as NotificationRouter } from "./router-DpDpAJjz.js";
1
+
2
+ import { kt as GrantContext, nn as StoreImpl, q as Value, wt as EffectResult, yt as Call, zt as SegmentContext } from "./debug-CQBxKnJB.js";
3
+ import { i as WatchLimits, n as RouterOptions, t as NotificationRouter } from "./router-Zhrw5l__.js";
4
4
  //#region src/store/engine.d.ts
5
5
  /** A Store's limits, each counted by logical size (chapter 8). */
6
6
  type StoreQuotas = {
@@ -1,3 +1,4 @@
1
+
1
2
  //#region src/persistent-tree.ts
2
3
  const total = (t) => t?.total ?? 0;
3
4
  const height = (t) => t?.height ?? 0;
@@ -76,6 +77,29 @@ const values = function* (t) {
76
77
  //#endregion
77
78
  //#region src/list-storage.ts
78
79
  const chunkSize = 32;
80
+ /** Replacement keeps the tree's shape, spans and endpoint keys unchanged. */
81
+ const replaceItem = (root, i, value) => {
82
+ const offset = total(root.left);
83
+ let left = root.left;
84
+ let right = root.right;
85
+ let chunk = root.value;
86
+ if (i < offset) left = replaceItem(left, i, value);
87
+ else if (i >= offset + root.span) right = replaceItem(right, i - offset - root.span, value);
88
+ else {
89
+ const copy = chunk.slice();
90
+ copy[i - offset] = value;
91
+ chunk = copy;
92
+ }
93
+ return {
94
+ key: root.key,
95
+ value: chunk,
96
+ span: root.span,
97
+ left,
98
+ right,
99
+ height: root.height,
100
+ total: root.total
101
+ };
102
+ };
79
103
  /** A persistent sequence of small chunks. Growth and point edits copy only a
80
104
  * chunk and its AVL path, including when extending a retained older List. */
81
105
  var ListStorage = class ListStorage {
@@ -104,10 +128,10 @@ var ListStorage = class ListStorage {
104
128
  return found?.node.value[found.offset];
105
129
  }
106
130
  set(i, value) {
131
+ if (value !== void 0) return new ListStorage(replaceItem(this.#root, i, value), this.#first, this.#last);
107
132
  const found = at(this.#root, i);
108
133
  const chunk = [...found.node.value];
109
- if (value === void 0) chunk.splice(found.offset, 1);
110
- else chunk[found.offset] = value;
134
+ chunk.splice(found.offset, 1);
111
135
  const root = chunk.length ? put(this.#root, found.node.key, chunk, chunk.length) : remove(this.#root, found.node.key);
112
136
  const first = at(root, 0)?.node.key ?? 0;
113
137
  const last = at(root, total(root) - 1)?.node.key ?? -1;
@@ -184,6 +208,10 @@ var MapStorage = class MapStorage {
184
208
  //#region src/dates.ts
185
209
  const US_PER_SECOND = 1000000n;
186
210
  const US_PER_DAY = 86400n * US_PER_SECOND;
211
+ /** The current wall-clock time as epoch microseconds, for `pump`. */
212
+ const nowMicros = () => BigInt(Date.now()) * 1000n;
213
+ /** Whether a mathematical deadline can cross the Host boundary as an Instant. */
214
+ const isInstant = (us) => us >= -62135596800000000n && us < 253402300800000000n;
187
215
  /** A date or time past the range; `year` is the year it would have been. */
188
216
  var DateRangeError = class extends Error {
189
217
  year;
@@ -1533,6 +1561,7 @@ const diagnosticCodes = [
1533
1561
  "pattern too large",
1534
1562
  "wrong argument count",
1535
1563
  "wrong argument",
1564
+ "wrong labels",
1536
1565
  "unknown operation",
1537
1566
  "wrong mode",
1538
1567
  "missing and wait",
@@ -1874,6 +1903,24 @@ const builtins = [
1874
1903
  "variadic": false
1875
1904
  }
1876
1905
  },
1906
+ {
1907
+ "name": "degrees",
1908
+ "kind": "function",
1909
+ "contract": {
1910
+ "required": 1,
1911
+ "total": 1,
1912
+ "variadic": false
1913
+ }
1914
+ },
1915
+ {
1916
+ "name": "radians",
1917
+ "kind": "function",
1918
+ "contract": {
1919
+ "required": 1,
1920
+ "total": 1,
1921
+ "variadic": false
1922
+ }
1923
+ },
1877
1924
  {
1878
1925
  "name": "random",
1879
1926
  "kind": "function",
@@ -2942,40 +2989,59 @@ const powerOf = (spec, n) => ownUnit(checkCalendar(spec.map((slot) => ({
2942
2989
  //#endregion
2943
2990
  //#region src/values.ts
2944
2991
  const valueToken = Symbol("Value");
2992
+ const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
2993
+ const frozenParts = (parts) => Object.freeze({
2994
+ coefficient: parts.coefficient,
2995
+ exponent: parts.exponent,
2996
+ negative: parts.negative && parts.coefficient !== 0n
2997
+ });
2945
2998
  const decimalToken = Symbol("Decimal");
2946
2999
  let makeValue;
2947
3000
  let extendListValue;
2948
3001
  let editListValue;
2949
3002
  let editMapValue;
2950
3003
  let makeDecimal;
3004
+ let makeSmallDecimal;
2951
3005
  /** Internal: a Decimal's cached, immutable arithmetic representation. */
2952
3006
  let decimalParts;
3007
+ /**
3008
+ * Internal: a Decimal's value as a JS number when it is a safe integer
3009
+ * written with exponent 0, or NaN. The fast paths compute on it directly.
3010
+ */
3011
+ let smallInteger;
3012
+ let isDecimal;
2953
3013
  var Decimal = class Decimal {
2954
3014
  #canonical;
2955
3015
  #parts;
2956
- constructor(token, canonical, parts) {
3016
+ #small;
3017
+ constructor(token, canonical, parts, small) {
2957
3018
  if (token !== decimalToken) invalidValue("Use a numeric constructor");
2958
3019
  this.#canonical = canonical;
2959
- this.#parts = Object.freeze({
2960
- coefficient: parts.coefficient,
2961
- exponent: parts.exponent,
2962
- negative: parts.negative && parts.coefficient !== 0n
2963
- });
3020
+ this.#parts = parts && frozenParts(parts);
3021
+ this.#small = small;
2964
3022
  Object.freeze(this);
2965
3023
  }
2966
3024
  static {
2967
- makeDecimal = (canonical, parts) => new Decimal(decimalToken, canonical, parts);
2968
- decimalParts = (decimal) => decimal.#parts;
3025
+ isDecimal = (input) => typeof input === "object" && input !== null && #small in input;
3026
+ makeDecimal = (canonical, parts) => new Decimal(decimalToken, canonical, parts, parts.exponent === 0 && parts.coefficient <= SAFE ? Number(parts.coefficient) * (parts.negative ? -1 : 1) + 0 : NaN);
3027
+ makeSmallDecimal = (n) => new Decimal(decimalToken, void 0, void 0, n);
3028
+ decimalParts = (decimal) => decimal.#parts ??= frozenParts({
3029
+ coefficient: BigInt(Math.abs(decimal.#small)),
3030
+ exponent: 0,
3031
+ negative: decimal.#small < 0
3032
+ });
3033
+ smallInteger = (decimal) => decimal.#small;
2969
3034
  }
2970
3035
  toString() {
2971
- return this.#canonical;
3036
+ return this.#canonical ??= String(this.#small);
2972
3037
  }
2973
3038
  toBigInt() {
2974
- if (!isInteger(this.#parts)) invalidValue("Decimal is not an integer");
2975
- return integerOf(this.#parts);
3039
+ const parts = decimalParts(this);
3040
+ if (!isInteger(parts)) invalidValue("Decimal is not an integer");
3041
+ return integerOf(parts);
2976
3042
  }
2977
3043
  toNumberLossy() {
2978
- return Number(this.#canonical);
3044
+ return Number(this.toString());
2979
3045
  }
2980
3046
  };
2981
3047
  /** Immutable, opaque value. Host code uses the named constructors. */
@@ -3353,6 +3419,8 @@ const dec = (s) => {
3353
3419
  }));
3354
3420
  };
3355
3421
  /** Internal: a checked arithmetic result, retaining its coefficient directly. */
3422
+ /** A safe integer as a number Value, without BigInt or text work. */
3423
+ const smallNumber = (n) => makeValue("number", makeSmallDecimal(n + 0));
3356
3424
  const canonicalNumber = (parts) => makeValue("number", makeDecimal(formatDec(parts), parts));
3357
3425
  /** ECMAScript's shortest round-trip digits, expanded without rounding. */
3358
3426
  const num = (n) => {
@@ -3476,7 +3544,7 @@ const map = (input) => {
3476
3544
  requireValue(value);
3477
3545
  if (seen.has(nfc)) invalidValue(`Duplicate map key: ${displayText(nfc)}`);
3478
3546
  seen.add(nfc);
3479
- pairs.push(Object.freeze([nfc, value]));
3547
+ pairs.push([nfc, value]);
3480
3548
  }
3481
3549
  return makeValue("map", MapStorage.copy(pairs));
3482
3550
  };
@@ -3645,17 +3713,23 @@ var MailboxFull = class extends Error {
3645
3713
  };
3646
3714
  /**
3647
3715
  * A Script-level error as the Host sees it, such as a Request's `send failed`
3648
- * or a `run end`'s error. Its `data` is a map, or Nothing.
3716
+ * or a `run end`'s error. Its `data` is a map, or Nothing. A `send failed`
3717
+ * also carries its `reason` from `data`.
3649
3718
  */
3650
3719
  var ScriptError = class extends Error {
3651
3720
  code;
3652
3721
  data;
3722
+ reason;
3653
3723
  constructor(code, message, data = nothing) {
3654
3724
  super(message);
3655
3725
  this.code = code;
3656
3726
  this.data = data;
3657
3727
  this.name = "ScriptError";
3728
+ this.reason = code === "send failed" ? data.get("reason").asText() : void 0;
3658
3729
  }
3659
3730
  };
3731
+ /** The rejection of a Request whose receiver's Run ended without answering. */
3732
+ const sendFailed = (reason) => new ScriptError("send failed", `No answer came: the receiver's Run ended ${reason}`, map([["reason", text(reason)]]));
3733
+ const hostDetail = (error) => error instanceof Error ? `${error.name}: ${error.message}` : `the Host threw ${typeof error === "symbol" ? error.toString() : String(error)}`;
3660
3734
  //#endregion
3661
- export { builtins as $, mapWithEntry as A, subtract as At, sourceForm as B, civilUs as Bt, instantOf as C, integerOf as Ct, listWithItem as D, negate as Dt, listValues as E, multiply as Et, quantity as F, addMonths as Ft, fromBase as G, parseInstant as Gt, trimWhiteSpace as H, formatInstant as Ht, quantityOf as I, checkInstant as It, powerOf as J, ownUnit as K, parseInstantText as Kt, range as L, civilDays as Lt, num as M, DateRangeError as Mt, objectValue as N, US_PER_DAY as Nt, literalDigits as O, powerInteger as Ot, patternValue as P, US_PER_SECOND as Pt, unitText as Q, record as R, civilOfDays as Rt, instant as S, formatDec as St, list as T, mod as Tt, UnitError as U, isoWeek as Ut, text as V, dayOfYear as Vt, combine as W, parseCivil as Wt, toBase as X, sameDimension as Y, unitEntry as Z, displayText as _, compareDec as _t, invalidValue as a, assertScalarText as at, functionsBelongTo as b, div as bt, bool as c, isWhiteSpace as ct, canonicalNumber as d, scalarCount as dt, diagnosticCodes as et, civilDate as f, simpleFold as ft, decimalParts as g, add as gt, dec as h, ArithmeticError as ht, ScriptError as i, units as it, nothing as j, withinLimits as jt, map as k, roundRatio as kt, bytes as l, lower as lt, compareBytes as m, unicodeVersion as mt, LoadError as n, libraryExports as nt, Decimal as o, characterBoundaries as ot, civilOf as p, upper as pt, parseUnit as q, weekday as qt, MailboxFull as r, unitKinds as rt, Value as s, generalCategory as st, HostError as t, grammar as tt, bytesOf as u, normalizeNFC as ut, extendList as v, decOf as vt, isReadable as w, isInteger as wt, hiddenCodePoint as x, divide as xt, functionValue as y, digitsOf as yt, requireValue as z, civilOfUs as zt };
3735
+ export { powerOf as $, parseInstantText as $t, listWithItem as A, mod as At, range as B, addMonths as Bt, hiddenCodePoint as C, decOf as Ct, isReadable as D, formatDec as Dt, isDecimal as E, divide as Et, num as F, subtract as Ft, sourceForm as G, civilUs as Gt, requireValue as H, civilDays as Ht, objectValue as I, withinLimits as It, UnitError as J, isInstant as Jt, text as K, dayOfYear as Kt, patternValue as L, DateRangeError as Lt, map as M, negate as Mt, mapWithEntry as N, powerInteger as Nt, list as O, integerOf as Ot, nothing as P, roundRatio as Pt, parseUnit as Q, parseInstant as Qt, quantity as R, US_PER_DAY as Rt, functionsBelongTo as S, compareDec as St, instantOf as T, div as Tt, smallInteger as U, civilOfDays as Ut, record as V, checkInstant as Vt, smallNumber as W, civilOfUs as Wt, fromBase as X, nowMicros as Xt, combine as Y, isoWeek as Yt, ownUnit as Z, parseCivil as Zt, dec as _, simpleFold as _t, hostDetail as a, diagnosticCodes as at, extendList as b, ArithmeticError as bt, Decimal as c, unitKinds as ct, bytes as d, characterBoundaries as dt, weekday as en, sameDimension as et, bytesOf as f, generalCategory as ft, compareBytes as g, scalarCount as gt, civilOf as h, normalizeNFC as ht, ScriptError as i, builtins as it, literalDigits as j, multiply as jt, listValues as k, isInteger as kt, Value as l, units as lt, civilDate as m, lower as mt, LoadError as n, unitEntry as nt, invalidValue as o, grammar as ot, canonicalNumber as p, isWhiteSpace as pt, trimWhiteSpace as q, formatInstant as qt, MailboxFull as r, unitText as rt, sendFailed as s, libraryExports as st, HostError as t, toBase as tt, bool as u, assertScalarText as ut, decimalParts as v, upper as vt, instant as w, digitsOf as wt, functionValue as x, add as xt, displayText as y, unicodeVersion as yt, quantityOf as z, US_PER_SECOND as zt };