@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.3106

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 (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -0,0 +1,280 @@
1
+ //#region src/database/schema.ts
2
+ /** A table's name: a leading `_` is the Database's own. */
3
+ const TABLE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u;
4
+ /** A short, stable text of a string (FNV-1a, base 36): a table's code and the ids a call inserts. */
5
+ function fnv(text) {
6
+ let hash = 2166136261;
7
+ for (let i = 0; i < text.length; i += 1) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619) >>> 0;
8
+ return hash.toString(36);
9
+ }
10
+ /** A table's code: the first 7 characters of every id inserted into it, so a table can be found from an id alone. */
11
+ const tableCode = (table) => fnv(table).padStart(7, "0");
12
+ /**
13
+ * An id's form, whoever mints it: its table's code (`tableCode`, 7 characters), then more base-36 letters and
14
+ * digits (`[0-9a-z]`), 16 to 256 characters in all. The SDK mints the code, 7 characters of its call's FNV-1a, then
15
+ * its insert's count; a Database may mint its own ids (`Rows.newId`), in this form, and `normalizeId` and
16
+ * `v.id` take every id of it for its table.
17
+ */
18
+ const ID_FORM = /^[0-9a-z]{16,256}$/u;
19
+ /** Whether `id` has the form of an id of `table` (`ID_FORM`, beginning with its table's code). */
20
+ const isIdForm = (table, id) => ID_FORM.test(id) && id.startsWith(tableCode(table));
21
+ const v = Object.freeze({
22
+ string: () => "string",
23
+ number: () => "number",
24
+ boolean: () => "boolean",
25
+ /** Any JSON value, at any depth. */
26
+ document: () => "document",
27
+ /** Any value, as Convex's `v.any()`: the same shape as `v.document()`. */
28
+ any: () => "document",
29
+ /** Only null, as Convex's `v.null()`: `v.union(v.string(), v.null())` is a string or null. */
30
+ null: () => ({ literal: null }),
31
+ /** May be left out or null. */
32
+ optional: (shape) => ({ optional: shape }),
33
+ array: (shape) => ({ array: shape }),
34
+ object: (fields) => ({ object: fields }),
35
+ int64: () => "int64",
36
+ bytes: () => "bytes",
37
+ timestamp: () => "timestamp",
38
+ decimal: () => "decimal",
39
+ literal: (value) => ({ literal: value }),
40
+ union: (...shapes) => ({ union: shapes }),
41
+ record: (shape) => ({ record: shape }),
42
+ id: (table) => ({ id: String(table) })
43
+ });
44
+ const INDEX = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
45
+ const INDEX_FIELDS = 8;
46
+ const RESERVED_INDEXES = /* @__PURE__ */ new Set(["by_id", "by_creation_time"]);
47
+ const MAX_DIMENSIONS = 4096;
48
+ /** Whether an index may order a field of this shape: what the Database orders, its keys comparing as their values do. */
49
+ function orderable(shape) {
50
+ const inner = shape && typeof shape === "object" && "optional" in shape ? shape.optional : shape;
51
+ if (typeof inner === "string") return [
52
+ "string",
53
+ "number",
54
+ "boolean",
55
+ "int64",
56
+ "timestamp"
57
+ ].includes(inner);
58
+ if (!inner) return false;
59
+ if ("id" in inner) return true;
60
+ if ("literal" in inner) return inner.literal === null || [
61
+ "string",
62
+ "number",
63
+ "boolean"
64
+ ].includes(typeof inner.literal);
65
+ if ("union" in inner) return inner.union.every(orderable);
66
+ return false;
67
+ }
68
+ const unwrapped = (shape) => shape && typeof shape === "object" && "optional" in shape ? shape.optional : shape;
69
+ /** The shape at a field's path (`"author.id"` reaches into `author`'s object), or undefined when the table has none there. */
70
+ function shapeAt(fields, path) {
71
+ if (typeof path !== "string" || !path) return void 0;
72
+ let shape = { object: fields };
73
+ for (const part of path.split(".")) {
74
+ const inner = unwrapped(shape);
75
+ shape = inner && typeof inner === "object" && "object" in inner && Object.hasOwn(inner.object, part) ? inner.object[part] : void 0;
76
+ if (!shape) return void 0;
77
+ }
78
+ return shape;
79
+ }
80
+ /** A field's value at its path in a row, or undefined when the row has none there. */
81
+ function valueAt(row, path) {
82
+ let value = row;
83
+ for (const part of path.split(".")) {
84
+ if (value === null || typeof value !== "object" || Array.isArray(value) || !Object.hasOwn(value, part)) return void 0;
85
+ value = value[part];
86
+ }
87
+ return value;
88
+ }
89
+ function tableOf(fields, indexes, search = Object.freeze({}), vector = Object.freeze({})) {
90
+ const taken = (name) => name in indexes || name in search || name in vector;
91
+ const filtersOf = (kind, name, filterFields) => {
92
+ if (!Array.isArray(filterFields) || filterFields.length > 16 || new Set(filterFields).size !== filterFields.length || filterFields.some((f) => shapeAt(fields, f) === void 0)) throw new TypeError(`${kind} ${name}: filterFields are up to 16 different fields of the table`);
93
+ return Object.freeze([...filterFields]);
94
+ };
95
+ const stagedOf = (kind, name, staged) => {
96
+ if (typeof staged !== "boolean") throw new TypeError(`${kind} ${name}: staged is true or false`);
97
+ return staged;
98
+ };
99
+ return Object.freeze({
100
+ fields,
101
+ indexes,
102
+ search,
103
+ vector,
104
+ index(name, field, { unique = false } = {}) {
105
+ if (typeof name !== "string" || !INDEX.test(name) || RESERVED_INDEXES.has(name)) throw new TypeError(`index ${JSON.stringify(name)}: a name of [A-Za-z][A-Za-z0-9_]{0,63}, not by_id or by_creation_time`);
106
+ if (taken(name)) throw new TypeError(`index ${name}: declared twice`);
107
+ const list = Array.isArray(field) ? field : [field];
108
+ if (!list.length || list.length > INDEX_FIELDS || new Set(list).size !== list.length) throw new TypeError(`index ${name}: a field, or a list of up to ${INDEX_FIELDS} different fields`);
109
+ for (const one of list) {
110
+ if (typeof one !== "string" || !(one in fields)) throw new TypeError(`index ${name}: ${JSON.stringify(one)} is not a field of the table`);
111
+ if (!orderable(fields[one])) throw new TypeError(`index ${name}: ${one} is not a string, number, boolean, id or null`);
112
+ }
113
+ const on = list.length === 1 ? list[0] : Object.freeze([...list]);
114
+ return tableOf(fields, Object.freeze({
115
+ ...indexes,
116
+ [name]: unique ? Object.freeze({
117
+ fields: on,
118
+ unique: true
119
+ }) : on
120
+ }), search, vector);
121
+ },
122
+ searchIndex(name, { searchField, filterFields = [], staged = false } = { searchField: "" }) {
123
+ if (typeof name !== "string" || !INDEX.test(name) || RESERVED_INDEXES.has(name) || taken(name)) throw new TypeError(`searchIndex ${JSON.stringify(name)}: a name of [A-Za-z][A-Za-z0-9_]{0,63}, not another index's`);
124
+ if (unwrapped(shapeAt(fields, searchField)) !== "string") throw new TypeError(`searchIndex ${name}: searchField is a string field of the table`);
125
+ return tableOf(fields, indexes, Object.freeze({
126
+ ...search,
127
+ [name]: Object.freeze({
128
+ field: searchField,
129
+ filters: filtersOf("searchIndex", name, filterFields),
130
+ staged: stagedOf("searchIndex", name, staged)
131
+ })
132
+ }), vector);
133
+ },
134
+ vectorIndex(name, { vectorField, dimensions, filterFields = [], staged = false } = {
135
+ vectorField: "",
136
+ dimensions: 0
137
+ }) {
138
+ if (typeof name !== "string" || !INDEX.test(name) || RESERVED_INDEXES.has(name) || taken(name)) throw new TypeError(`vectorIndex ${JSON.stringify(name)}: a name of [A-Za-z][A-Za-z0-9_]{0,63}, not another index's`);
139
+ if (Object.keys(vector).length >= 4) throw new TypeError(`vectorIndex ${name}: up to 4 vector indexes a table`);
140
+ const shape = unwrapped(shapeAt(fields, vectorField));
141
+ if (!shape || typeof shape !== "object" || !("array" in shape) || shape.array !== "number") throw new TypeError(`vectorIndex ${name}: vectorField is a v.array(v.number()) field of the table`);
142
+ if (!Number.isInteger(dimensions) || dimensions < 2 || dimensions > 4096) throw new TypeError(`vectorIndex ${name}: dimensions is a whole number from 2 to ${MAX_DIMENSIONS}`);
143
+ return tableOf(fields, indexes, search, Object.freeze({
144
+ ...vector,
145
+ [name]: Object.freeze({
146
+ field: vectorField,
147
+ dimensions,
148
+ filters: filtersOf("vectorIndex", name, filterFields),
149
+ staged: stagedOf("vectorIndex", name, staged)
150
+ })
151
+ }));
152
+ }
153
+ });
154
+ }
155
+ /** An index's fields in order. */
156
+ function indexFields(declared) {
157
+ const fields = declared !== null && typeof declared === "object" && !Array.isArray(declared) ? declared.fields : declared;
158
+ return Array.isArray(fields) ? [...fields] : [fields];
159
+ }
160
+ function defineTable(fields) {
161
+ if (fields === null || typeof fields !== "object" || Array.isArray(fields)) throw new TypeError("defineTable({ <field>: v.<shape>() })");
162
+ for (const [field, shape] of Object.entries(fields)) {
163
+ if (field.startsWith("_")) throw new TypeError(`defineTable: ${field}: a leading _ is the Database's`);
164
+ if (shapeError(shape, void 0, field)?.endsWith("not a shape")) throw new TypeError(`defineTable: ${field}: not a shape`);
165
+ }
166
+ return tableOf(Object.freeze({ ...fields }), Object.freeze({}));
167
+ }
168
+ function defineSchema(tables) {
169
+ if (tables === null || typeof tables !== "object" || Array.isArray(tables)) throw new TypeError("defineSchema({ <table>: defineTable(...) })");
170
+ const out = {};
171
+ const indexes = {};
172
+ const search = {}, vector = {};
173
+ const codes = /* @__PURE__ */ new Map();
174
+ for (const [name, table] of Object.entries(tables)) {
175
+ if (!TABLE.test(name)) throw new TypeError(`defineSchema: "${name}" is not a table name`);
176
+ if (!table?.fields) throw new TypeError(`defineSchema: "${name}" is not a defineTable(...)`);
177
+ const other = codes.get(tableCode(name));
178
+ if (other !== void 0) throw new TypeError(`defineSchema: "${other}" and "${name}" would have ids of one form; rename one of them`);
179
+ codes.set(tableCode(name), name);
180
+ out[name] = table.fields;
181
+ indexes[name] = table.indexes ?? Object.freeze({});
182
+ if (table.search && Object.keys(table.search).length > 4) throw new TypeError(`defineSchema: "${name}": up to 4 search indexes a table, not ${Object.keys(table.search).length}`);
183
+ if (table.search && Object.keys(table.search).length) search[name] = table.search;
184
+ if (table.vector && Object.keys(table.vector).length) vector[name] = table.vector;
185
+ }
186
+ return Object.freeze({
187
+ schema: true,
188
+ tables: Object.freeze(out),
189
+ indexes: Object.freeze(indexes),
190
+ search: Object.freeze(search),
191
+ vector: Object.freeze(vector)
192
+ });
193
+ }
194
+ /** Reads the public int64 form exactly: a safe integer or a decimal string within signed 64-bit limits. */
195
+ function int64Value(value) {
196
+ if (!(typeof value === "number" && Number.isSafeInteger(value)) && !(typeof value === "string" && /^-?\d{1,19}$/u.test(value))) return void 0;
197
+ const integer = BigInt(value);
198
+ return integer >= -(1n << 63n) && integer < 1n << 63n ? integer : void 0;
199
+ }
200
+ /** Whether `value` fits `shape`: null, or the reason. An id fits only its own table (`isIdForm`). */
201
+ function shapeError(shape, value, at = "the value") {
202
+ const wrong = (what) => `${at}: ${what} expected`;
203
+ if (shape === "document") return null;
204
+ if (typeof shape === "string") switch (shape) {
205
+ case "string": return typeof value === "string" ? null : wrong("a string");
206
+ case "number": return typeof value === "number" && Number.isFinite(value) ? null : wrong("a number");
207
+ case "boolean": return typeof value === "boolean" ? null : wrong("a boolean");
208
+ case "int64": return int64Value(value) !== void 0 ? null : wrong("a whole number of 64 bits");
209
+ case "bytes": return value instanceof ArrayBuffer || ArrayBuffer.isView(value) ? null : wrong("bytes, an ArrayBuffer");
210
+ case "timestamp": return typeof value === "number" && Number.isFinite(value) ? null : wrong("a timestamp (milliseconds)");
211
+ case "decimal": return typeof value === "string" && /^-?\d+(\.\d+)?$/u.test(value) ? null : wrong("a decimal as a string");
212
+ default: return `${at}: no shape ${String(shape)}`;
213
+ }
214
+ if (shape && typeof shape === "object") {
215
+ if ("optional" in shape) return value === void 0 || value === null ? null : shapeError(shape.optional, value, at);
216
+ if ("array" in shape) return Array.isArray(value) ? value.map((item, k) => shapeError(shape.array, item, `${at}[${k}]`)).find(Boolean) ?? null : wrong("an array");
217
+ if ("object" in shape) {
218
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return wrong("an object");
219
+ const record = value;
220
+ for (const key of Object.keys(record)) if (!(key in shape.object)) return `${at}.${key}: no such field`;
221
+ for (const [key, inner] of Object.entries(shape.object)) {
222
+ if (record[key] === void 0 && inner && typeof inner === "object" && "optional" in inner) continue;
223
+ if (record[key] === void 0) return `${at}.${key}: missing`;
224
+ const why = shapeError(inner, record[key], `${at}.${key}`);
225
+ if (why) return why;
226
+ }
227
+ return null;
228
+ }
229
+ if ("literal" in shape) return JSON.stringify(value) === JSON.stringify(shape.literal) ? null : wrong(`the value ${JSON.stringify(shape.literal)}`);
230
+ if ("union" in shape) return shape.union.some((one) => shapeError(one, value, at) === null) ? null : wrong("one of the union's shapes");
231
+ if ("record" in shape) return value !== null && typeof value === "object" && !Array.isArray(value) ? Object.entries(value).map(([k, item]) => shapeError(shape.record, item, `${at}.${k}`)).find(Boolean) ?? null : wrong("an object");
232
+ if ("id" in shape) return typeof value === "string" && isIdForm(shape.id, value) ? null : wrong(`an id of ${shape.id}`);
233
+ }
234
+ return `${at}: not a shape`;
235
+ }
236
+ //#endregion
237
+ //#region src/database/bytes.ts
238
+ const TAG = "$bytes";
239
+ const isBinary = (value) => value instanceof ArrayBuffer || ArrayBuffer.isView(value);
240
+ const isPlain = (value) => value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
241
+ const isTag = (value) => isPlain(value) && typeof value[TAG] === "string" && Object.keys(value).length === 1;
242
+ const base64Of = (bytes) => {
243
+ let text = "";
244
+ for (let at = 0; at < bytes.length; at += 32768) text += String.fromCharCode(...bytes.subarray(at, at + 32768));
245
+ return btoa(text);
246
+ };
247
+ const bufferOf = (base64) => {
248
+ const text = atob(base64.replace(/-/gu, "+").replace(/_/gu, "/"));
249
+ const out = new Uint8Array(text.length);
250
+ for (let at = 0; at < text.length; at += 1) out[at] = text.charCodeAt(at);
251
+ return out.buffer;
252
+ };
253
+ const tagOf = (value) => ({ [TAG]: base64Of(value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) });
254
+ /** `JSON.stringify`'s replacer: bytes as their tag. A hand-made tag is refused. */
255
+ function tagBytes(_key, value) {
256
+ if (isTag(value)) throw new TypeError("an object whose only key is $bytes is how bytes travel, so one can't be sent as data");
257
+ return isBinary(value) ? tagOf(value) : value;
258
+ }
259
+ /** `JSON.stringify`'s replacer for comparing values: bytes as their tag, so two values with different bytes differ. */
260
+ const keyBytes = (_key, value) => isBinary(value) ? tagOf(value) : value;
261
+ /** Bytes written into a document as a typed array, kept as the `ArrayBuffer` a read gives back. */
262
+ function bytesAsBuffers(value) {
263
+ if (ArrayBuffer.isView(value)) return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
264
+ if (Array.isArray(value)) return value.map(bytesAsBuffers);
265
+ if (isPlain(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, bytesAsBuffers(item)]));
266
+ return value;
267
+ }
268
+ /** `JSON.parse`'s reviver: each tag as the `ArrayBuffer` it stands for. */
269
+ const untagBytes = (_key, value) => isTag(value) ? bufferOf(value[TAG]) : value;
270
+ /** `value` as JSON would carry it: bytes tagged, at any depth. */
271
+ const bytesTagged = (value) => value === void 0 ? void 0 : JSON.parse(JSON.stringify(value, tagBytes));
272
+ /** `value` with each tag in it, at any depth, as an `ArrayBuffer`. */
273
+ function bytesUntagged(value) {
274
+ if (isTag(value)) return bufferOf(value[TAG]);
275
+ if (Array.isArray(value)) return value.map(bytesUntagged);
276
+ if (isPlain(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, bytesUntagged(item)]));
277
+ return value;
278
+ }
279
+ //#endregion
280
+ export { shapeError as _, tagBytes as a, valueAt as b, TABLE as c, fnv as d, indexFields as f, shapeAt as g, orderable as h, keyBytes as i, defineSchema as l, isIdForm as m, bytesTagged as n, untagBytes as o, int64Value as p, bytesUntagged as r, ID_FORM as s, bytesAsBuffers as t, defineTable as u, tableCode as v, v as y };
@@ -164,12 +164,15 @@ var Aimd = class {
164
164
  return this.v;
165
165
  }
166
166
  };
167
- /** Decorrelated jitter (AWS, "Exponential Backoff And Jitter"): the next wait after `prev` ms is uniform between
168
- * `base` and 3x `prev` (at least `base`), at most `cap`. `rand`: a [0, 1) source (tests pass their own). */
169
- function jitterBackoff(prev, base, cap, rand = Math.random) {
170
- const lo = Math.max(0, fin(base, 0)), hi = Math.max(lo, fin(prev, 0) * 3);
171
- return Math.min(fin(cap, Infinity), lo + rand() * (hi - lo));
172
- }
167
+ //#endregion
168
+ //#region src/database/client/connection.mjs
169
+ /** How long a socket's open may take (its upgrade answered), ms; a reconnect's try still unopened at each of HEDGE_AT
170
+ * (ms from its start) gets another socket beside it, at most three at once. */
171
+ const OPEN_WAIT = 1e4;
172
+ const HEDGE_AT = [100, 200];
173
+ /** A reconnect's waits between tries after the first (which is at once): RETRY_FIRST ms, doubling to RETRY_MAX. */
174
+ const RETRY_FIRST = 50;
175
+ const RETRY_MAX = 1e3;
173
176
  const TAG_TTL = 864e5;
174
177
  const groupOf = (id) => {
175
178
  const t = String(id ?? ""), k = t.indexOf("/");
@@ -237,11 +240,13 @@ const SUBSCRIBE_WINDOW_MS = breakEvenMs({
237
240
  holdUsdPerSec: PUSH_USD / 60,
238
241
  eachUsd: READ_USD
239
242
  });
240
- /** Whether a token says server code: ours with `ro: "server"`, or the platform's for a Database Key (`iss: "midsummer"`,
241
- * `sub: "key:<id>"`; a person's, `user:<handle>`, is not). */
243
+ /** Whether a token says server code: ours with `ro: "server"`, or the platform's for a Database Key (`key:<id>`), a
244
+ * Deployment (`site:<project>:<environment>`) or a CI or Agent run (`workload:<project>:<environment>`), each with
245
+ * `iss: "midsummer"`; a person's, `user:<handle>`, is not. */
246
+ const SERVER_SUBJECTS = /^(?:key|site|workload):/u;
242
247
  const serverToken = (token) => {
243
248
  const p = payloadOf(token);
244
- return p?.ro === "server" || p?.iss === "midsummer" && String(p?.sub ?? "").startsWith("key:");
249
+ return p?.ro === "server" || p?.iss === "midsummer" && SERVER_SUBJECTS.test(String(p?.sub ?? ""));
245
250
  };
246
251
  /** The shape `Connection.connect` takes: "binding" (a server object binding in `opts.env.DATABASE_EDGE` or
247
252
  * `opts.binding`), "server" (a runtime with no `window` / `document`, and a server token), else "browser". `g`: the
@@ -263,6 +268,46 @@ const SHARED = /* @__PURE__ */ new Map();
263
268
  * window is admitted to the main LRU only if a count-min sketch (4 rows of 4-bit-ish counters, halved every 10x the
264
269
  * size in accesses) says it is used more often than the main LRU's victim. `touch` every access (hit or miss), `add`
265
270
  * a missed key: it returns the keys that left the cache (possibly the one leaving the window). */
271
+ /**
272
+ * Where a request to `url` goes, and the headers that name it. A `*.localhost` name is loopback (RFC 6761)
273
+ * whatever the system's resolver says, and a Debian container's says nothing: outside a browser, which
274
+ * resolves it itself and never lets a page set Host, it goes to 127.0.0.1 with the name as its Host
275
+ * (and, over TLS, as the name the certificate is checked for). Anything else goes as it is.
276
+ * const { url, init } = loopback("http://db-a.localhost:8792/ws"); fetch(url, init)
277
+ */
278
+ function loopback(url, g = globalThis) {
279
+ const at = new URL(url);
280
+ if (g.document !== void 0 || !at.hostname.endsWith(".localhost")) return {
281
+ url: String(url),
282
+ init: {}
283
+ };
284
+ const host = at.host, name = at.hostname;
285
+ at.hostname = "127.0.0.1";
286
+ return {
287
+ url: at.href,
288
+ init: {
289
+ headers: { Host: host },
290
+ .../^(https|wss):$/u.test(at.protocol) ? { tls: { serverName: name } } : {}
291
+ }
292
+ };
293
+ }
294
+ /** `fetch` of `url` through `loopback`, `init`'s headers kept beside its Host. */
295
+ const fetchAt = (url, init = {}) => {
296
+ const to = loopback(url);
297
+ return to.init.headers ? fetch(to.url, {
298
+ ...init,
299
+ ...to.init,
300
+ headers: {
301
+ ...Object.fromEntries(new Headers(init.headers ?? {})),
302
+ ...to.init.headers
303
+ }
304
+ }) : fetch(to.url, init);
305
+ };
306
+ /** A WebSocket to `url` through `loopback`. */
307
+ const socketAt = (url) => {
308
+ const to = loopback(url);
309
+ return to.init.headers ? new WebSocket(to.url, to.init) : new WebSocket(to.url);
310
+ };
266
311
  var TinyLfu = class {
267
312
  constructor(size, { windowShare = .01 } = {}) {
268
313
  this.size = Math.max(2, Math.floor(size));
@@ -363,8 +408,8 @@ var Connection = class Connection {
363
408
  ...options,
364
409
  shape
365
410
  };
366
- if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-BzI9at5x.mjs")).idbStore(new URL(url).host);
367
- if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-D-P8_ci_.mjs")).ConnectionTabs.connect(url, o);
411
+ if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-lIZ5GxVv.mjs")).idbStore(new URL(url).host);
412
+ if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-zCh8kceo.mjs")).ConnectionTabs.connect(url, o);
368
413
  return Connection.open(url, o);
369
414
  }
370
415
  /** A Connection over one socket, of the shape given (default "browser"), no detection (tabs.mjs opens its own so). */
@@ -372,6 +417,10 @@ var Connection = class Connection {
372
417
  const g = new Connection(url, options);
373
418
  if (g.store) await g.store.attach(g);
374
419
  if (options.functions) g.predictor = new (await (import("./predict-Drfm_8pO.mjs"))).Predictor(g, options.functions);
420
+ if (options.shape === "server" && options.http !== false) {
421
+ g.http = true;
422
+ return g;
423
+ }
375
424
  await g.open();
376
425
  if (!g.dir) await Promise.race([g.hello, new Promise((r) => setTimeout(r, HELLO_WAIT_MS))]);
377
426
  return g;
@@ -517,7 +566,7 @@ var Connection = class Connection {
517
566
  const exp = expOf(this.token);
518
567
  if (!this.token || exp && exp * 1e3 - Date.now() < 6e4) return true;
519
568
  try {
520
- return (await fetch(this.url.replace(/^ws/u, "http"), { signal: AbortSignal.timeout(1e4) })).status === 401;
569
+ return (await fetchAt(this.url.replace(/^ws/u, "http"), { signal: AbortSignal.timeout(1e4) })).status === 401;
521
570
  } catch {
522
571
  return false;
523
572
  }
@@ -543,13 +592,13 @@ var Connection = class Connection {
543
592
  openOnce() {
544
593
  return new Promise((ready, fail) => {
545
594
  const dialed = this.dial ? Promise.resolve(this.dial(this)) : null;
546
- const ws = dialed ? null : new WebSocket(this.url);
595
+ const ws = dialed ? null : socketAt(this.url);
547
596
  const timer = setTimeout(() => {
548
597
  fail(/* @__PURE__ */ new Error("open timeout"));
549
598
  try {
550
599
  ws?.close(1e3);
551
600
  } catch {}
552
- }, 1e4);
601
+ }, OPEN_WAIT);
553
602
  const opened = (ws) => {
554
603
  clearTimeout(timer);
555
604
  if (this.closed) {
@@ -559,6 +608,13 @@ var Connection = class Connection {
559
608
  ready();
560
609
  return;
561
610
  }
611
+ if (this.ws && this.ws !== ws && this.ws.readyState === 1) {
612
+ try {
613
+ ws.close(1e3);
614
+ } catch {}
615
+ ready();
616
+ return;
617
+ }
562
618
  this.ws = ws;
563
619
  this.heard = this.answeredAt = this.openedAt = performance.now();
564
620
  this.probe = 0;
@@ -608,22 +664,39 @@ var Connection = class Connection {
608
664
  }
609
665
  });
610
666
  }
611
- /** Opens a socket again until one opens (one loop at a time), backing off from `delay` to 5 s. Decorrelated
612
- * jitter (policy `jitterBackoff`): clients a dead edge dropped together do not come back together. */
613
- async reconnect(delay = 100) {
667
+ /** Opens a socket again until one opens (one loop at a time): the first try at once, then after 50 ms doubling to
668
+ * 1 s, each wait jittered (clients a dead server dropped together do not come back together). A try still unopened
669
+ * at 100 ms gets a second socket beside it and at 200 ms a third, and the first to open serves (the others are
670
+ * closed): a socket the network sent to a replica that is gone costs at most 100 ms, while a slow open (a wake, a
671
+ * long replay, a takeover waiting for a dead replica's lease) is never given up. */
672
+ async reconnect(delay = 0) {
614
673
  if (this.reopening || this.closed) return;
615
674
  this.reopening = true;
616
675
  this.stats.reconnects += 1;
676
+ const opens = () => this.open().then(() => true, () => false);
677
+ const firstOf = (tries) => new Promise((done) => {
678
+ let n = 0;
679
+ for (const p of tries) p.then((ok) => {
680
+ if (ok) done(true);
681
+ else if (++n === tries.length) done(false);
682
+ });
683
+ });
617
684
  try {
618
- for (;;) {
619
- await new Promise((r) => setTimeout(r, delay));
685
+ for (let step = RETRY_FIRST;;) {
686
+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));
620
687
  if (this.closed || this.ws?.readyState === 1) return;
621
- try {
622
- await this.open();
623
- return;
624
- } catch {
625
- delay = jitterBackoff(delay, 50, 5e3);
688
+ const tries = [opens()];
689
+ let opened = null;
690
+ for (let k = 0, at = 0; k <= HEDGE_AT.length; k += 1) {
691
+ const wait = k < HEDGE_AT.length ? new Promise((r) => setTimeout(() => r(null), HEDGE_AT[k] - at)) : new Promise(() => {});
692
+ opened = await Promise.race([firstOf(tries), wait]);
693
+ if (opened !== null) break;
694
+ at = HEDGE_AT[k];
695
+ tries.push(opens());
626
696
  }
697
+ if (opened) return;
698
+ delay = step * (.5 + Math.random() / 2);
699
+ step = Math.min(RETRY_MAX, step * 2);
627
700
  }
628
701
  } finally {
629
702
  this.reopening = false;
@@ -739,6 +812,7 @@ var Connection = class Connection {
739
812
  * same tag, and its answer is still read here); "b" or "e": never waits for durable (server shapes), and its round
740
813
  * trip tunes the conflation window. */
741
814
  send(unit, op, keep = false, now = null, route = void 0, relax = null) {
815
+ if (this.http && !this.ws && !this.reopening && !this.closed) this.reconnect(0);
742
816
  const i = op.i ?? this.next++;
743
817
  const o = {
744
818
  i,
@@ -1339,12 +1413,15 @@ var Connection = class Connection {
1339
1413
  this.notifyRow(key);
1340
1414
  }
1341
1415
  const guess = optimistic || as != null ? null : this.predictor?.begin(name, args, route);
1342
- const a = await this.send(this.unitOf(route), {
1416
+ const op = {
1343
1417
  k: "m",
1344
1418
  f: name,
1345
1419
  a: args,
1346
1420
  t: tag ?? this.tag(),
1347
- ...asOf(as),
1421
+ ...asOf(as)
1422
+ };
1423
+ const a = this.http && this.ws?.readyState !== 1 ? await this.overHttp(op) : await this.send(this.unitOf(route), {
1424
+ ...op,
1348
1425
  ...this.urgent()
1349
1426
  }, true, null, route);
1350
1427
  guess?.end(a);
@@ -1355,6 +1432,68 @@ var Connection = class Connection {
1355
1432
  if (refused(a)) throw coded(a);
1356
1433
  return a;
1357
1434
  }
1435
+ /** One query or mutation over HTTP (`POST <db>/call`, the token in its header), with no socket: its answer as a
1436
+ * socket's. A mutation's tag rides with it, so one sent again (after a failure the network gave no answer to)
1437
+ * applies once; a query, or a tagged mutation, is sent again on a 5xx or no answer, twice at most; a 401 renews the
1438
+ * token once. */
1439
+ async overHttp(op) {
1440
+ const body = JSON.stringify([{
1441
+ i: 1,
1442
+ ...op
1443
+ }]), again = op.k === "q" || !!op.t;
1444
+ for (let tries = 0;; tries += 1) {
1445
+ let r;
1446
+ try {
1447
+ r = await fetchAt(`${this.base}/call`, {
1448
+ method: "POST",
1449
+ headers: {
1450
+ authorization: `Bearer ${this.token}`,
1451
+ "content-type": "application/json"
1452
+ },
1453
+ body
1454
+ });
1455
+ } catch (e) {
1456
+ if (again && tries < 2) continue;
1457
+ return {
1458
+ i: 1,
1459
+ ok: false,
1460
+ why: "unavailable",
1461
+ error: String(e?.message ?? e)
1462
+ };
1463
+ }
1464
+ if (r.status === 401 && this.refresh && tries === 0) {
1465
+ await this.renew(false);
1466
+ continue;
1467
+ }
1468
+ const text = await r.text();
1469
+ if (!r.ok) {
1470
+ if (r.status >= 500 && again && tries < 2) continue;
1471
+ let j = {};
1472
+ try {
1473
+ j = JSON.parse(text);
1474
+ } catch {}
1475
+ return {
1476
+ i: 1,
1477
+ ok: false,
1478
+ why: r.status === 401 ? "denied" : j.error ?? "refused",
1479
+ error: j.why ?? text.slice(0, 200)
1480
+ };
1481
+ }
1482
+ for (const line of text.split("\n")) try {
1483
+ const v = JSON.parse(line);
1484
+ if (Array.isArray(v)) {
1485
+ const a = v.find((x) => x?.i === 1);
1486
+ if (a) return a;
1487
+ }
1488
+ } catch {}
1489
+ return {
1490
+ i: 1,
1491
+ ok: false,
1492
+ why: "unavailable",
1493
+ error: "no answer in the call's reply"
1494
+ };
1495
+ }
1496
+ }
1358
1497
  /** An ACTION of a the database app (it may do I/O; not a transaction): called as a mutation is, by reference or
1359
1498
  * name, tagged (a resend after a reconnect is answered from its tag). Resolves its answer. */
1360
1499
  async action(name, args, options = {}) {
@@ -1363,12 +1502,13 @@ var Connection = class Connection {
1363
1502
  /** A query function's value, once, on unit `unit` (default "0"). */
1364
1503
  async query(name, args, { unit = "0", as } = {}) {
1365
1504
  name = fnName(name);
1366
- const a = await this.send(String(unit), {
1505
+ const op = {
1367
1506
  k: "q",
1368
1507
  f: name,
1369
1508
  a: args,
1370
1509
  ...asOf(as)
1371
- });
1510
+ };
1511
+ const a = this.http && this.ws?.readyState !== 1 ? await this.overHttp(op) : await this.send(String(unit), op);
1372
1512
  if (!a.ok) throw coded(a);
1373
1513
  return a.value;
1374
1514
  }
@@ -1485,7 +1625,7 @@ var Connection = class Connection {
1485
1625
  }
1486
1626
  /** Stores a file (R2) and its `_files` row (owner: this user); resolves its id. */
1487
1627
  async upload(blob, name) {
1488
- const put = () => fetch(`${this.base}/files?${this.auth()}&name=${encodeURIComponent(name)}`, {
1628
+ const put = () => fetchAt(`${this.base}/files?${this.auth()}&name=${encodeURIComponent(name)}`, {
1489
1629
  method: "PUT",
1490
1630
  body: blob
1491
1631
  });
@@ -1780,7 +1920,7 @@ var Connection = class Connection {
1780
1920
  }
1781
1921
  const home = this.homes.get(hk);
1782
1922
  if (!home) return null;
1783
- const ws = new WebSocket(`${this.base.replace(/^http/u, "ws")}/ws?token=${encodeURIComponent(this.token)}&home=${encodeURIComponent(home)}`);
1923
+ const ws = socketAt(`${this.base.replace(/^http/u, "ws")}/ws?token=${encodeURIComponent(this.token)}&home=${encodeURIComponent(home)}`);
1784
1924
  lane = {
1785
1925
  unit,
1786
1926
  ws,
@@ -1868,4 +2008,4 @@ var Connection = class Connection {
1868
2008
  }
1869
2009
  };
1870
2010
  //#endregion
1871
- export { TAG_TTL as n, Connection as t };
2011
+ export { payloadOf as i, TAG_TTL as n, fetchAt as r, Connection as t };
@@ -1,2 +1,2 @@
1
- import { a as isSource, i as buildDatabase, n as BuiltFunction, o as typeOf, r as Refused, t as Built } from "../build-SQ44jwSa.mjs";
2
- export { Built, BuiltFunction, Refused, buildDatabase, isSource, typeOf };
1
+ import { a as MODULE_BYTES, c as blockNames, d as exported, f as isSource, i as BuiltFunction, l as buildDatabase, m as unboundCalls, n as BUILD_FILES, o as Packages, p as typeOf, r as Built, s as Refused, t as BUILD_BYTES, u as enumAsObject } from "../build-DQo-JrlN.mjs";
2
+ export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };