@northtalk/ts 0.5.0 → 0.5.1

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 (70) hide show
  1. package/README.md +11 -0
  2. package/base64-CDO-a06R.js +29 -0
  3. package/{binary-value-B3knLdHD.d.ts → binary-value-xvJoGg0C.d.ts} +1 -1
  4. package/{checker-DMI4LiRm.js → checker-CUhn2XaM.js} +4 -4
  5. package/{core-D_9OuTRE.d.ts → core-BuTAYRm-.d.ts} +1 -1
  6. package/{debug-nN5tQ_p4.d.ts → debug-DRhMZAxw.d.ts} +24 -8
  7. package/debug.d.ts +1 -1
  8. package/debug.js +1 -1
  9. package/{driver-Bf-7Roq6.d.ts → driver-CHDcuqUy.d.ts} +1 -1
  10. package/driver.d.ts +1 -1
  11. package/driver.js +1 -1
  12. package/{encoding-C3Q7pIC9.js → encoding-RUuES_e4.js} +2 -2
  13. package/{engine-BpdGfAND.js → engine-CXf5FCwi.js} +6 -6
  14. package/{engine-CQqt4rTB.d.ts → engine-Cc3yofGM.d.ts} +2 -2
  15. package/{errors-BKJES3Zu.js → errors-D11zizZg.js} +1580 -1481
  16. package/{group-Bz2wh72R.js → group-BflSou2n.js} +45 -33
  17. package/http-fetch-DFwVIOQg.js +517 -0
  18. package/http.d.ts +39 -2
  19. package/http.js +189 -6
  20. package/index.d.ts +10 -660
  21. package/index.js +36 -49
  22. package/{inline-grants-Cx0Z9XAt.js → inline-grants-XbX9HL_w.js} +72 -304
  23. package/lean-BebPaTMK.js +47 -0
  24. package/lean-CjWVuOrC.d.ts +741 -0
  25. package/lean.d.ts +8 -0
  26. package/lean.js +15 -0
  27. package/{manifest-Dw-8Unmf.js → manifest-CCfpn0kC.js} +3 -4
  28. package/{manifest-DYAbIyQm.d.ts → manifest-DVrx-pT2.d.ts} +2 -2
  29. package/message-layer.d.ts +2 -2
  30. package/message-layer.js +2 -2
  31. package/notify.d.ts +1 -1
  32. package/notify.js +1 -1
  33. package/{objects-BRcpeXwZ.d.ts → objects-DC6HjzBY.d.ts} +1 -1
  34. package/{objects-BC4fS0vq.js → objects-DmUc0lha.js} +1 -1
  35. package/{base64-Dtqaz_0A.js → operations-DnCcztkZ.js} +1632 -32
  36. package/package.json +36 -2
  37. package/{readers-B5e5bBrY.js → readers-CsvlahLi.js} +2 -2
  38. package/{readers-L90Hoa97.d.ts → readers-MmyZ_d0w.d.ts} +1 -1
  39. package/{request-pump-binary-BjnyqXV5.js → request-pump-binary-oqjWFqZA.js} +5 -4
  40. package/{router-BCHEfs4x.js → router-BZ-aYeXA.js} +4 -4
  41. package/{router-CBuMIl6i.d.ts → router-D56rSkU8.d.ts} +2 -2
  42. package/session.d.ts +2 -2
  43. package/session.js +54 -15
  44. package/setup.d.ts +1 -1
  45. package/setup.js +4 -4
  46. package/sqlite.d.ts +2 -2
  47. package/sqlite.js +5 -5
  48. package/stdlib/bytes.d.ts +6 -0
  49. package/stdlib/bytes.js +11 -0
  50. package/stdlib/date.d.ts +6 -0
  51. package/stdlib/date.js +11 -0
  52. package/stdlib/json.d.ts +6 -0
  53. package/stdlib/json.js +11 -0
  54. package/stdlib/list.d.ts +6 -0
  55. package/stdlib/list.js +10 -0
  56. package/stdlib/map.d.ts +6 -0
  57. package/stdlib/map.js +10 -0
  58. package/stdlib/text.d.ts +6 -0
  59. package/stdlib/text.js +10 -0
  60. package/stdlib/units.d.ts +6 -0
  61. package/stdlib/units.js +10 -0
  62. package/stdlib-registry-BwitI3Ox.d.ts +18 -0
  63. package/{store-DTQa0lyE.js → store-DHlo6fP5.js} +2 -2
  64. package/{store-capability-BxXgiRM7.js → store-capability-BrUUAwVS.js} +3 -4
  65. package/store.d.ts +2 -2
  66. package/store.js +2 -2
  67. package/{user-capability-5-IvCeZI.js → user-capability-BcRQyyEw.js} +4 -5
  68. package/wasm.d.ts +5 -5
  69. package/wasm.js +12 -11
  70. package/capabilities-Bi5Qm6Fr.js +0 -1320
@@ -0,0 +1,517 @@
1
+
2
+ import { A as listValues, L as nothing, N as map, Q as text, R as num, Yt as characterBoundaries, en as normalizeNFC, i as ScriptError, o as invalidValue, q as requireValue, u as bool, v as dec } from "./errors-D11zizZg.js";
3
+ import { dt as errorMessages, n as ScriptError$1 } from "./operations-DnCcztkZ.js";
4
+ //#region src/json.ts
5
+ var JsonReader = class {
6
+ source;
7
+ i = 0;
8
+ constructor(source) {
9
+ this.source = source;
10
+ }
11
+ fail(at = this.i) {
12
+ const scalar = Array.from(this.source, (c) => /^[\uD800-\uDFFF]$/.test(c) ? "�" : c).join("");
13
+ const offset = characterBoundaries(scalar).filter((i) => i <= at).length;
14
+ throw new ScriptError("can't decode", errorMessages["can't decode"].replace("{format}", text("json").toString()).replace("{offset}", String(offset)), map([["format", text("json")], ["offset", num(offset)]]));
15
+ }
16
+ space() {
17
+ while (/[\t\n\r ]/.test(this.source[this.i] ?? "") && this.i < this.source.length) this.i++;
18
+ }
19
+ eat(c) {
20
+ if (this.source[this.i] !== c) this.fail();
21
+ this.i++;
22
+ }
23
+ hex4() {
24
+ let n = 0;
25
+ for (let k = 0; k < 4; k++) {
26
+ const c = this.source[this.i];
27
+ if (c === void 0 || !/[\dA-Fa-f]/.test(c)) this.fail();
28
+ n = n * 16 + Number.parseInt(c, 16);
29
+ this.i++;
30
+ }
31
+ return n;
32
+ }
33
+ string() {
34
+ this.eat("\"");
35
+ const parts = [];
36
+ const escapes = {
37
+ "\"": "\"",
38
+ "\\": "\\",
39
+ "/": "/",
40
+ b: "\b",
41
+ f: "\f",
42
+ n: "\n",
43
+ r: "\r",
44
+ t: " "
45
+ };
46
+ while (this.i < this.source.length) {
47
+ const start = this.i;
48
+ const cp = this.source.codePointAt(this.i);
49
+ const c = String.fromCodePoint(cp);
50
+ if (c === "\"") {
51
+ this.i++;
52
+ return normalizeNFC(parts.join(""));
53
+ }
54
+ if (cp < 32 || cp >= 55296 && cp <= 57343) this.fail();
55
+ this.i += c.length;
56
+ if (c !== "\\") {
57
+ parts.push(c);
58
+ continue;
59
+ }
60
+ if (this.i === this.source.length) this.fail();
61
+ const escape = this.source[this.i++];
62
+ if (Object.hasOwn(escapes, escape)) {
63
+ parts.push(escapes[escape]);
64
+ continue;
65
+ }
66
+ if (escape !== "u") this.fail(this.i - 1);
67
+ let u = this.hex4();
68
+ if (u >= 56320 && u <= 57343) this.fail(start);
69
+ if (u >= 55296 && u <= 56319) {
70
+ const lowStart = this.i;
71
+ if (this.source[this.i] !== "\\" || this.source[this.i + 1] !== "u") this.fail();
72
+ this.i += 2;
73
+ const low = this.hex4();
74
+ if (low < 56320 || low > 57343) this.fail(lowStart);
75
+ u = 65536 + (u - 55296) * 1024 + low - 56320;
76
+ }
77
+ parts.push(String.fromCodePoint(u));
78
+ }
79
+ return this.fail();
80
+ }
81
+ digits() {
82
+ const start = this.i;
83
+ while (this.i < this.source.length && /\d/.test(this.source[this.i])) this.i++;
84
+ return this.source.slice(start, this.i);
85
+ }
86
+ number() {
87
+ const start = this.i;
88
+ let sign = "";
89
+ if (this.source[this.i] === "-") {
90
+ sign = "-";
91
+ this.i++;
92
+ }
93
+ if (!/\d/.test(this.source[this.i] ?? "")) this.fail();
94
+ let whole;
95
+ if (this.source[this.i] === "0") {
96
+ whole = "0";
97
+ this.i++;
98
+ } else whole = this.digits();
99
+ let fraction = "";
100
+ if (this.source[this.i] === ".") {
101
+ this.i++;
102
+ fraction = this.digits();
103
+ if (!fraction) this.fail();
104
+ }
105
+ let exponent = "", negativeExponent = false;
106
+ if (/[Ee]/.test(this.source[this.i] ?? "")) {
107
+ this.i++;
108
+ if (/[+-]/.test(this.source[this.i] ?? "")) negativeExponent = this.source[this.i++] === "-";
109
+ exponent = this.digits();
110
+ if (!exponent) this.fail();
111
+ }
112
+ const coefficient = whole + fraction;
113
+ const significant = coefficient.replace(/^0+/, "");
114
+ exponent = exponent.replace(/^0+/, "");
115
+ if (exponent.length > 9) {
116
+ if (!significant && !negativeExponent) return num(0);
117
+ this.fail(start);
118
+ }
119
+ const q = (negativeExponent ? -1 : 1) * Number(exponent) - fraction.length;
120
+ if (!significant && q >= 0) return num(0);
121
+ if (significant.length > 34) this.fail(start);
122
+ if (q >= 0) {
123
+ if (significant.length + q > 34) this.fail(start);
124
+ return dec(sign + significant + "0".repeat(q));
125
+ }
126
+ if (-q > 6176) this.fail(start);
127
+ const digits = coefficient.padStart(-q + 1, "0");
128
+ return dec(sign + digits.slice(0, q) + "." + digits.slice(q));
129
+ }
130
+ atom() {
131
+ const c = this.source[this.i];
132
+ if (c === "\"") return text(this.string());
133
+ if (c === "-" || /\d/.test(c ?? "")) return this.number();
134
+ for (const [literal, value] of [
135
+ ["true", bool(true)],
136
+ ["false", bool(false)],
137
+ ["null", nothing]
138
+ ]) {
139
+ if (c !== literal[0]) continue;
140
+ for (const ch of literal) this.eat(ch);
141
+ return value;
142
+ }
143
+ return this.fail();
144
+ }
145
+ read() {
146
+ const frames = [];
147
+ let value;
148
+ const key = (frame) => {
149
+ this.space();
150
+ const start = this.i;
151
+ frame.key = this.string();
152
+ if (frame.keys.has(frame.key)) this.fail(start);
153
+ frame.keys.add(frame.key);
154
+ this.space();
155
+ this.eat(":");
156
+ };
157
+ for (;;) {
158
+ if (!value) {
159
+ this.space();
160
+ const c = this.source[this.i];
161
+ if (c === "[" || c === "{") {
162
+ this.i++;
163
+ this.space();
164
+ const frame = c === "[" ? {
165
+ kind: "list",
166
+ values: []
167
+ } : {
168
+ kind: "map",
169
+ pairs: [],
170
+ keys: /* @__PURE__ */ new Set(),
171
+ key: ""
172
+ };
173
+ if (this.source[this.i] === (c === "[" ? "]" : "}")) {
174
+ this.i++;
175
+ value = c === "[" ? listValues([]) : map([]);
176
+ } else {
177
+ if (frame.kind === "map") key(frame);
178
+ frames.push(frame);
179
+ continue;
180
+ }
181
+ } else value = this.atom();
182
+ }
183
+ const parent = frames.at(-1);
184
+ this.space();
185
+ if (!parent) {
186
+ if (this.i !== this.source.length) this.fail();
187
+ return value;
188
+ }
189
+ if (parent.kind === "list") parent.values.push(value);
190
+ else parent.pairs.push([parent.key, value]);
191
+ if (this.source[this.i] === ",") {
192
+ this.i++;
193
+ if (parent.kind === "map") key(parent);
194
+ value = void 0;
195
+ } else {
196
+ this.eat(parent.kind === "list" ? "]" : "}");
197
+ frames.pop();
198
+ value = parent.kind === "list" ? listValues(parent.values) : map(parent.pairs);
199
+ }
200
+ }
201
+ }
202
+ };
203
+ /** Read exact decimal digits, NFC strings and insertion-ordered maps. */
204
+ const decodeJson = (source) => {
205
+ if (typeof source !== "string") invalidValue("JSON must be text");
206
+ return new JsonReader(source).read();
207
+ };
208
+ const quoteJson = (s) => {
209
+ const short = {
210
+ "\b": "b",
211
+ " ": "t",
212
+ "\n": "n",
213
+ "\f": "f",
214
+ "\r": "r"
215
+ };
216
+ return "\"" + s.replaceAll(/[\u0000-\u001f"\\]/g, (c) => c === "\"" || c === "\\" ? "\\" + c : Object.hasOwn(short, c) ? "\\" + short[c] : String.raw`\u00` + c.charCodeAt(0).toString(16).padStart(2, "0")) + "\"";
217
+ };
218
+ /** Compact JSON, with canonical numbers and chapter 7's string escapes. */
219
+ const encodeJson = (value) => {
220
+ requireValue(value);
221
+ const pending = [{
222
+ value,
223
+ path: void 0
224
+ }];
225
+ const output = [];
226
+ while (pending.length) {
227
+ const next = pending.pop();
228
+ if (typeof next === "string") {
229
+ output.push(next);
230
+ continue;
231
+ }
232
+ const { value: v, path } = next;
233
+ switch (v.kind) {
234
+ case "nothing":
235
+ output.push("null");
236
+ break;
237
+ case "boolean":
238
+ case "number":
239
+ output.push(v.toString());
240
+ break;
241
+ case "text":
242
+ output.push(quoteJson(v.asText()));
243
+ break;
244
+ case "list":
245
+ output.push("[");
246
+ pending.push("]");
247
+ for (let i = v.length; i >= 1; i--) {
248
+ if (i < v.length) pending.push(",");
249
+ pending.push({
250
+ value: v.index(i),
251
+ path: {
252
+ key: i,
253
+ parent: path
254
+ }
255
+ });
256
+ }
257
+ break;
258
+ case "map": {
259
+ output.push("{");
260
+ pending.push("}");
261
+ const entries = v.entries();
262
+ for (let i = entries.length - 1; i >= 0; i--) {
263
+ const [k, child] = entries[i];
264
+ if (i < entries.length - 1) pending.push(",");
265
+ pending.push({
266
+ value: child,
267
+ path: {
268
+ key: k,
269
+ parent: path
270
+ }
271
+ }, quoteJson(k) + ":");
272
+ }
273
+ break;
274
+ }
275
+ default: {
276
+ const keys = [];
277
+ for (let p = path; p; p = p.parent) keys.push(typeof p.key === "string" ? text(p.key) : num(p.key));
278
+ throw new ScriptError("not encodable", errorMessages["not encodable"].replace("{kind}", text(v.kind).toString()), map([["kind", text(v.kind)], ["path", listValues(keys.reverse())]]));
279
+ }
280
+ }
281
+ }
282
+ return output.join("");
283
+ };
284
+ //#endregion
285
+ //#region src/http-fetch.ts
286
+ const FETCH_METHODS = [
287
+ "GET",
288
+ "HEAD",
289
+ "POST",
290
+ "PUT",
291
+ "PATCH",
292
+ "DELETE",
293
+ "OPTIONS"
294
+ ];
295
+ /** Header names the Host controls, which a Script can't set. */
296
+ const FETCH_HOST_HEADERS = /* @__PURE__ */ new Set([
297
+ "host",
298
+ "content-length",
299
+ "transfer-encoding",
300
+ "connection",
301
+ "keep-alive",
302
+ "proxy-connection",
303
+ "te",
304
+ "trailer",
305
+ "upgrade"
306
+ ]);
307
+ const invalid = (code, field) => new ScriptError$1(code, [["field", text(field)]], true);
308
+ const badRequest = (field) => invalid("invalid request", field);
309
+ const DIGIT = /^\d+$/;
310
+ const HEX = /^[\dA-Fa-f]{2}$/;
311
+ const NAME = /^[\dA-Za-z-]+(\.[\dA-Za-z-]+)*$/;
312
+ const PCHAR = /^[\w!$&'()*+,./:;=@~-]$/;
313
+ const defaultPort = (scheme) => scheme === "https" ? 443 : 80;
314
+ const ipv4 = (host) => {
315
+ const parts = host.split(".");
316
+ return parts.length === 4 && parts.every((p) => DIGIT.test(p) && p.length <= 3 && (p === "0" || !p.startsWith("0")) && Number(p) <= 255);
317
+ };
318
+ const hexGroup = (g) => /^[\dA-Fa-f]{1,4}$/.test(g);
319
+ const groupsOf = (part) => part === "" ? [] : part.split(":");
320
+ const ipv6 = (inner) => {
321
+ let s = inner;
322
+ const dot = s.lastIndexOf(":");
323
+ if (s.slice(dot + 1).includes(".")) {
324
+ if (!ipv4(s.slice(dot + 1))) return false;
325
+ s = `${s.slice(0, dot + 1)}0:0`;
326
+ }
327
+ const halves = s.split("::");
328
+ if (halves.length === 1) {
329
+ const all = groupsOf(s);
330
+ return all.length === 8 && all.every(hexGroup);
331
+ }
332
+ if (halves.length !== 2) return false;
333
+ const named = [...groupsOf(halves[0]), ...groupsOf(halves[1])];
334
+ return named.length <= 7 && named.every(hexGroup);
335
+ };
336
+ const escapesOk = (s) => {
337
+ for (let i = s.indexOf("%"); i >= 0; i = s.indexOf("%", i + 1)) if (!HEX.test(s.slice(i + 1, i + 3))) return false;
338
+ return true;
339
+ };
340
+ const partOk = (s, extra) => {
341
+ for (let i = 0; i < s.length; i++) {
342
+ const c = s[i];
343
+ if (c === "%") i += 2;
344
+ else if (!PCHAR.test(c) && !extra.includes(c)) return false;
345
+ }
346
+ return true;
347
+ };
348
+ /** Parses and normalizes a fetch URL, or undefined outside the profile. */
349
+ const parseFetchUrl = (url) => {
350
+ for (let i = 0; i < url.length; i++) {
351
+ const c = url.charCodeAt(i);
352
+ if (c <= 32 || c >= 127 || c === 92) return;
353
+ }
354
+ if (!escapesOk(url)) return;
355
+ const m = /^(https?):\/\//i.exec(url);
356
+ if (!m) return;
357
+ const scheme = m[1].toLowerCase();
358
+ let rest = url.slice(m[0].length);
359
+ const hash = rest.indexOf("#");
360
+ if (hash >= 0) rest = rest.slice(0, hash);
361
+ const end = rest.search(/[/?]/);
362
+ const authority = end < 0 ? rest : rest.slice(0, end);
363
+ rest = end < 0 ? "" : rest.slice(end);
364
+ let host;
365
+ let portText;
366
+ if (authority.startsWith("[")) {
367
+ const close = authority.indexOf("]");
368
+ if (close < 0 || !ipv6(authority.slice(1, close))) return;
369
+ host = authority.slice(0, close + 1).toLowerCase();
370
+ const after = authority.slice(close + 1);
371
+ if (after !== "") {
372
+ if (!after.startsWith(":")) return;
373
+ portText = after.slice(1);
374
+ }
375
+ } else {
376
+ const colon = authority.indexOf(":");
377
+ host = (colon < 0 ? authority : authority.slice(0, colon)).toLowerCase();
378
+ portText = colon < 0 ? void 0 : authority.slice(colon + 1);
379
+ if (!NAME.test(host)) return;
380
+ if (DIGIT.test(host.slice(host.lastIndexOf(".") + 1)) && !ipv4(host)) return;
381
+ }
382
+ let port = defaultPort(scheme);
383
+ if (portText !== void 0) {
384
+ if (!DIGIT.test(portText)) return;
385
+ port = Number(portText);
386
+ if (port < 1 || port > 65535) return;
387
+ }
388
+ const q = rest.indexOf("?");
389
+ const path = q < 0 ? rest : rest.slice(0, q);
390
+ const query = q < 0 ? void 0 : rest.slice(q + 1);
391
+ if (!partOk(path, "") || query !== void 0 && !partOk(query, "?")) return;
392
+ return {
393
+ scheme,
394
+ host,
395
+ port,
396
+ path: path === "" ? "/" : path,
397
+ ...query === void 0 ? {} : { query }
398
+ };
399
+ };
400
+ /** The origin, `scheme://host:port`, always with its port. */
401
+ const fetchOrigin = (u) => `${u.scheme}://${u.host}:${u.port}`;
402
+ /** The normalized URL: no default port, no fragment. */
403
+ const fetchUrlText = (u) => `${u.scheme}://${u.host}${u.port === defaultPort(u.scheme) ? "" : `:${u.port}`}${u.path}${u.query === void 0 ? "" : `?${u.query}`}`;
404
+ const utf8 = new TextEncoder();
405
+ const UNRESERVED = /^[\w.~-]$/;
406
+ const percentEncode = (s) => {
407
+ let out = "";
408
+ for (const byte of utf8.encode(s)) {
409
+ const c = String.fromCharCode(byte);
410
+ out += UNRESERVED.test(c) ? c : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
411
+ }
412
+ return out;
413
+ };
414
+ const texts = (v) => {
415
+ if (v.kind === "text") return [v.asText()];
416
+ if (v.kind !== "list") return;
417
+ const out = [];
418
+ for (let i = 1; i <= v.length; i++) {
419
+ const item = v.index(i);
420
+ if (item.kind !== "text") return;
421
+ out.push(item.asText());
422
+ }
423
+ return out;
424
+ };
425
+ const TOKEN = /^[\w!#$%&'*+.^`|~-]+$/;
426
+ const headerValueOk = (s) => !/[\u0000-\u0008\u000a-\u001f\u007f]/.test(s) && !/^[\t ]|[\t ]$/.test(s);
427
+ /**
428
+ * Whether a headers map names one header twice in different cases. Shared
429
+ * with `respond`.
430
+ */
431
+ const duplicateHeaderNames = (headers) => {
432
+ const seen = /* @__PURE__ */ new Set();
433
+ for (const [name] of headers.entries()) {
434
+ const lower = name.toLowerCase();
435
+ if (seen.has(lower)) return true;
436
+ seen.add(lower);
437
+ }
438
+ return false;
439
+ };
440
+ const given = (m, key) => m.entries().find(([k]) => k === key)?.[1];
441
+ /**
442
+ * Checks `fetch`'s arguments, after their Shapes, in chapter 7's order, and
443
+ * gives what the Host receives. Throws `out of domain` or `invalid request`.
444
+ */
445
+ const checkFetch = (args) => {
446
+ const request = args[1] && args[1].kind === "map" ? args[1] : map([]);
447
+ const methodValue = given(request, "method");
448
+ const method = methodValue?.asText() ?? "GET";
449
+ if (!FETCH_METHODS.includes(method)) throw new ScriptError$1("out of domain", [["function", text("fetch")], ["value", methodValue]], true);
450
+ const url = parseFetchUrl(args[0].asText());
451
+ if (!url) throw badRequest("url");
452
+ const headers = given(request, "headers");
453
+ if (headers) {
454
+ if (duplicateHeaderNames(headers)) throw badRequest("headers");
455
+ for (const [name, value] of headers.entries()) {
456
+ const values = texts(value);
457
+ if (!TOKEN.test(name) || FETCH_HOST_HEADERS.has(name.toLowerCase()) || !values || !values.every(headerValueOk)) throw badRequest("headers");
458
+ }
459
+ }
460
+ const query = given(request, "query");
461
+ if (query) {
462
+ const pairs = [];
463
+ for (const [key, value] of query.entries()) {
464
+ const values = texts(value);
465
+ if (!values) throw badRequest("query");
466
+ for (const v of values) pairs.push(`${percentEncode(key)}=${percentEncode(v)}`);
467
+ }
468
+ if (query.mapSize > 0) {
469
+ if (url.query !== void 0) throw badRequest("query");
470
+ url.query = pairs.join("&");
471
+ }
472
+ }
473
+ const body = given(request, "body");
474
+ const json = given(request, "json");
475
+ let jsonText;
476
+ if (json) {
477
+ if (body) throw badRequest("json");
478
+ try {
479
+ jsonText = encodeJson(json);
480
+ } catch {
481
+ throw badRequest("json");
482
+ }
483
+ }
484
+ if ((method === "GET" || method === "HEAD") && (body || json)) throw badRequest(body ? "body" : "json");
485
+ const out = [["method", text(method)]];
486
+ if (headers) out.push(["headers", headers]);
487
+ if (body) out.push(["body", body]);
488
+ if (jsonText !== void 0) out.push(["json", text(jsonText)]);
489
+ return {
490
+ url: fetchUrlText(url),
491
+ request: map(out)
492
+ };
493
+ };
494
+ const whole = (v) => {
495
+ if (v.kind !== "number") return;
496
+ const n = Number(v.toString());
497
+ return Number.isSafeInteger(n) ? n : void 0;
498
+ };
499
+ /** Whether the Host's answer follows chapter 7's response rules. */
500
+ const fetchAnswerOk = (answer) => {
501
+ if (answer.kind !== "map") return false;
502
+ const entries = answer.entries();
503
+ if (entries.map(([k]) => k).join(",") !== "status,headers,body") return false;
504
+ const [[, status], [, headers], [, body]] = entries;
505
+ const n = whole(status);
506
+ if (n === void 0 || n < 200 || n > 599 || body.kind !== "bytes") return false;
507
+ if (headers.kind !== "map") return false;
508
+ let previous;
509
+ for (const [name, value] of headers.entries()) {
510
+ if (!TOKEN.test(name) || name !== name.toLowerCase() || previous !== void 0 && !(previous < name)) return false;
511
+ previous = name;
512
+ if (!(name === "set-cookie" ? value.kind === "list" && texts(value) !== void 0 : value.kind === "text")) return false;
513
+ }
514
+ return true;
515
+ };
516
+ //#endregion
517
+ export { parseFetchUrl as a, fetchOrigin as i, duplicateHeaderNames as n, decodeJson as o, fetchAnswerOk as r, encodeJson as s, checkFetch as t };
package/http.d.ts CHANGED
@@ -1,5 +1,36 @@
1
1
  /// <reference lib="esnext.disposable" />
2
- import { J as Value, Qt as Group, gt as ObjectKindDef, ht as ObjectKind, nn as HttpImpl, x as PumpResult } from "./debug-nN5tQ_p4.js";
2
+ import { J as Value, Qt as Group, gt as ObjectKindDef, ht as ObjectKind, nn as HttpClientImpl, rn as HttpImpl, x as PumpResult } from "./debug-DRhMZAxw.js";
3
+ import { Buffer } from "node:buffer";
4
+ //#region src/http/fetch.d.ts
5
+ /** The largest response body `fetch` reads by default: 8 MiB. */
6
+ export declare const HTTP_FETCH_DEFAULT_MAX_BODY_BYTES: number;
7
+ /** The most response header bytes `fetch` reads by default: 64 KiB. */
8
+ export declare const HTTP_FETCH_DEFAULT_MAX_HEADER_BYTES: number;
9
+ /** No origin, every origin, or a list of exact origins. */
10
+ type HttpFetchOrigins = 'any' | readonly string[];
11
+ type HttpFetchOptions = {
12
+ /** The certificate authorities HTTPS trusts, instead of the runtime's. */
13
+ ca?: string | Buffer | readonly (string | Buffer)[];
14
+ /** Told why a call failed. Never shown to the Script. */
15
+ log?: (message: string) => void;
16
+ /** The response body bound, 8 MiB by default. */
17
+ maxBodyBytes?: number;
18
+ /** The response header bound, trailers included, 64 KiB by default. */
19
+ maxHeaderBytes?: number;
20
+ /**
21
+ * The origins a Grant may fetch from: a list such as
22
+ * `['https://api.example.com']`, `'any'`, or a function of the Grant's
23
+ * binding giving one of these. By default, and for an empty list or an
24
+ * undefined result, it may fetch from none. Each origin is a scheme, host
25
+ * and optional port, with no path, query or wildcard.
26
+ */
27
+ origins?: HttpFetchOrigins | ((binding: unknown) => HttpFetchOrigins | undefined);
28
+ };
29
+ /** The origins as `scheme://host:port`, or throws `invalid value`. */
30
+ export declare const httpFetchOrigins: (origins: HttpFetchOrigins) => "any" | Set<string>;
31
+ /** `fetch` for `httpCapability`, alone or beside the router's server Operations. */
32
+ export declare const createHttpFetch: (o?: HttpFetchOptions) => HttpClientImpl;
33
+ //#endregion
3
34
  //#region src/http/router.d.ts
4
35
  /** The largest request body the router reads by default: 1 MiB. */
5
36
  export declare const HTTP_DEFAULT_MAX_BODY_BYTES: number;
@@ -15,6 +46,12 @@ type HttpHostOptions = {
15
46
  defaultPort?: number;
16
47
  /** Defines the `httpExchange` Object Kind; the TS Core's by default. Pass the Core's own for the Zig Host Adapter. */
17
48
  defineObjectKind?: <N>(k: ObjectKindDef<N>) => ObjectKind<N>;
49
+ /**
50
+ * Offers `fetch` beside the server Operations, with these origins and
51
+ * bounds. Without it the Host only serves; `createHttpFetch` alone only
52
+ * fetches.
53
+ */
54
+ fetch?: HttpFetchOptions;
18
55
  /** Told of each 500's cause and each refused Delivery. Never sent to the client. */
19
56
  log?: (message: string) => void;
20
57
  /** A larger request body is answered 413 without a Delivery. */
@@ -56,4 +93,4 @@ export declare const requestFields: (method: string, target: string, rawHeaders:
56
93
  /** Creates the HTTP router. Give `impl` to `httpCapability`, and call `pumped` after each Pump. */
57
94
  export declare const createHttpHost: (o?: HttpHostOptions) => HttpHost;
58
95
  //#endregion
59
- export type { HttpAddress, HttpHost, HttpHostOptions };
96
+ export type { HttpAddress, HttpFetchOptions, HttpFetchOrigins, HttpHost, HttpHostOptions };