@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
@@ -1,6 +1,121 @@
1
- import { E as listValues, M as num, V as text, a as invalidValue, c as bool, h as dec, i as ScriptError, j as nothing, k as map, l as bytes, ot as characterBoundaries, t as HostError, ut as normalizeNFC, z as requireValue } from "./errors-DHwz1Vho.js";
2
- import { ft as errorMessages, r as registerStandardChecks, u as ScriptError$1, vt as defineCapability, xt as shape, yt as expectedOf } from "./encoding-DWlbPq-e.js";
3
- import { c as fixed, s as costOf } from "./store-capability-CDoVafZL.js";
1
+
2
+ import { E as isDecimal, F as num, H as requireValue, K as text, M as map, Ot as integerOf, P as nothing, V as record, _ as dec, d as bytes, dt as characterBoundaries, ht as normalizeNFC, i as ScriptError, k as listValues, kt as isInteger, l as Value, o as invalidValue, t as HostError, u as bool, v as decimalParts } from "./errors-LYJZ_c8h.js";
3
+ import { a as defineValueCapability, f as validComputedMessageName, s as expectedOf, u as shape } from "./capabilities-CH0FkRMq.js";
4
+ import { i as ScriptError$1, lt as errorMessages } from "./base64-DORMd3Hv.js";
5
+ import { r as registerStandardChecks } from "./encoding-nlrpj-Pb.js";
6
+ import { c as fixed, s as costOf } from "./store-capability-OZp4hXmj.js";
7
+ //#region src/talk.ts
8
+ const blank = /^[\t ]*$/;
9
+ const commonPrefix = (a, b) => {
10
+ let i = 0;
11
+ while (i < a.length && i < b.length && a[i] === b[i]) i++;
12
+ return a.slice(0, i);
13
+ };
14
+ /**
15
+ * Dedents NorthTalk source; rejects JS interpolation.
16
+ *
17
+ * Write NorthTalk's own interpolation as `\${…}` and its backticks as `` \` ``.
18
+ * Pass values as Request arguments instead of splicing them into source. The
19
+ * longest whitespace prefix shared by every non-blank line is removed, compared
20
+ * exactly, so tabs and spaces never match each other.
21
+ */
22
+ const talk = (strings, ...values) => {
23
+ if (values.length > 0) throw new TypeError("talk source cannot interpolate JS values; write NorthTalk interpolation as \\${…} or pass the value as a Request argument");
24
+ const lines = strings.raw[0].replaceAll(/\\([\S\s])/g, (escape, c) => c === "`" || c === "$" ? c : escape).split("\n");
25
+ if (lines.length > 1 && blank.test(lines[0])) lines.shift();
26
+ if (lines.length > 1 && blank.test(lines.at(-1))) lines.pop();
27
+ let margin;
28
+ for (const line of lines) {
29
+ if (blank.test(line)) continue;
30
+ const indent = /^[\t ]*/.exec(line)[0];
31
+ margin = margin === void 0 ? indent : commonPrefix(margin, indent);
32
+ }
33
+ return lines.map((line) => blank.test(line) ? "" : line.slice(margin.length)).join("\n");
34
+ };
35
+ //#endregion
36
+ //#region src/plain.ts
37
+ const tagOf = (input) => Object.prototype.toString.call(input);
38
+ const isPlainObject = (input) => [null, Object.prototype].includes(Object.getPrototypeOf(input));
39
+ /**
40
+ * Plain JS data to a Value by the named constructors (ADR 0119). Anything
41
+ * the table doesn't name, and cyclic data, throws `invalid value`.
42
+ */
43
+ const toValue = (plain, options = {}) => {
44
+ const decimalNumbers = options.numbers === "decimal";
45
+ const open = /* @__PURE__ */ new Set();
46
+ const convert = (input) => {
47
+ switch (typeof input) {
48
+ case "undefined": return nothing;
49
+ case "boolean": return bool(input);
50
+ case "string": return text(input);
51
+ case "bigint": return num(input);
52
+ case "number": return decimalNumbers ? num(input) : invalidValue("A JS number needs { numbers: 'decimal' }, or num() or dec()");
53
+ case "object": break;
54
+ default: return invalidValue(`Not plain data: ${typeof input}`);
55
+ }
56
+ if (input === null) return nothing;
57
+ if (Value.isValue(input)) return input;
58
+ if (isDecimal(input)) return dec(input.toString());
59
+ if (tagOf(input) === "[object Uint8Array]") return bytes(input);
60
+ if (open.has(input)) return invalidValue("Cyclic data has no Value");
61
+ open.add(input);
62
+ let result;
63
+ if (Array.isArray(input)) {
64
+ const items = [];
65
+ for (let i = 0; i < input.length; i++) items.push(convert(input[i]));
66
+ result = listValues(items);
67
+ } else if (tagOf(input) === "[object Map]") result = map(Array.from(input, ([k, v]) => {
68
+ if (typeof k !== "string") invalidValue("Map keys must be text");
69
+ return [k, convert(v)];
70
+ }));
71
+ else if (isPlainObject(input)) {
72
+ const fields = Object.create(null);
73
+ for (const [k, v] of Object.entries(input)) Object.defineProperty(fields, k, {
74
+ value: convert(v),
75
+ enumerable: true
76
+ });
77
+ result = record(fields);
78
+ } else return invalidValue(`Not plain data: ${input.constructor?.name ?? "object"}`);
79
+ open.delete(input);
80
+ return result;
81
+ };
82
+ return convert(plain);
83
+ };
84
+ /** A Value as plain JS data (ADR 0119); kinds with no JS form stay Values. */
85
+ const fromValue = (v, options = {}) => {
86
+ if (!Value.isValue(v)) invalidValue("Expected a Value from a named constructor");
87
+ const convert = (value) => {
88
+ switch (value.kind) {
89
+ case "nothing": return null;
90
+ case "boolean": return value.asBool();
91
+ case "text": return value.asText();
92
+ case "number": {
93
+ const d = value.asDecimal();
94
+ return options.numbers === "string" ? d.toString() : d;
95
+ }
96
+ case "bytes": return value.asBytes();
97
+ case "list": {
98
+ const items = [];
99
+ for (let i = 1; i <= value.length; i++) items.push(convert(value.index(i)));
100
+ return items;
101
+ }
102
+ case "map": {
103
+ if (options.maps === "map") return new Map(value.entries().map(([k, x]) => [k, convert(x)]));
104
+ const fields = {};
105
+ for (const [k, x] of value.entries()) Object.defineProperty(fields, k, {
106
+ value: convert(x),
107
+ enumerable: true,
108
+ writable: true,
109
+ configurable: true
110
+ });
111
+ return fields;
112
+ }
113
+ default: return value;
114
+ }
115
+ };
116
+ return convert(v);
117
+ };
118
+ //#endregion
4
119
  //#region src/json.ts
5
120
  var JsonReader = class {
6
121
  source;
@@ -461,7 +576,7 @@ const sqliteCapability = (impl, costs, perRow) => {
461
576
  commit: scoped("commit", { closes: "transaction" }, []),
462
577
  rollback: scoped("rollback", { closes: "transaction" }, [])
463
578
  };
464
- const capability = defineCapability("sqlite", operations, { coordinator: (binding) => {
579
+ const capability = defineValueCapability("sqlite", operations, { coordinator: (binding) => {
465
580
  checkBinding(binding);
466
581
  return impl.coordinator(binding.database);
467
582
  } });
@@ -475,4 +590,139 @@ const sqliteCapability = (impl, costs, perRow) => {
475
590
  return fixed(capability);
476
591
  };
477
592
  //#endregion
478
- export { decodeJson as n, encodeJson as r, sqliteCapability as t };
593
+ //#region src/http-capability.ts
594
+ /** A `serve` waits as long as `console`'s `read`. */
595
+ const HTTP_MAX_PENDING_MS = 2147483647;
596
+ const exchangeShape = {
597
+ k: "object",
598
+ kind: "httpExchange"
599
+ };
600
+ const optional = (s) => ({
601
+ optional: true,
602
+ shape: s
603
+ });
604
+ const responseShape = shape.map({
605
+ status: optional(shape.number),
606
+ headers: optional(shape.openMap({})),
607
+ body: optional(shape.oneOf(shape.text, shape.bytes)),
608
+ json: optional(shape.any)
609
+ });
610
+ const optionsShape = shape.optional(shape.map({
611
+ host: optional(shape.text),
612
+ port: optional(shape.number)
613
+ }));
614
+ const addressShape = shape.map({
615
+ host: shape.text,
616
+ port: shape.number
617
+ });
618
+ const whole = (value) => {
619
+ const parts = value?.kind === "number" ? decimalParts(value.asDecimal()) : void 0;
620
+ return parts && isInteger(parts) ? integerOf(parts) : void 0;
621
+ };
622
+ const given = (m, key) => m.entries().find(([k]) => k === key)?.[1];
623
+ const effectiveMessage = (args) => args[2]?.asText() ?? "httpRequest";
624
+ const invalid = (code, field) => new ScriptError$1(code, [["field", text(field)]], true);
625
+ const checkServe = (args, serving) => {
626
+ if (args[0].asText() === "") throw invalid("invalid serve", "name");
627
+ if (!serving) return;
628
+ if (!args[1].asText().startsWith("/")) throw invalid("invalid serve", "prefix");
629
+ const message = effectiveMessage(args);
630
+ if (message.includes(":") || !validComputedMessageName(message, 1)) throw invalid("invalid serve", "message");
631
+ };
632
+ const checkResponse = (response) => {
633
+ const status = given(response, "status");
634
+ if (status) {
635
+ const n = whole(status);
636
+ if (n === void 0 || n < 100n || n > 599n) throw invalid("invalid response", "status");
637
+ }
638
+ const headers = given(response, "headers");
639
+ if (headers?.kind === "map") {
640
+ for (const [, value] of headers.entries()) if (!(value.kind === "text" || value.kind === "list" && Array.from({ length: value.length }, (_, i) => value.index(i + 1).kind).every((kind) => kind === "text"))) throw invalid("invalid response", "headers");
641
+ }
642
+ const json = given(response, "json");
643
+ if (json) {
644
+ if (given(response, "body")) throw invalid("invalid response", "json");
645
+ jsonText(json);
646
+ }
647
+ };
648
+ const jsonText = (json) => {
649
+ try {
650
+ return encodeJson(json);
651
+ } catch {
652
+ throw invalid("invalid response", "json");
653
+ }
654
+ };
655
+ const resolvedResponse = (response) => {
656
+ if (!given(response, "json")) return response;
657
+ return map(response.entries().map(([k, v]) => [k, k === "json" ? text(jsonText(v)) : v]));
658
+ };
659
+ /** Optional for Hosts. The binding is the Host's own description of the addresses a Grant may listen on. */
660
+ const httpCapability = (impl, costs) => {
661
+ for (const name of [
662
+ "serve",
663
+ "unserve",
664
+ "respond"
665
+ ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Http needs ${name}`);
666
+ const operations = {
667
+ serve: {
668
+ mode: "suspending",
669
+ args: [
670
+ shape.text,
671
+ shape.text,
672
+ shape.optional(shape.text),
673
+ optionsShape
674
+ ],
675
+ result: addressShape,
676
+ errors: [{ code: "address in use" }, { code: "bad address" }],
677
+ maxPendingMs: HTTP_MAX_PENDING_MS,
678
+ cost: costOf(costs, "serve"),
679
+ start: (call, ...args) => impl.serve(call, args[0].asText(), args[1].asText(), effectiveMessage(args), args[3]?.kind === "map" ? args[3] : map([]))
680
+ },
681
+ unserve: {
682
+ mode: "immediate",
683
+ args: [shape.text],
684
+ result: shape.nothing,
685
+ errors: [],
686
+ cost: costOf(costs, "unserve"),
687
+ do: (call, name) => {
688
+ impl.unserve(call, name.asText());
689
+ return nothing;
690
+ }
691
+ },
692
+ respond: {
693
+ mode: "immediate",
694
+ args: [exchangeShape, responseShape],
695
+ result: shape.nothing,
696
+ errors: [
697
+ { code: "already responded" },
698
+ { code: "exchange closed" },
699
+ { code: "not owner" }
700
+ ],
701
+ cost: costOf(costs, "respond"),
702
+ do: (call, exchange, response) => {
703
+ impl.respond(call, exchange.asObject(), resolvedResponse(response));
704
+ return nothing;
705
+ }
706
+ }
707
+ };
708
+ const hostErrors = {
709
+ serve: ["address in use", "bad address"],
710
+ unserve: [],
711
+ respond: [
712
+ "already responded",
713
+ "exchange closed",
714
+ "not owner"
715
+ ]
716
+ };
717
+ for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
718
+ error: (code) => hostErrors[name].includes(code),
719
+ arguments: (args) => {
720
+ if (name === "respond") checkResponse(args[1]);
721
+ else checkServe(args, name === "serve");
722
+ },
723
+ ...name === "serve" ? { result: (answer) => answer.kind === "map" && whole(answer.get("port")) !== void 0 } : {}
724
+ });
725
+ return fixed(defineValueCapability("http", operations));
726
+ };
727
+ //#endregion
728
+ export { fromValue as a, encodeJson as i, sqliteCapability as n, toValue as o, decodeJson as r, talk as s, httpCapability as t };
package/http.d.ts ADDED
@@ -0,0 +1,59 @@
1
+
2
+ import { Jt as Group, Qt as HttpImpl, b as PumpResult, ht as ObjectKindDef, mt as ObjectKind, q as Value } from "./debug-CQBxKnJB.js";
3
+ //#region src/http/router.d.ts
4
+ /** The largest request body the router reads by default: 1 MiB. */
5
+ export declare const HTTP_DEFAULT_MAX_BODY_BYTES: number;
6
+ type HttpHostOptions = {
7
+ /**
8
+ * Whether a Grant may listen on this address, from its binding. The
9
+ * default allows any; a refusal fails `serve` with `bad address`.
10
+ */
11
+ allow?: (host: string, port: number, binding: unknown) => boolean;
12
+ /** The host a `serve` without `host` listens on: `127.0.0.1` by default. */
13
+ defaultHost?: string;
14
+ /** The port a `serve` without `port` listens on: 0, any free port, by default. */
15
+ defaultPort?: number;
16
+ /** Defines the `httpExchange` Object Kind; the TS Core's by default. Pass the Core's own for the Zig Host Adapter. */
17
+ defineObjectKind?: <N>(k: ObjectKindDef<N>) => ObjectKind<N>;
18
+ /** Told of each 500's cause and each refused Delivery. Never sent to the client. */
19
+ log?: (message: string) => void;
20
+ /** A larger request body is answered 413 without a Delivery. */
21
+ maxBodyBytes?: number;
22
+ /** When set, every `serve` listens on this port, whatever it asked for. */
23
+ portOverride?: number;
24
+ };
25
+ type HttpAddress = {
26
+ host: string;
27
+ port: number;
28
+ };
29
+ type HttpHost = {
30
+ /** Every address listening now, in the order the listeners bound. */
31
+ addresses(): HttpAddress[];
32
+ /** Stops accepting, answers every open exchange 503 and closes every listener. */
33
+ close(): Promise<void>;
34
+ /** A Group the Host discards: removes its registrations and answers its open exchanges 503. */
35
+ detach(group: Group): void;
36
+ /**
37
+ * Waits up to `ms` for the open exchanges to be answered, then answers the
38
+ * rest 503. Call `stopAccepting` first so no new ones arrive.
39
+ */
40
+ drain(ms: number): Promise<void>;
41
+ /** The `HttpImpl` to give `httpCapability`. */
42
+ readonly impl: HttpImpl;
43
+ /** `onPump` for a Group's driver: `pumped(group, result)` bound to it. */
44
+ onPump(group: Group): (result: PumpResult) => void;
45
+ /** The exchanges delivered and not yet answered. */
46
+ readonly openExchanges: number;
47
+ /** After each Pump of the Group returns: settles exchanges from its reports, in order. */
48
+ pumped(group: Group, result: Pick<PumpResult, 'reports'>): void;
49
+ /** The Serve Registrations held. */
50
+ readonly registrations: number;
51
+ /** Stops accepting connections. New requests on open connections are answered 503. */
52
+ stopAccepting(): void;
53
+ };
54
+ /** The one argument chapter 7 gives an HTTP Exchange's Delivery, without `exchange`. */
55
+ export declare const requestFields: (method: string, target: string, rawHeaders: readonly string[], body: Uint8Array) => [string, Value][];
56
+ /** Creates the HTTP router. Give `impl` to `httpCapability`, and call `pumped` after each Pump. */
57
+ export declare const createHttpHost: (o?: HttpHostOptions) => HttpHost;
58
+ //#endregion
59
+ export type { HttpAddress, HttpHost, HttpHostOptions };