@northtalk/ts 0.6.0 → 0.7.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 (58) hide show
  1. package/{binary-value-C4ZiXVjv.d.ts → binary-value-M8v567iA.d.ts} +1 -1
  2. package/{checker-CUhn2XaM.js → checker-Coml0Tf9.js} +581 -71
  3. package/{core-egHbNmve.d.ts → core-D4qYURer.d.ts} +1 -1
  4. package/{debug--Of4MSLw.d.ts → debug-C_Ob5rkl.d.ts} +126 -9
  5. package/debug.d.ts +1 -1
  6. package/debug.js +1 -1
  7. package/{driver-BIm1mL77.d.ts → driver-CLi_OmyQ.d.ts} +1 -1
  8. package/driver.d.ts +1 -1
  9. package/driver.js +1 -1
  10. package/encoding-BL2ECJmg.js +338 -0
  11. package/{engine-DbDcopGM.d.ts → engine-BBNHy4-F.d.ts} +2 -2
  12. package/{engine-CXf5FCwi.js → engine-DhBk0lTt.js} +6 -6
  13. package/{errors-D11zizZg.js → errors-P3ga1I-9.js} +124 -21
  14. package/{group-BpzTo0k4.js → group-BqccKTWz.js} +367 -68
  15. package/{http-fetch-DFwVIOQg.js → http-fetch-DA-NbFIM.js} +2 -2
  16. package/http.d.ts +1 -1
  17. package/http.js +4 -4
  18. package/index-CBuczWK0.d.ts +9 -0
  19. package/index.d.ts +6 -12
  20. package/index.js +15 -14
  21. package/{inline-grants-XbX9HL_w.js → inline-grants-BT2nnfLA.js} +4 -5
  22. package/{lean-aCvN6y52.js → lean-BJmLobmd.js} +13 -8
  23. package/{lean-DiS9rUcn.d.ts → lean-CFLJ9VrX.d.ts} +155 -6
  24. package/lean.d.ts +5 -6
  25. package/lean.js +15 -14
  26. package/{manifest-CCfpn0kC.js → manifest-37x-HSxH.js} +4 -3
  27. package/message-layer.d.ts +2 -2
  28. package/message-layer.js +2 -2
  29. package/notify.d.ts +1 -1
  30. package/notify.js +1 -1
  31. package/{objects-DmUc0lha.js → objects-DE6kRk0r.js} +1 -1
  32. package/{objects-DYq_YvaQ.d.ts → objects-DVlpWsi0.d.ts} +7 -3
  33. package/{operations-DnCcztkZ.js → operations-CGjDlkGU.js} +73 -15
  34. package/package.json +5 -1
  35. package/peer-capability-elnbQy-J.js +149 -0
  36. package/peer.d.ts +173 -0
  37. package/peer.js +542 -0
  38. package/{readers-8WCimMop.d.ts → readers-ChQ0e92c.d.ts} +1 -1
  39. package/{readers-CsvlahLi.js → readers-yMS1eAOp.js} +1 -1
  40. package/{request-pump-binary-oqjWFqZA.js → request-pump-binary-BS1J8DF2.js} +4 -4
  41. package/{router-BZ-aYeXA.js → router-Bm7A2kjt.js} +4 -4
  42. package/{router-BQsO8aPV.d.ts → router-D0rf5SkW.d.ts} +2 -2
  43. package/session.d.ts +2 -2
  44. package/session.js +64 -16
  45. package/setup.d.ts +3 -2
  46. package/setup.js +13 -16
  47. package/sqlite.d.ts +2 -2
  48. package/sqlite.js +5 -5
  49. package/{store-DHlo6fP5.js → store-D80OlpyG.js} +2 -2
  50. package/store-capability-DBLlWaNO.js +187 -0
  51. package/store.d.ts +2 -2
  52. package/store.js +2 -2
  53. package/{user-capability-BcRQyyEw.js → user-capability-D6hGa3eF.js} +3 -4
  54. package/wasm.d.ts +13 -6
  55. package/wasm.js +45 -19
  56. package/encoding-RUuES_e4.js +0 -99
  57. package/manifest-mpivREn-.d.ts +0 -122
  58. package/store-capability-BrUUAwVS.js +0 -389
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.disposable" />
2
- import { C as Report, D as RunEvent, Dn as Library, E as RestoreResult, F as TsGroupOptions, Fn as Limits, Ht as ScopeDecl, I as TsRestoreOptions, J as Value, L as TsScript, M as SessionPort, Mn as compileLibrary, Nn as replacementLibraries, P as TsGroup, Zn as LoadError, _n as LocaleImpl, g as Inspection, gt as ObjectKindDef, ht as ObjectKind, j as SessionControls, jt as Grant, mn as SqliteBinding, pt as HostObject, qt as Shape, t as DebugController, xt as CapabilityDef, yn as CalendarImpl, yt as GrantDecls } from "./debug--Of4MSLw.js";
2
+ import { C as Report, Cn as CalendarImpl, D as RunEvent, E as RestoreResult, F as TsGroupOptions, Ht as ScopeDecl, I as TsRestoreOptions, J as Value, L as TsScript, M as SessionPort, Nn as Library, P as TsGroup, Rn as compileLibrary, Vn as Limits, g as Inspection, gt as ObjectKindDef, ht as ObjectKind, j as SessionControls, jt as Grant, pt as HostObject, qt as Shape, rr as LoadError, t as DebugController, vn as SqliteBinding, xn as LocaleImpl, xt as CapabilityDef, yt as GrantDecls, zn as replacementLibraries } from "./debug-C_Ob5rkl.js";
3
3
  //#region src/setup.d.ts
4
4
  type ShapeSpec = string | {
5
5
  quantity: string;
@@ -136,7 +136,6 @@ type Setup = {
136
136
  perStep?: number;
137
137
  }[];
138
138
  };
139
- declare const operationDeclarations: (capabilities: ReadonlyMap<string, CapabilityDef<unknown>>) => GrantDecls;
140
139
  /**
141
140
  * The Core a case runs on: the TS Core's free functions by default, or
142
141
  * another Core behind the same embedding interface, such as the Zig reactor's
@@ -166,6 +165,10 @@ type SetupGroup = {
166
165
  load(group: TsGroup, name: string, objects?: Record<string, HostObject>): TsScript;
167
166
  };
168
167
  /** Make a Group whose Scripts are loaded only when the Host requests them. */
168
+ /** A case's `musical-clock` Standard Capability, as the Group option. */
169
+ declare const musicalClockOf: (capabilities: ReadonlyMap<string, CapabilityDef<unknown>>) => {
170
+ musicalClock?: CapabilityDef<unknown>;
171
+ };
169
172
  declare const buildSetupGroup: (setup: Setup, capabilities: ReadonlyMap<string, CapabilityDef<unknown>>, options: {
170
173
  core?: CaseCore;
171
174
  name: string;
@@ -469,6 +472,7 @@ declare class SessionHost {
469
472
  private save;
470
473
  private restore;
471
474
  private library;
475
+ private addScript;
472
476
  private store;
473
477
  private export;
474
478
  private inspected;
@@ -649,4 +653,4 @@ declare class SessionObjects {
649
653
  private perform;
650
654
  }
651
655
  //#endregion
652
- export { shapeOf as A, Setup as C, capabilityOperations as D, buildSetupGroup as E, tsCore as M, immutableSetup as O, OperationSpec as S, ShapeSpec as T, UserPrompt as _, ReplayOptions as a, MissingCapabilityError as b, parseTranscript as c, DebugAction as d, MOCK_ARGUMENTS as f, SourcePlacement as g, SessionHost as h, parseEnvelope as i, shapeSpec as j, operationDeclarations as k, replayTranscript as l, SessionEnvironment as m, ObjectReference as n, Replayed as o, Mock as p, SessionObjects as r, TranscriptItem as s, Envelope as t, writeTranscript as u, Waiting as v, SetupGroup as w, ObjectRefSpec as x, CaseCore as y };
656
+ export { shapeOf as A, Setup as C, capabilityOperations as D, buildSetupGroup as E, tsCore as M, immutableSetup as O, OperationSpec as S, ShapeSpec as T, UserPrompt as _, ReplayOptions as a, MissingCapabilityError as b, parseTranscript as c, DebugAction as d, MOCK_ARGUMENTS as f, SourcePlacement as g, SessionHost as h, parseEnvelope as i, shapeSpec as j, musicalClockOf as k, replayTranscript as l, SessionEnvironment as m, ObjectReference as n, Replayed as o, Mock as p, SessionObjects as r, TranscriptItem as s, Envelope as t, writeTranscript as u, Waiting as v, SetupGroup as w, ObjectRefSpec as x, CaseCore as y };
@@ -1,5 +1,5 @@
1
1
 
2
- import { $ as textStorage, $t as lower, A as listValues, At as US_PER_DAY, B as ownedMapPairs, Ct as multiply, D as isDecimal, Dt as subtract, E as instantOf, Et as roundRatio, H as quantity, Ht as isoWeek, I as mapWithEntry, It as civilOfDays, J as sliceText, Jt as assertScalarText, Kt as parseInstantText, L as nothing, Lt as civilOfUs, M as literalDigits, Mt as addMonths, N as map, Nt as checkInstant, Ot as withinLimits, Pt as civilDays, Q as text, Qt as isWhiteSpace, R as num, Rt as civilUs, St as mod, T as instant, Tt as powerInteger, U as quantityOf, V as patternValue, W as range, Wt as parseCivil, X as smallNumber, Xt as charactersAt, Y as smallInteger, Yt as characterBoundaries, Zt as generalCategory, _ as concatText, _t as div, at as parseUnit, b as displayText, bt as integerOf, ct as toBase, d as bytes, dt as ArithmeticError, en as normalizeNFC, et as trimWhiteSpace, f as bytesOf, ft as add, g as compareBytes, gt as digitsOf, h as civilOf, ht as digitCount$1, it as ownUnit, j as listWithItem, jt as US_PER_SECOND, k as list, kt as DateRangeError, l as Value, ln as unitKinds, lt as unitEntry, mt as decOf, nn as simpleFold, nt as combine, o as invalidValue, ot as powerOf, p as canonicalNumber, pt as compareDec, qt as weekday, rn as upper, rt as fromBase, sn as grammar, st as sameDimension, t as HostError, tn as scalarCount, tt as UnitError, u as bool, ut as unitText, v as dec, vt as divide, wt as negate, x as extendList, xt as isInteger, y as decimalParts, yt as formatDec, zt as dayOfYear } from "./errors-D11zizZg.js";
2
+ import { $t as charactersAt, A as listValues, At as subtract, B as ownedMapPairs, Bt as civilOfUs, Ct as integerOf, D as isDecimal, Dt as negate, E as instantOf, Et as multiply, Ft as addMonths, Gt as isoWeek, H as quantity, Ht as dayOfYear, I as mapWithEntry, It as checkInstant, J as sliceText, L as nothing, Lt as civilDays, M as literalDigits, Mt as DateRangeError, N as map, Nt as US_PER_DAY, Ot as powerInteger, Pt as US_PER_SECOND, Q as smallInteger, Qt as characterBoundaries, R as num, St as formatDec, T as instant, Tt as mod, U as quantityOf, V as patternValue, Vt as civilUs, W as range, X as smallDecimalNumber, Xt as weekday, Y as smallCoefficient, Yt as parseInstantText, Z as smallExponent, Zt as assertScalarText, _ as concatText, _t as decOf, an as simpleFold, at as fromBase, b as displayText, bt as div, ct as parseUnit, d as bytes, dt as toBase, en as generalCategory, et as text, f as bytesOf, fn as unitKinds, ft as unitEntry, g as compareBytes, gt as compareDec, h as civilOf, ht as add, in as scalarCount, it as combine, j as listWithItem, jt as withinLimits, k as list, kt as roundRatio, l as Value, lt as powerOf, mt as ArithmeticError, nn as lower, nt as trimWhiteSpace, o as invalidValue, on as upper, ot as musicalKind, p as canonicalNumber, pt as unitText, qt as parseCivil, rn as normalizeNFC, rt as UnitError, st as ownUnit, t as HostError, tn as isWhiteSpace, tt as textStorage, u as bool, un as grammar, ut as sameDimension, v as dec, vt as digitCount$1, wt as isInteger, x as extendList, xt as divide, y as decimalParts, yt as digitsOf, zt as civilOfDays } from "./errors-P3ga1I-9.js";
3
3
  //#region src/tasks.ts
4
4
  const runTask = (root) => {
5
5
  const stack = [root];
@@ -1152,9 +1152,9 @@ const checkMetering = (op) => {
1152
1152
  * Define a Capability whose Host functions take and return Values. The
1153
1153
  * standard Capabilities and replay Stubs use this form.
1154
1154
  */
1155
- const defineValueCapability = (name, ops, lifecycle, release) => {
1155
+ const defineValueCapability = (name, ops, lifecycle, release, reserved) => {
1156
1156
  if (release !== void 0 && typeof release !== "function") invalidValue("A release hook must be a function");
1157
- for (const op of Object.keys(ops)) if (refusedNames.has(op)) throw new HostError("invalid value", `${op} can't name an Operation`);
1157
+ for (const op of Object.keys(ops)) if (refusedNames.has(op) && !(reserved && op === "wait")) throw new HostError("invalid value", `${op} can't name an Operation`);
1158
1158
  const coordinated = !!lifecycle && typeof lifecycle === "object" && "coordinator" in lifecycle ? lifecycle : void 0;
1159
1159
  if (coordinated && typeof coordinated.coordinator !== "function") invalidValue("A coordinator mapping must be a function");
1160
1160
  if (lifecycle !== void 0 && !coordinated && !hasHooks(lifecycle)) invalidValue("A participant requires synchronous begin, commit and rollback hooks");
@@ -1163,7 +1163,7 @@ const defineValueCapability = (name, ops, lifecycle, release) => {
1163
1163
  const scopeEffects = /* @__PURE__ */ new Map();
1164
1164
  for (const [opName, op] of Object.entries(ops)) {
1165
1165
  if (op.command !== void 0 && typeof op.command !== "boolean") invalidValue("command must be Boolean");
1166
- if (op.command && RESERVED.has(opName)) invalidValue(`${opName} is a Reserved Word, so it can't be a command`);
1166
+ if (op.command && RESERVED.has(opName)) invalidValue(`\`${opName}\` is a Reserved Word, so it can't name a command`);
1167
1167
  if (op.labels !== void 0) {
1168
1168
  if (!Array.isArray(op.labels) || [...op.labels].some((label) => typeof label !== "string" || !validArgumentLabel(label))) invalidValue("labels must be a list of Argument Label words");
1169
1169
  if (op.labels.length && op.labels.length !== (op.args?.length ?? 0) - 1) invalidValue("labels must have one entry per argument after the first");
@@ -1316,6 +1316,22 @@ const defineTyped = (name, ops, lifecycle, release) => defineValueCapability(nam
1316
1316
  function defineCapability(...input) {
1317
1317
  return input.length === 0 ? defineTyped : defineTyped(...input);
1318
1318
  }
1319
+ /**
1320
+ * The Operation declarations a Library's Capability calls are checked
1321
+ * against, for `compileLibrary`'s `declarations`. Takes CapabilityDefs, keyed
1322
+ * by their names, or a map from the name each is granted under.
1323
+ */
1324
+ const operationDeclarations = (capabilities) => {
1325
+ const entries = typeof capabilities.get === "function" ? capabilities : [...capabilities].map((c) => [c.name, c]);
1326
+ const declarations = Object.create(null);
1327
+ for (const [name, capability] of entries) declarations[name] = Object.fromEntries([...capability.operations].map(([operation, op]) => [operation, {
1328
+ args: op.args ?? [],
1329
+ mode: op.mode,
1330
+ ...op.labels?.length ? { labels: op.labels } : {},
1331
+ ...op.command ? { command: true } : {}
1332
+ }]));
1333
+ return declarations;
1334
+ };
1319
1335
  //#endregion
1320
1336
  //#region src/generated/machine.ts
1321
1337
  const instructions = [
@@ -2603,10 +2619,13 @@ const errorMessages = {
2603
2619
  "not read-only": "A query must not change the database",
2604
2620
  "too many rows": "The statement gave more than {max} rows",
2605
2621
  "unrepresentable": "The value in {column} can't be represented",
2622
+ "no musical time": "This Host keeps no musical time",
2606
2623
  "user busy": "Another prompt is waiting for an answer",
2607
2624
  "invalid serve": "A Serve Registration's {field} isn't valid",
2608
2625
  "address in use": "That address is already in use",
2609
2626
  "bad address": "That address isn't allowed",
2627
+ "name in use": "That name is already exposed",
2628
+ "not exposed": "No Script is exposed under that name",
2610
2629
  "invalid response": "The response's {field} isn't valid",
2611
2630
  "already responded": "That HTTP request has already been answered",
2612
2631
  "exchange closed": "The client has gone",
@@ -7370,11 +7389,11 @@ const comparison = (op, a, b, fold) => {
7370
7389
  scanned
7371
7390
  };
7372
7391
  }
7373
- const x = smallOf(a);
7374
- const y = smallOf(b);
7392
+ const x = smallCoefficientOf(a);
7393
+ const y = smallCoefficientOf(b);
7375
7394
  let scanned = 0;
7376
7395
  let o;
7377
- if (!Number.isNaN(x) && !Number.isNaN(y)) o = x < y ? -1 : x > y ? 1 : 0;
7396
+ if (!Number.isNaN(x) && !Number.isNaN(y) && exponentOf(a) === exponentOf(b)) o = x < y ? -1 : x > y ? 1 : 0;
7378
7397
  else {
7379
7398
  const comparer = new Comparer(fold);
7380
7399
  scanned = comparer.scanned(a, b);
@@ -7514,6 +7533,18 @@ const waitUs = (v) => {
7514
7533
  ]);
7515
7534
  return durationUs(q);
7516
7535
  };
7536
+ /**
7537
+ * `wait q`'s count when `q` is in a Musical Unit (chapter 5, `wait` in
7538
+ * Musical Units): a whole number, 0 or more, or `out of domain`. Undefined
7539
+ * for any other value, which waits as an exact duration.
7540
+ */
7541
+ const musicalCount = (v) => {
7542
+ const q = v.asQuantityRef();
7543
+ if (!q || !musicalKind(q.unit)) return;
7544
+ const n = numberOf(q);
7545
+ if (!isInteger(n) || n.negative && n.coefficient !== 0n) throw outOfDomain("wait", v);
7546
+ return integerOf(n);
7547
+ };
7517
7548
  const secondsOf = (us) => {
7518
7549
  let d = {
7519
7550
  negative: us < 0n,
@@ -7556,19 +7587,46 @@ const dateArithmetic = (op, a, b) => {
7556
7587
  if (us % US_PER_DAY !== 0n) throw incompatible(DAYS, q.unit);
7557
7588
  return inRangeDate(() => civilOf(civilOfDays(civilDays(c) + us / US_PER_DAY, null)));
7558
7589
  };
7590
+ const MIN_EXPONENT = -6176;
7559
7591
  /**
7560
- * Add, subtract or multiply two small integers (see `smallInteger`), or
7561
- * undefined when either isn't one or the result isn't a safe integer. The
7562
- * exact result needs no rounding, so it equals the Decimal path's.
7592
+ * Add, subtract or multiply two small Decimals: safe-integer coefficients x
7593
+ * and y with exponents ex and ey (see `smallCoefficient`). Undefined when
7594
+ * either isn't one, when adding or subtracting unequal exponents, or when the
7595
+ * result's coefficient isn't a safe integer or its exponent is out of range.
7596
+ * Such a result is exact and at the ideal exponent, so it equals the Decimal
7597
+ * path's.
7563
7598
  */
7564
- const smallArithmetic = (op, x, y) => {
7565
- const r = op === "add" ? x + y : op === "subtract" ? x - y : op === "multiply" ? x * y : NaN;
7566
- return Number.isSafeInteger(r) ? smallNumber(r) : void 0;
7599
+ const smallArithmetic = (op, x, ex, y, ey) => {
7600
+ let r;
7601
+ let e = ex;
7602
+ if (op === "multiply") {
7603
+ r = x * y;
7604
+ e = ex + ey;
7605
+ if (e < MIN_EXPONENT) return;
7606
+ } else if (op === "divide") return smallQuotient(x, ex, y, ey);
7607
+ else if (ex !== ey) return;
7608
+ else r = op === "add" ? x + y : op === "subtract" ? x - y : NaN;
7609
+ return Number.isSafeInteger(r) ? smallDecimalNumber(r, e) : void 0;
7610
+ };
7611
+ const smallQuotient = (x, ex, y, ey) => {
7612
+ if (y === 0 || Number.isNaN(x) || Number.isNaN(y)) return;
7613
+ let n = x;
7614
+ let e = ex - ey;
7615
+ for (; e > 0; e--) n *= 10;
7616
+ while (Number.isSafeInteger(n) && e >= MIN_EXPONENT) {
7617
+ if (n % y === 0) return smallDecimalNumber(n / y, e);
7618
+ n *= 10;
7619
+ e--;
7620
+ }
7567
7621
  };
7568
7622
  /** A number Value's small integer, or NaN. */
7569
7623
  const smallOf = (v) => v.kind === "number" ? smallInteger(v.asDecimal()) : NaN;
7624
+ /** A number Value's small coefficient (see `smallCoefficient`), or NaN. */
7625
+ const smallCoefficientOf = (v) => v.kind === "number" ? smallCoefficient(v.asDecimal()) : NaN;
7626
+ /** A number Value's exponent, or 0 for another kind. */
7627
+ const exponentOf = (v) => v.kind === "number" ? smallExponent(v.asDecimal()) : 0;
7570
7628
  const arithmetic = (op, a, b) => {
7571
- const small = smallArithmetic(op, smallOf(a), smallOf(b));
7629
+ const small = smallArithmetic(op, smallCoefficientOf(a), exponentOf(a), smallCoefficientOf(b), exponentOf(b));
7572
7630
  if (small) return small;
7573
7631
  if (isDate(a) || isDate(b)) try {
7574
7632
  return dateArithmetic(op, a, b);
@@ -8689,4 +8747,4 @@ const builtinDefaults = {
8689
8747
  toFloat32: [text("big")]
8690
8748
  };
8691
8749
  //#endregion
8692
- export { disassemble as $, negated as A, subjectText as B, isKind as C, validMessageSelector as Ct, matchCaptures as D, runTask as Dt, makeRange as E, RESERVED as Et, search as F, charge as G, waitUs as H, setKey as I, partSize as J, fixedRates as K, smallArithmetic as L, prepareConversion as M, property as N, matchesOf as O, randomBound as P, arityOf as Q, smallOf as R, isEmpty as S, validComputedMessageName as St, makePatternValue as T, Lexer as Tt, wrongKind as U, textForm as V, cacheBuild as W, resetMeasured as X, rateOf as Y, sizeOf as Z, deleteKey as _, defineCapability as _t, builtin as a, patternSource as at, hasKey as b, mismatch as bt, canConvert as c, textDisplay as ct, chunkSet as d, errorMessages as dt, functionHead as et, chunkThere as f, languageVersion as ft, decodeUtf8 as g, acceptsArgumentCount as gt, convert as h, LimitReached as ht, arithmetic as i, numberText as it, outOfRange as j, member as k, chunkDelete as l, compareText as lt, concat as m, reservedErrorKeys as mt, ScriptError as n, opcodes as nt, builtinDefaults as o, quantityText as ot, comparison as p, limitDefaults as pt, keysContents as q, appendTo as r, capturesOf$1 as rt, byteOf as s, splicesOf as st, NotImplementedError as t, instructionSpec as tt, chunkGet as u, costModel as ut, equals as v, defineValueCapability as vt, keyText as w, validStaticMessageName as wt, integerValue as x, shape as xt, getKey as y, expectedOf as yt, splice as z };
8750
+ export { arityOf as $, musicalCount as A, Lexer as At, splice as B, isKind as C, mismatch as Ct, matchCaptures as D, validComputedMessageName as Dt, makeRange as E, shapeDiagnostics as Et, randomBound as F, cacheBuild as G, textForm as H, search as I, keysContents as J, charge as K, setKey as L, outOfRange as M, runTask as Mt, prepareConversion as N, matchesOf as O, validMessageSelector as Ot, property as P, sizeOf as Q, smallArithmetic as R, isEmpty as S, expectedOf as St, makePatternValue as T, shape as Tt, waitUs as U, subjectText as V, wrongKind as W, rateOf as X, partSize as Y, resetMeasured as Z, deleteKey as _, acceptsArgumentCount as _t, builtin as a, numberText as at, hasKey as b, defineValueCapability as bt, canConvert as c, splicesOf as ct, chunkSet as d, costModel as dt, disassemble as et, chunkThere as f, errorMessages as ft, decodeUtf8 as g, LimitReached as gt, convert as h, reservedErrorKeys as ht, arithmetic as i, capturesOf$1 as it, negated as j, RESERVED as jt, member as k, validStaticMessageName as kt, chunkDelete as l, textDisplay as lt, concat as m, limitDefaults as mt, ScriptError as n, instructionSpec as nt, builtinDefaults as o, patternSource as ot, comparison as p, languageVersion as pt, fixedRates as q, appendTo as r, opcodes as rt, byteOf as s, quantityText as st, NotImplementedError as t, functionHead as tt, chunkGet as u, compareText as ut, equals as v, decodeShape as vt, keyText as w, operationDeclarations as wt, integerValue as x, diagnosticRecord as xt, getKey as y, defineCapability as yt, smallCoefficientOf as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@northtalk/ts",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "NorthTalk, a readable scripting language for embedding: the TS Core, its Session Host and Standard Capabilities.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -65,6 +65,10 @@
65
65
  "types": "./message-layer.d.ts",
66
66
  "default": "./message-layer.js"
67
67
  },
68
+ "./peer": {
69
+ "types": "./peer.d.ts",
70
+ "default": "./peer.js"
71
+ },
68
72
  "./session": {
69
73
  "types": "./session.d.ts",
70
74
  "default": "./session.js"
@@ -0,0 +1,149 @@
1
+
2
+ import { A as listValues, L as nothing, et as text, t as HostError, v as dec } from "./errors-P3ga1I-9.js";
3
+ import { t as defineObjectKind } from "./objects-DE6kRk0r.js";
4
+ import { Dt as validComputedMessageName, Tt as shape, bt as defineValueCapability, n as ScriptError } from "./operations-CGjDlkGU.js";
5
+ import { c as fixed, f as registerStandardChecks, s as costOf } from "./encoding-BL2ECJmg.js";
6
+ //#region src/peer-capability.ts
7
+ /** The Core-fixed Object Kind of a Peer: no properties, no collection. */
8
+ const PEER_KIND = "peer";
9
+ const peerKind = defineObjectKind({
10
+ name: PEER_KIND,
11
+ props: {}
12
+ });
13
+ const itemsOf = (list) => Array.from({ length: list.length }, (_, i) => list.index(i + 1));
14
+ const OPERATIONS = [
15
+ "expose",
16
+ "unexpose",
17
+ "reach",
18
+ "post",
19
+ "call",
20
+ "caller"
21
+ ];
22
+ /** The Operations `send` uses: `post` for a plain one, `call` with `and wait`. */
23
+ const PEER_POST = "post";
24
+ const PEER_CALL = "call";
25
+ const peerShape = {
26
+ k: "object",
27
+ kind: PEER_KIND
28
+ };
29
+ const argsShape = shape.listOf(shape.any);
30
+ const outOfDomain = (fn, value) => new ScriptError("out of domain", [["function", text(fn)], ["value", value]], true);
31
+ /** Whether a value is a Peer: a Host Object of the Core's kind `peer`. */
32
+ const isPeer = (v) => v.kind === "object" && v.asObjectRef()?.kind === "peer";
33
+ const strayObject = (v, path) => {
34
+ if (v.kind === "object") return isPeer(v) ? null : path;
35
+ if (v.kind === "list") for (let i = 1; i <= v.length; i++) {
36
+ const found = strayObject(v.index(i), [...path, i]);
37
+ if (found) return found;
38
+ }
39
+ if (v.kind === "map") for (const [key, item] of v.entries()) {
40
+ const found = strayObject(item, [...path, key]);
41
+ if (found) return found;
42
+ }
43
+ return null;
44
+ };
45
+ /**
46
+ * A Remote Send's arguments, checked as the `post` and `call` Operations
47
+ * check them, after their Shapes: a Selector a computed `send` could use,
48
+ * then no Host Object other than a Peer at any depth (chapter 5, Remote
49
+ * Sends). `path` counts from the Operation's arguments.
50
+ */
51
+ const checkRemoteSend = (args) => {
52
+ const message = args[1];
53
+ const sent = args[2];
54
+ if (!validComputedMessageName(message.asText(), sent.length)) throw new ScriptError("bad message name", [["name", message], ["arguments", dec(String(sent.length))]], true);
55
+ const path = strayObject(sent, [3]);
56
+ if (path) throw new ScriptError("not encodable", [["kind", text("object")], ["path", listValues(path.map(keyValue))]], true);
57
+ };
58
+ const keyValue = (k) => typeof k === "number" ? dec(String(k)) : text(k);
59
+ const nonEmpty = (fn, v) => {
60
+ if (v?.kind === "text" && v.asText() === "") throw outOfDomain(fn, v);
61
+ };
62
+ /**
63
+ * Optional for Hosts. The binding is the Host's own description of the
64
+ * names the Grant may `reach` and `expose`; the Core never reads it.
65
+ */
66
+ const peerCapability = (impl, costs) => {
67
+ for (const name of OPERATIONS) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Peer needs ${name}`);
68
+ const operations = {
69
+ expose: {
70
+ mode: "suspending",
71
+ args: [shape.optional(shape.text)],
72
+ result: peerShape,
73
+ errors: [{ code: "bad address" }, { code: "name in use" }],
74
+ cost: costOf(costs, "expose"),
75
+ start: (call, name) => name?.kind === "text" ? impl.expose(call, name.asText()) : impl.expose(call)
76
+ },
77
+ unexpose: {
78
+ mode: "immediate",
79
+ args: [shape.oneOf(shape.text, peerShape)],
80
+ result: shape.nothing,
81
+ errors: [],
82
+ cost: costOf(costs, "unexpose"),
83
+ do: (call, exposure) => {
84
+ impl.unexpose(call, exposure.kind === "text" ? exposure.asText() : exposure.asObject());
85
+ return nothing;
86
+ }
87
+ },
88
+ reach: {
89
+ mode: "suspending",
90
+ args: [shape.text],
91
+ result: peerShape,
92
+ errors: [{ code: "bad address" }, { code: "not exposed" }],
93
+ cost: costOf(costs, "reach"),
94
+ start: (call, address) => impl.reach(call, address.asText())
95
+ },
96
+ post: {
97
+ mode: "fire-and-forget",
98
+ args: [
99
+ peerShape,
100
+ shape.text,
101
+ argsShape
102
+ ],
103
+ errors: [],
104
+ cost: costOf(costs, "post"),
105
+ fire: (call, peer, message, args) => impl.post(call, peer.asObject(), message.asText(), itemsOf(args))
106
+ },
107
+ call: {
108
+ mode: "suspending",
109
+ args: [
110
+ peerShape,
111
+ shape.text,
112
+ argsShape
113
+ ],
114
+ result: shape.any,
115
+ errors: [{
116
+ code: "send failed",
117
+ fields: {
118
+ reason: shape.text,
119
+ error: {
120
+ optional: true,
121
+ shape: shape.any
122
+ }
123
+ }
124
+ }],
125
+ cost: costOf(costs, "call"),
126
+ start: (call, peer, message, args) => impl.call(call, peer.asObject(), message.asText(), itemsOf(args))
127
+ },
128
+ caller: {
129
+ mode: "immediate",
130
+ args: [],
131
+ result: shape.any,
132
+ errors: [],
133
+ cost: costOf(costs, "caller"),
134
+ do: (call) => impl.caller(call)
135
+ }
136
+ };
137
+ const hostErrors = {
138
+ expose: ["bad address", "name in use"],
139
+ reach: ["bad address", "not exposed"],
140
+ call: ["send failed"]
141
+ };
142
+ for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
143
+ error: (code) => hostErrors[name]?.includes(code) ?? false,
144
+ ...name === "expose" || name === "reach" || name === "unexpose" ? { arguments: (args) => nonEmpty(name, args[0]) } : name === "post" || name === "call" ? { arguments: checkRemoteSend } : {}
145
+ });
146
+ return fixed(defineValueCapability("peer", operations));
147
+ };
148
+ //#endregion
149
+ export { peerKind as a, peerCapability as i, PEER_KIND as n, PEER_POST as r, PEER_CALL as t };
package/peer.d.ts ADDED
@@ -0,0 +1,173 @@
1
+ /// <reference lib="esnext.disposable" />
2
+ import { J as Value, P as TsGroup, rn as PeerImpl } from "./debug-C_Ob5rkl.js";
3
+ //#region src/peer-message-port.d.ts
4
+ /** What the link needs of a `MessagePort`, a `Worker` or a worker's `self`. */
5
+ type PortEndpoint = {
6
+ addEventListener(type: string, listener: (event: MessageEvent) => void): void;
7
+ postMessage(message: unknown): void;
8
+ removeEventListener(type: string, listener: (event: MessageEvent) => void): void;
9
+ };
10
+ type MessagePortLinkOptions = {
11
+ /**
12
+ * The other end's name: `reach` uses it as the address, and it joins the
13
+ * Caller Identity.
14
+ */
15
+ name?: string;
16
+ };
17
+ /**
18
+ * A link to the Host at the other end of a `MessagePort`, or of a `Worker`
19
+ * from the page, or of the page from a worker's `self`. Closing a port ends
20
+ * the link at both ends. A worker that is terminated sends no word, so the
21
+ * page closes the link itself, as `WorkerSupervisor.closeOnTerminate` does.
22
+ */
23
+ export declare const messagePortLink: (port: PortEndpoint, options?: MessagePortLinkOptions) => PeerLink;
24
+ //#endregion
25
+ //#region src/peer-websocket.d.ts
26
+ /** What the link needs of a WHATWG `WebSocket`, or of a server's socket adapted to one. */
27
+ type WebSocketEndpoint = {
28
+ addEventListener(type: string, listener: (event: Event) => void): void;
29
+ close(code?: number, reason?: string): void;
30
+ /** 0 while connecting, 1 when open, 2 closing, 3 closed. */
31
+ readonly readyState: number;
32
+ removeEventListener(type: string, listener: (event: Event) => void): void;
33
+ send(data: string): void;
34
+ /** The address dialled, whose origin joins the Caller Identity. */
35
+ readonly url?: string;
36
+ };
37
+ type WebSocketLinkOptions = {
38
+ /** The name `reach` finds this link by, as for a MessagePort link. */
39
+ name?: string;
40
+ /**
41
+ * The server's key fingerprint, checked against the key it proves. An
42
+ * address `wss://HOST/PATH#FINGERPRINT` pins it too.
43
+ */
44
+ pin?: string;
45
+ /** Sent in the `hello` for the server's `authenticate`. */
46
+ token?: string;
47
+ };
48
+ /** Caller Identity data, merged into `{key, via: "ws"}`. */
49
+ type WebSocketCaller = Readonly<Record<string, Value | string>>;
50
+ type AcceptWebSocketOptions = {
51
+ /**
52
+ * Checks the `hello`'s token, undefined when it has none: the data it gives
53
+ * joins the Caller Identity, and undefined or a throw refuses the
54
+ * connection, which closes before any Remote Send.
55
+ */
56
+ authenticate?: (token: string | undefined) => WebSocketCaller | undefined | Promise<WebSocketCaller | undefined>;
57
+ /** The name `reach` finds this link by. */
58
+ name?: string;
59
+ };
60
+ /**
61
+ * A link to the server at the other end of a WebSocket the caller opened,
62
+ * as a browser does. The server's key is proved, and checked against the
63
+ * pin when one is given.
64
+ */
65
+ export declare const webSocketLink: (socket: WebSocketEndpoint, options?: WebSocketLinkOptions) => PeerLink;
66
+ /**
67
+ * A link to the Host that opened a WebSocket to this server, from the
68
+ * server's socket adapted to a `WebSocketEndpoint`. The other key is proved,
69
+ * and `authenticate` checks the token before any Remote Send arrives.
70
+ */
71
+ export declare const acceptWebSocket: (socket: WebSocketEndpoint, options?: AcceptWebSocketOptions) => PeerLink;
72
+ //#endregion
73
+ //#region src/peer.d.ts
74
+ /**
75
+ * What a link tells the router: each whole frame it receives, its close, and
76
+ * when it has learned the other Host's key, for a link that starts without it.
77
+ */
78
+ export type PeerLinkEvents = {
79
+ close(): void;
80
+ frame(text: string): void;
81
+ keyed(): void;
82
+ };
83
+ /**
84
+ * One connection to another Host. It moves whole frames, each the Value
85
+ * Encoding's JSON text, and says who the other Host is. A link hands the
86
+ * router frames only once `open` gives it somewhere to put them.
87
+ */
88
+ export type PeerLink = {
89
+ /** The address `reach` names this link by, such as a port's name. */
90
+ readonly address?: string;
91
+ close(): void;
92
+ /** Whether the link has closed: it sends nothing more. */
93
+ readonly closed: boolean;
94
+ /**
95
+ * The Caller Identity data for what arrives on this link: what this Host
96
+ * vouches for about the other one, or Nothing when it vouches for nobody.
97
+ */
98
+ readonly identity: Value;
99
+ /**
100
+ * The other Host's key fingerprint, or empty until the link learns it and
101
+ * calls `keyed`. It hands the router no frame before then.
102
+ */
103
+ readonly key: string;
104
+ /**
105
+ * Starts the link; `own` is this Host's key, for a link that sends it, and
106
+ * `signer` proves it, for a link that must.
107
+ */
108
+ open(events: PeerLinkEvents, own: string, signer?: HostSigner): void;
109
+ /** Sends one frame; false when it can't, as when closed or too large. */
110
+ send(frame: string): boolean;
111
+ };
112
+ /**
113
+ * What proves a Host holds its key: the key's DER SubjectPublicKeyInfo, and
114
+ * its ECDSA P-256 SHA-256 signature over some bytes, as the 64 bytes of `r`
115
+ * then `s`, as WebCrypto gives it.
116
+ */
117
+ export type HostSigner = {
118
+ sign(data: Uint8Array): Promise<Uint8Array>;
119
+ readonly spki: Uint8Array;
120
+ };
121
+ export type PeerRouterOptions = {
122
+ /** For a Peer naming a key with no open link: the address that dials it. */
123
+ addressOf?: (key: string) => string | undefined;
124
+ /** A link to the Host an address names, for `reach`; undefined when none. */
125
+ dial?: (address: string) => Promise<PeerLink | undefined>;
126
+ /** This Host's key fingerprint. */
127
+ key: string;
128
+ /** Proves this Host holds that key, for a link that asks, as a WebSocket does. */
129
+ signer?: HostSigner;
130
+ };
131
+ /** A key fingerprint: lowercase hex SHA-256 of the DER SubjectPublicKeyInfo. */
132
+ export declare const fingerprintOf: (spki: BufferSource) => Promise<string>;
133
+ /** A new ECDSA P-256 Host key and its fingerprint. */
134
+ export declare const newHostKey: () => Promise<{
135
+ fingerprint: string;
136
+ keys: CryptoKeyPair;
137
+ signer: HostSigner;
138
+ }>;
139
+ /** A Host's side of `peer`: its exposures and the links to other Hosts. */
140
+ export declare class PeerRouter {
141
+ private readonly o;
142
+ readonly key: string;
143
+ private group;
144
+ private readonly exposures;
145
+ private readonly names;
146
+ private readonly peers;
147
+ private readonly wires;
148
+ private readonly byKey;
149
+ private readonly callers;
150
+ constructor(o: PeerRouterOptions);
151
+ /** A router for the Group, with a new Host key unless the options give one. */
152
+ static create(group: TsGroup, options?: Partial<PeerRouterOptions>): Promise<PeerRouter>;
153
+ /** Gives the router its Group, whose Scripts its exposures name. */
154
+ bind(group: TsGroup): void;
155
+ /** Carries Remote Sends over a link. The newest link to a key carries what this Host sends there. */
156
+ connect(link: PeerLink): void;
157
+ /** Closes every link. */
158
+ close(): void;
159
+ private wireFor;
160
+ /** A link to the Host with this key, dialled if the Host knows its address. */
161
+ private wireTo;
162
+ /** This Group's one Peer for an exposure id. */
163
+ private peerFor;
164
+ private local;
165
+ private arrive;
166
+ /** The `peerCapability` implementation. */
167
+ readonly impl: PeerImpl;
168
+ private expose;
169
+ private reach;
170
+ private send;
171
+ }
172
+ //#endregion
173
+ export type { AcceptWebSocketOptions, MessagePortLinkOptions, PortEndpoint, WebSocketEndpoint, WebSocketLinkOptions };