ezship 0.1.11 → 0.1.13

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.
package/session.d.mts ADDED
@@ -0,0 +1,20 @@
1
+ // Hand-written declarations for cli/session.mjs: Session State (docs/adr/0088).
2
+ import type { Shape } from "./shape.d.mts";
3
+
4
+ export const SESSION_FILE: "session.ts";
5
+ export const SESSION_PATH: "/_ez/session";
6
+ export const SESSION_VERSION_KEY: "~session";
7
+ export const SESSION_LIMITS: Readonly<{ keys: number; valueBytes: number }>;
8
+
9
+ /** `saved` survives sign-out and devices; `signedIn` ends with the sign-in. */
10
+ export type SessionLifetime = "saved" | "signedIn";
11
+ export type SessionDeclaration = {
12
+ keys: Record<string, { lifetime: SessionLifetime; shape: Shape }>;
13
+ };
14
+
15
+ export function parseSessionDeclaration(source: string): SessionDeclaration | { error: string };
16
+ export function sessionValueError(
17
+ declaration: SessionDeclaration,
18
+ key: string,
19
+ value: unknown,
20
+ ): string | null;
package/session.mjs ADDED
@@ -0,0 +1,142 @@
1
+ // Session State (docs/adr/0088): typed per-viewer values an Instance declares in `global/session.ts`. The
2
+ // file is TypeScript the Pipeline compiles, but its `Saved` and `SignedIn` types are written in the JSON TYPE
3
+ // subset (shape.mjs), so the Host can read them without a compiler and check every write. Pure and
4
+ // zero-dependency, like the rest of the contract.
5
+
6
+ import { parseShape, shapeError } from "./shape.mjs";
7
+
8
+ /** @typedef {import("./session.d.mts").SessionDeclaration} SessionDeclaration */
9
+
10
+ /** The Global Workspace file that declares Provided values and Session State. */
11
+ export const SESSION_FILE = "session.ts";
12
+ /** Where a page reads (GET) and writes (PUT `/<key>`) its viewer's Session State, under the Site's prefix. */
13
+ export const SESSION_PATH = "/_ez/session";
14
+ /** The viewer's own counter in the live version map (docs/adr/0053); no Table can have this name. */
15
+ export const SESSION_VERSION_KEY = "~session";
16
+ /** At most this many keys per Instance, each value at most this many bytes of JSON. */
17
+ export const SESSION_LIMITS = Object.freeze({ keys: 32, valueBytes: 4096 });
18
+
19
+ const KEY_RE = /^[a-z][A-Za-z0-9]*$/;
20
+ const LIFETIMES = /** @type {const} */ ([
21
+ ["Saved", "saved"],
22
+ ["SignedIn", "signedIn"],
23
+ ]);
24
+ const SHAPE = `${SESSION_FILE} exports \`type Provided = { ... }\`, \`type Saved = { ... }\`, \`type SignedIn = { ... }\` and \`const defaults: Saved & SignedIn = { ... }\` (each may be empty).`;
25
+
26
+ /**
27
+ * The source with comments blanked out (same length, so offsets still point into the original); quoted
28
+ * text is kept, so a "//" inside a string literal type survives.
29
+ * @param {string} source
30
+ */
31
+ function blankComments(source) {
32
+ let out = "";
33
+ let i = 0;
34
+ while (i < source.length) {
35
+ const c = source[i];
36
+ if (c === '"' || c === "'" || c === "`") {
37
+ let j = i + 1;
38
+ while (j < source.length && source[j] !== c) j += source[j] === "\\" ? 2 : 1;
39
+ out += source.slice(i, j + 1);
40
+ i = j + 1;
41
+ } else if (source.startsWith("//", i)) {
42
+ const end = source.indexOf("\n", i);
43
+ const stop = end < 0 ? source.length : end;
44
+ out += " ".repeat(stop - i);
45
+ i = stop;
46
+ } else if (source.startsWith("/*", i)) {
47
+ const end = source.indexOf("*/", i + 2);
48
+ const stop = end < 0 ? source.length : end + 2;
49
+ out += source.slice(i, stop).replace(/[^\n]/g, " ");
50
+ i = stop;
51
+ } else {
52
+ out += c;
53
+ i++;
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * The balanced `{ ... }` starting at `start`, or null.
61
+ * @param {string} text @param {number} start
62
+ */
63
+ function braced(text, start) {
64
+ if (text[start] !== "{") return null;
65
+ let depth = 0;
66
+ for (let i = start; i < text.length; i++) {
67
+ const c = text[i];
68
+ if (c === '"' || c === "'") {
69
+ let j = i + 1;
70
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
71
+ i = j;
72
+ } else if (c === "{") depth++;
73
+ else if (c === "}" && --depth === 0) return text.slice(start, i + 1);
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * The Session State keys `global/session.ts` declares, with their lifetimes and shapes, or what is wrong.
80
+ * @type {typeof import("./session.d.mts").parseSessionDeclaration}
81
+ */
82
+ export function parseSessionDeclaration(source) {
83
+ const text = blankComments(source);
84
+ for (const name of ["Provided", "Saved", "SignedIn"])
85
+ if (!new RegExp(`^export\\s+type\\s+${name}\\s*=`, "m").test(text))
86
+ return { error: `${SESSION_FILE} has no \`export type ${name}\`. ${SHAPE}` };
87
+ if (!/^export\s+const\s+defaults\s*:\s*Saved\s*&\s*SignedIn\s*=/m.test(text))
88
+ return {
89
+ error: `${SESSION_FILE} has no \`export const defaults: Saved & SignedIn = { ... }\`. ${SHAPE}`,
90
+ };
91
+ /** @type {SessionDeclaration["keys"]} */
92
+ const keys = {};
93
+ for (const [name, lifetime] of LIFETIMES) {
94
+ const m = new RegExp(`^export\\s+type\\s+${name}\\s*=\\s*`, "m").exec(text);
95
+ const body = m ? braced(text, m.index + m[0].length) : null;
96
+ if (!body)
97
+ return {
98
+ error: `${SESSION_FILE}: ${name} is an object type written out, \`export type ${name} = { key: string | null }\`.`,
99
+ };
100
+ const parsed = parseShape(body, 16_000);
101
+ if ("error" in parsed)
102
+ return {
103
+ error: `${SESSION_FILE}: ${name}: ${parsed.error.replace(/^TYPE: /, "")}. Session State is written in the JSON TYPE subset: string, number, boolean, null, DateString, EpochMs, Cents, literals, { ... }, T[] and Record<string, T>; never a named type.`,
104
+ };
105
+ if (parsed.shape.kind !== "object")
106
+ return { error: `${SESSION_FILE}: ${name} is an object type.` };
107
+ for (const prop of parsed.shape.props) {
108
+ if (!KEY_RE.test(prop.name))
109
+ return {
110
+ error: `${SESSION_FILE}: ${name}.${prop.name}: a Session State key is camelCase (activeCompanyId).`,
111
+ };
112
+ if (prop.optional)
113
+ return {
114
+ error: `${SESSION_FILE}: ${name}.${prop.name} is optional; every key has a value from defaults (use \`T | null\`).`,
115
+ };
116
+ if (Object.hasOwn(keys, prop.name))
117
+ return {
118
+ error: `${SESSION_FILE}: ${prop.name} is declared in both Saved and SignedIn; a key has one lifetime.`,
119
+ };
120
+ keys[prop.name] = { lifetime, shape: prop.type };
121
+ }
122
+ }
123
+ if (Object.keys(keys).length > SESSION_LIMITS.keys)
124
+ return {
125
+ error: `${SESSION_FILE} declares ${Object.keys(keys).length} Session State keys; the limit is ${SESSION_LIMITS.keys}.`,
126
+ };
127
+ return { keys };
128
+ }
129
+
130
+ /**
131
+ * Why a page or function may not store `value` under `key`, or null.
132
+ * @type {typeof import("./session.d.mts").sessionValueError}
133
+ */
134
+ export function sessionValueError(declaration, key, value) {
135
+ if (!Object.hasOwn(declaration.keys, key))
136
+ return `${key} is not Session State this Instance declares in global/${SESSION_FILE}.`;
137
+ const encoded = JSON.stringify(value);
138
+ if (encoded === undefined) return `${key} must be a JSON value.`;
139
+ if (new TextEncoder().encode(encoded).length > SESSION_LIMITS.valueBytes)
140
+ return `${key} is larger than ${SESSION_LIMITS.valueBytes} bytes of JSON.`;
141
+ return shapeError(declaration.keys[key].shape, value, key);
142
+ }
package/shape.d.mts ADDED
@@ -0,0 +1,14 @@
1
+ // Hand-written declarations for cli/shape.mjs: a JSON column's declared TYPE (docs/adr/0078).
2
+
3
+ export type Shape =
4
+ | { kind: "string" | "number" | "boolean" | "null" | "unknown" | "date" | "epoch" | "cents" }
5
+ | { kind: "literal"; value: string | number | boolean }
6
+ | { kind: "array" | "record"; of: Shape }
7
+ | { kind: "object"; props: { name: string; optional: boolean; type: Shape }[] }
8
+ | { kind: "union"; of: Shape[] };
9
+
10
+ export function isCalendarDate(value: unknown): value is string;
11
+ /** `maxLength` defaults to a column's 2,000 characters; Session State (ADR 0088) declares a whole object. */
12
+ export function parseShape(text: string, maxLength?: number): { shape: Shape } | { error: string };
13
+ export function printShape(shape: Shape): string;
14
+ export function shapeError(shape: Shape, value: unknown, path: string): string | null;
package/shape.mjs ADDED
@@ -0,0 +1,312 @@
1
+ // A JSON column's declared shape (docs/adr/0078): `<col> JSON TYPE '<shape>'` in db/schema.sql, written in a
2
+ // small TypeScript subset. The same parse gives the generated TypeScript type and the validator every page and
3
+ // function write passes through. Pure and zero-dependency, like the rest of the contract.
4
+ //
5
+ // shape := member ("|" member)* a leading "|" is allowed
6
+ // member := primary ("[" "]")*
7
+ // primary := string | number | boolean | null | unknown | DateString | EpochMs | Cents
8
+ // | "text" | 'text' | <number> | true | false
9
+ // | "{" (name "?"? ":" shape (";" | ",")?)* "}"
10
+ // | "(" shape ")" | Array "<" shape ">" | Record "<" string "," shape ">"
11
+
12
+ /** @typedef {import("./shape.d.mts").Shape} Shape */
13
+
14
+ /** The longest shape a column may declare, in characters. */
15
+ const MAX_SHAPE_LENGTH = 2000;
16
+ const MAX_DEPTH = 16;
17
+ const NAME_RE = /^[A-Za-z_$][\w$]*$/;
18
+ const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
19
+
20
+ /**
21
+ * Whether `value` is a calendar date written YYYY-MM-DD (a DATE column's value, a `DateString`).
22
+ * @param {unknown} value @returns {value is string}
23
+ */
24
+ export function isCalendarDate(value) {
25
+ if (typeof value !== "string") return false;
26
+ const m = DATE_RE.exec(value);
27
+ if (!m) return false;
28
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
29
+ return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1;
30
+ }
31
+
32
+ /** @param {string} text */
33
+ function tokenize(text) {
34
+ /** @type {{ kind: "word" | "string" | "number" | "punct"; text: string; value?: string | number }[]} */
35
+ const tokens = [];
36
+ let i = 0;
37
+ while (i < text.length) {
38
+ const c = text[i];
39
+ if (/\s/.test(c)) {
40
+ i++;
41
+ continue;
42
+ }
43
+ if (c === '"' || c === "'") {
44
+ let j = i + 1;
45
+ let value = "";
46
+ for (; j < text.length && text[j] !== c; j++) {
47
+ if (text[j] === "\\") j++;
48
+ value += text[j] ?? "";
49
+ }
50
+ if (j >= text.length) return { error: "an unterminated string literal" };
51
+ tokens.push({ kind: "string", text: text.slice(i, j + 1), value });
52
+ i = j + 1;
53
+ continue;
54
+ }
55
+ const number = /^-?\d+(\.\d+)?/.exec(text.slice(i));
56
+ if (number) {
57
+ tokens.push({ kind: "number", text: number[0], value: Number(number[0]) });
58
+ i += number[0].length;
59
+ continue;
60
+ }
61
+ const word = /^[A-Za-z_$][\w$]*/.exec(text.slice(i));
62
+ if (word) {
63
+ tokens.push({ kind: "word", text: word[0] });
64
+ i += word[0].length;
65
+ continue;
66
+ }
67
+ if ("{}[]()<>|;,:?".includes(c)) {
68
+ tokens.push({ kind: "punct", text: c });
69
+ i++;
70
+ continue;
71
+ }
72
+ return { error: `unexpected "${c}"` };
73
+ }
74
+ return { tokens };
75
+ }
76
+
77
+ const PRIMITIVES = /** @type {const} */ ({
78
+ string: "string",
79
+ number: "number",
80
+ boolean: "boolean",
81
+ null: "null",
82
+ unknown: "unknown",
83
+ DateString: "date",
84
+ EpochMs: "epoch",
85
+ Cents: "cents",
86
+ });
87
+
88
+ /**
89
+ * Parses a declared shape, or says what is wrong with it.
90
+ * @type {typeof import("./shape.d.mts").parseShape}
91
+ */
92
+ export function parseShape(text, maxLength = MAX_SHAPE_LENGTH) {
93
+ if (text.length > maxLength) return { error: `a TYPE is at most ${maxLength} characters` };
94
+ const lexed = tokenize(text);
95
+ if ("error" in lexed) return { error: `TYPE: ${lexed.error}` };
96
+ const { tokens } = lexed;
97
+ let i = 0;
98
+ const peek = (t = 0) => tokens[i + t];
99
+ /** @param {string} p */
100
+ const isPunct = (p, t = 0) => peek(t)?.kind === "punct" && peek(t)?.text === p;
101
+ /** @param {string} p */
102
+ const expect = (p) => {
103
+ if (!isPunct(p))
104
+ throw new Error(`expected ${p}${peek() ? ` before ${peek()?.text}` : " at the end"}`);
105
+ i++;
106
+ };
107
+ /** @param {number} depth @returns {Shape} */
108
+ const union = (depth) => {
109
+ if (depth > MAX_DEPTH) throw new Error(`nested more than ${MAX_DEPTH} levels`);
110
+ if (isPunct("|")) i++;
111
+ const members = [member(depth)];
112
+ while (isPunct("|")) {
113
+ i++;
114
+ members.push(member(depth));
115
+ }
116
+ return members.length === 1 ? members[0] : { kind: "union", of: members };
117
+ };
118
+ /** @param {number} depth @returns {Shape} */
119
+ const member = (depth) => {
120
+ let shape = primary(depth);
121
+ while (isPunct("[") && isPunct("]", 1)) {
122
+ i += 2;
123
+ shape = { kind: "array", of: shape };
124
+ }
125
+ return shape;
126
+ };
127
+ /** @param {number} depth @returns {Shape} */
128
+ const primary = (depth) => {
129
+ const t = peek();
130
+ if (!t) throw new Error("a type is missing at the end");
131
+ if (t.kind === "string") {
132
+ i++;
133
+ return { kind: "literal", value: /** @type {string} */ (t.value) };
134
+ }
135
+ if (t.kind === "number") {
136
+ i++;
137
+ return { kind: "literal", value: /** @type {number} */ (t.value) };
138
+ }
139
+ if (t.kind === "word") {
140
+ i++;
141
+ if (t.text === "true" || t.text === "false")
142
+ return { kind: "literal", value: t.text === "true" };
143
+ if (Object.hasOwn(PRIMITIVES, t.text))
144
+ return { kind: PRIMITIVES[/** @type {keyof typeof PRIMITIVES} */ (t.text)] };
145
+ if (t.text === "Array") {
146
+ expect("<");
147
+ const of = union(depth + 1);
148
+ expect(">");
149
+ return { kind: "array", of };
150
+ }
151
+ if (t.text === "Record") {
152
+ expect("<");
153
+ if (peek()?.text !== "string") throw new Error("Record keys are string: Record<string, T>");
154
+ i++;
155
+ expect(",");
156
+ const of = union(depth + 1);
157
+ expect(">");
158
+ return { kind: "record", of };
159
+ }
160
+ throw new Error(
161
+ `${t.text} is not a TYPE: use string, number, boolean, null, unknown, DateString, EpochMs, Cents, literals, { ... }, T[], Array<T> or Record<string, T>`,
162
+ );
163
+ }
164
+ if (t.text === "(") {
165
+ i++;
166
+ const inner = union(depth + 1);
167
+ expect(")");
168
+ return inner;
169
+ }
170
+ if (t.text === "{") {
171
+ i++;
172
+ /** @type {{ name: string; optional: boolean; type: Shape }[]} */
173
+ const props = [];
174
+ while (!isPunct("}")) {
175
+ const key = peek();
176
+ if (!key || (key.kind !== "word" && key.kind !== "string"))
177
+ throw new Error(`expected a property name${key ? ` before ${key.text}` : ""}`);
178
+ i++;
179
+ const name = key.kind === "string" ? /** @type {string} */ (key.value) : key.text;
180
+ if (props.some((p) => p.name === name))
181
+ throw new Error(`property ${name} is declared twice`);
182
+ const optional = isPunct("?");
183
+ if (optional) i++;
184
+ expect(":");
185
+ props.push({ name, optional, type: union(depth + 1) });
186
+ if (isPunct(";") || isPunct(",")) i++;
187
+ else if (!isPunct("}")) throw new Error(`expected ; or } after property ${name}`);
188
+ }
189
+ i++;
190
+ return { kind: "object", props };
191
+ }
192
+ throw new Error(`unexpected ${t.text}`);
193
+ };
194
+ try {
195
+ const shape = union(0);
196
+ if (i < tokens.length) throw new Error(`unexpected ${tokens[i].text} after the type`);
197
+ return { shape };
198
+ } catch (error) {
199
+ return { error: `TYPE: ${error instanceof Error ? error.message : String(error)}` };
200
+ }
201
+ }
202
+
203
+ /**
204
+ * The shape as TypeScript: what db/types.d.ts declares and what a column's declaration records.
205
+ * @type {typeof import("./shape.d.mts").printShape}
206
+ */
207
+ export function printShape(shape) {
208
+ switch (shape.kind) {
209
+ case "string":
210
+ case "number":
211
+ case "boolean":
212
+ case "null":
213
+ case "unknown":
214
+ return shape.kind;
215
+ case "date":
216
+ return "DateString";
217
+ case "epoch":
218
+ return "EpochMs";
219
+ case "cents":
220
+ return "Cents";
221
+ case "literal":
222
+ return JSON.stringify(shape.value);
223
+ case "array": {
224
+ const inner = printShape(shape.of);
225
+ return shape.of.kind === "union" ? `(${inner})[]` : `${inner}[]`;
226
+ }
227
+ case "record":
228
+ return `Record<string, ${printShape(shape.of)}>`;
229
+ case "object":
230
+ return shape.props.length
231
+ ? `{ ${shape.props.map((p) => `${NAME_RE.test(p.name) ? p.name : JSON.stringify(p.name)}${p.optional ? "?" : ""}: ${printShape(p.type)}`).join("; ")} }`
232
+ : "{}";
233
+ case "union":
234
+ return shape.of.map(printShape).join(" | ");
235
+ }
236
+ }
237
+
238
+ /** @param {unknown} v @returns {v is Record<string, unknown>} */
239
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
240
+
241
+ /** @param {string} path @param {string} key */
242
+ const child = (path, key) =>
243
+ NAME_RE.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
244
+
245
+ /**
246
+ * Why `value` does not match `shape`, naming the path to the bad value from `path` (the column), or null.
247
+ * @type {typeof import("./shape.d.mts").shapeError}
248
+ */
249
+ export function shapeError(shape, value, path) {
250
+ /** @param {string} want */
251
+ const wrong = (want) => `${path} must be ${want}`;
252
+ switch (shape.kind) {
253
+ case "unknown":
254
+ return null;
255
+ case "string":
256
+ return typeof value === "string" ? null : wrong("a string");
257
+ case "number":
258
+ return typeof value === "number" && Number.isFinite(value) ? null : wrong("a number");
259
+ case "boolean":
260
+ return typeof value === "boolean" ? null : wrong("true or false");
261
+ case "null":
262
+ return value === null ? null : wrong("null");
263
+ case "date":
264
+ return isCalendarDate(value) ? null : wrong("a date (YYYY-MM-DD)");
265
+ case "epoch":
266
+ return typeof value === "number" && Number.isInteger(value)
267
+ ? null
268
+ : wrong("epoch milliseconds (an integer)");
269
+ case "cents":
270
+ return typeof value === "number" && Number.isSafeInteger(value)
271
+ ? null
272
+ : wrong("a whole number of cents (Cents)");
273
+ case "literal":
274
+ return value === shape.value ? null : wrong(JSON.stringify(shape.value));
275
+ case "array": {
276
+ if (!Array.isArray(value)) return wrong("an array");
277
+ for (let i = 0; i < value.length; i++) {
278
+ const bad = shapeError(shape.of, value[i], `${path}[${i}]`);
279
+ if (bad) return bad;
280
+ }
281
+ return null;
282
+ }
283
+ case "record": {
284
+ if (!isObject(value)) return wrong("an object");
285
+ for (const [k, v] of Object.entries(value)) {
286
+ const bad = shapeError(shape.of, v, child(path, k));
287
+ if (bad) return bad;
288
+ }
289
+ return null;
290
+ }
291
+ case "object": {
292
+ if (!isObject(value)) return wrong("an object");
293
+ for (const p of shape.props) {
294
+ if (value[p.name] === undefined) {
295
+ if (p.optional) continue;
296
+ return `${child(path, p.name)} is required`;
297
+ }
298
+ const bad = shapeError(p.type, value[p.name], child(path, p.name));
299
+ if (bad) return bad;
300
+ }
301
+ for (const k of Object.keys(value))
302
+ if (!shape.props.some((p) => p.name === k))
303
+ return `${child(path, k)} is not in the declared TYPE`;
304
+ return null;
305
+ }
306
+ case "union": {
307
+ if (shape.of.some((s) => shapeError(s, value, path) === null)) return null;
308
+ const want = printShape(shape);
309
+ return wrong(want.length > 120 ? "one of the declared TYPE's members" : want);
310
+ }
311
+ }
312
+ }
package/signup.d.mts ADDED
@@ -0,0 +1,11 @@
1
+ import type { SignupInput, SignupChallenge, SignupResult } from "./types.d.mts";
2
+ export const TRIAL_HOST: "https://api.ezship.dev";
3
+ export const TRIAL_STATUS_PATH: "/api/trial";
4
+ export const SIGNUP_ROUTES: Readonly<{ start: string; complete: string }>;
5
+ export const SIGNUP_LINK_RE: RegExp;
6
+ export function signupLinkFromHash(hash: string): string | undefined;
7
+ export function signupClient(send?: typeof fetch): {
8
+ start(input: SignupInput): Promise<SignupChallenge>;
9
+ complete(receipt: string, code: string): Promise<SignupResult>;
10
+ open(link: string): Promise<SignupResult>;
11
+ };
package/signup.mjs ADDED
@@ -0,0 +1,42 @@
1
+ /** The public bootstrap exception (ADRs 0062, 0064). Provisioning has one destination: the trial Host. */
2
+ export const TRIAL_HOST = "https://api.ezship.dev";
3
+ export const TRIAL_STATUS_PATH = "/api/trial";
4
+ export const SIGNUP_ROUTES = Object.freeze({
5
+ start: "/cli/signup/start",
6
+ complete: "/cli/signup/complete",
7
+ });
8
+ /** ADR 0064: the verification email's Studio button opens `<studio>/#signup=<link>`. */
9
+ export const SIGNUP_LINK_RE = /^[A-Za-z0-9]{43}$/;
10
+
11
+ /**
12
+ * The link a Studio page was opened with, from its fragment, so no request line ever holds it.
13
+ * @type {typeof import("./signup.d.mts").signupLinkFromHash}
14
+ */
15
+ export function signupLinkFromHash(hash) {
16
+ return /^#(?:.*&)?signup=([A-Za-z0-9]{43})(?:&|$)/.exec(hash)?.[1];
17
+ }
18
+
19
+ /** @param {typeof fetch} [send] */
20
+ export function signupClient(send = fetch) {
21
+ /** @param {string} path @param {unknown} body */
22
+ async function post(path, body) {
23
+ const response = await send(TRIAL_HOST + path, {
24
+ method: "POST",
25
+ headers: { "content-type": "application/json" },
26
+ body: JSON.stringify(body),
27
+ redirect: "error",
28
+ });
29
+ const result = await response.json().catch(() => null);
30
+ if (!response.ok || !result)
31
+ throw new Error(result?.error || `Trial signup is unavailable (HTTP ${response.status}).`);
32
+ return result;
33
+ }
34
+ return {
35
+ /** @param {import('./types.d.mts').SignupInput} input @returns {Promise<import('./types.d.mts').SignupChallenge>} */
36
+ start: (input) => post(SIGNUP_ROUTES.start, input),
37
+ /** @param {string} receipt @param {string} code @returns {Promise<import('./types.d.mts').SignupResult>} */
38
+ complete: (receipt, code) => post(SIGNUP_ROUTES.complete, { receipt, code }),
39
+ /** @param {string} link @returns {Promise<import('./types.d.mts').SignupResult>} */
40
+ open: (link) => post(SIGNUP_ROUTES.complete, { link }),
41
+ };
42
+ }