@karpoland/sdk 0.0.0-stage → 1.0.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.
package/dist/page.js ADDED
@@ -0,0 +1,135 @@
1
+ import {
2
+ PlatformError,
3
+ createTransport,
4
+ enc,
5
+ randomKey
6
+ } from "./chunk-TRJPD7KM.js";
7
+
8
+ // src/page.ts
9
+ var one = async (key, p) => (await p)?.[key];
10
+ function createPageClient(opts = {}) {
11
+ const win = opts.window ?? globalThis.window;
12
+ const before = opts.refreshBeforeMs ?? 3e4;
13
+ let launch = null;
14
+ let timer;
15
+ const listeners = { launch: /* @__PURE__ */ new Set(), refresh: /* @__PURE__ */ new Set(), error: /* @__PURE__ */ new Set(), "session.updated": /* @__PURE__ */ new Set(), "install.updated": /* @__PURE__ */ new Set() };
16
+ const emit = (ev, d) => listeners[ev].forEach((fn) => fn(d));
17
+ let readyWaiters = [];
18
+ let refreshWaiters = [];
19
+ const post = (type) => win?.parent?.postMessage({ type }, "*");
20
+ const schedule = () => {
21
+ if (timer) clearTimeout(timer);
22
+ if (!launch) return;
23
+ const ms = new Date(launch.expires_at).getTime() - Date.now() - before;
24
+ timer = setTimeout(() => void client.refresh().catch((e) => emit("error", e)), Math.max(1e3, ms));
25
+ timer.unref?.();
26
+ };
27
+ const accept = (l) => {
28
+ const first = !launch;
29
+ launch = l;
30
+ schedule();
31
+ emit(first ? "launch" : "refresh", l);
32
+ readyWaiters.forEach((r) => r(l));
33
+ readyWaiters = [];
34
+ refreshWaiters.forEach((w) => w.resolve(l));
35
+ refreshWaiters = [];
36
+ };
37
+ const onMessage = (e) => {
38
+ if (!win || e.source !== win.parent) return;
39
+ const ev = e.data;
40
+ if (ev?.type === "karpo:event" && (ev.event === "session.updated" || ev.event === "install.updated")) {
41
+ emit(ev.event, { event: ev.event, ...ev.session_id ? { session_id: String(ev.session_id) } : {}, ...ev.install_id ? { install_id: String(ev.install_id) } : {} });
42
+ return;
43
+ }
44
+ const d = e.data;
45
+ if (!d || d.type !== "karpo:launch" || typeof d.token !== "string") return;
46
+ accept({ type: "karpo:launch", token: d.token, expires_at: String(d.expires_at ?? ""), context: d.context ?? {}, api: String(d.api ?? "") });
47
+ };
48
+ const waitLaunch = () => launch ? Promise.resolve(launch) : new Promise((resolve, reject) => {
49
+ const t = setTimeout(() => reject(new Error("karpoland: no karpo:launch from the parent frame; is the page opened inside Karpo Land?")), opts.launchTimeoutMs ?? 15e3);
50
+ readyWaiters.push((l) => (clearTimeout(t), resolve(l)));
51
+ });
52
+ const request = async (method, path, body, query, extra = {}) => {
53
+ const l = await waitLaunch();
54
+ const t = createTransport({
55
+ base: l.api,
56
+ fetch: opts.fetch,
57
+ retry: opts.retry,
58
+ headers: () => ({ Authorization: `Bearer ${launch?.token ?? l.token}` }),
59
+ onUnauthorized: async () => {
60
+ try {
61
+ await client.refresh();
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ });
68
+ return t.request(method, path, { body, query, ...extra });
69
+ };
70
+ const client = {
71
+ ready: async () => (await waitLaunch()).context,
72
+ get context() {
73
+ return launch?.context ?? null;
74
+ },
75
+ get launch() {
76
+ return launch;
77
+ },
78
+ on(ev, fn) {
79
+ listeners[ev].add(fn);
80
+ return () => listeners[ev].delete(fn);
81
+ },
82
+ async callTool(tool, args = {}, o = {}) {
83
+ const key = o.idempotencyKey ?? randomKey("page-");
84
+ const r = await request("POST", `/tools/${enc(tool)}`, { args, session_id: o.sessionId, install_id: o.installId }, void 0, { headers: { "Idempotency-Key": key }, idempotent: true });
85
+ return r.call;
86
+ },
87
+ sessions: {
88
+ get: (id) => one("session", request("GET", `/sessions/${enc(id)}`)),
89
+ join: (id, o = {}) => request("POST", `/sessions/${enc(id)}/join`, o),
90
+ leave: (id) => one("participant", request("POST", `/sessions/${enc(id)}/leave`, {})),
91
+ respond: (id, accept2) => one("participant", request("POST", `/sessions/${enc(id)}/respond`, { accept: accept2 }))
92
+ },
93
+ boards: {
94
+ get: (ref, query = {}) => one("board", request("GET", "/boards", void 0, { ref, ...query })),
95
+ list: async (query = {}) => await one("boards", request("GET", "/boards", void 0, query)) ?? []
96
+ },
97
+ residents: {
98
+ async get(ids) {
99
+ const want = [...new Set(ids.filter(Boolean).map(String))];
100
+ const out = [];
101
+ for (let i = 0; i < want.length; i += 100) {
102
+ const r = await request("GET", "/residents", void 0, { ids: want.slice(i, i + 100).join(",") });
103
+ out.push(...r.residents ?? []);
104
+ }
105
+ return out;
106
+ }
107
+ },
108
+ refresh() {
109
+ if (!win?.parent) return Promise.reject(new PlatformError(401, { status: "UNAUTHENTICATED", reason: "auth.TOKEN_INVALID", message: "no parent frame to refresh the launch token" }));
110
+ return new Promise((resolve, reject) => {
111
+ const waiter = { resolve: (l) => (clearTimeout(t), resolve(l)), reject };
112
+ const t = setTimeout(() => {
113
+ refreshWaiters = refreshWaiters.filter((w) => w !== waiter);
114
+ reject(new Error("karpoland: the parent frame did not send a fresh launch"));
115
+ }, opts.launchTimeoutMs ?? 15e3);
116
+ refreshWaiters.push(waiter);
117
+ post("karpo:refresh");
118
+ });
119
+ },
120
+ request: (method, path, body, query) => request(method, path, body, query),
121
+ destroy() {
122
+ if (timer) clearTimeout(timer);
123
+ win?.removeEventListener("message", onMessage);
124
+ }
125
+ };
126
+ win?.addEventListener("message", onMessage);
127
+ if (opts.launch) accept({ type: "karpo:launch", ...opts.launch });
128
+ else post("karpo:ready");
129
+ return client;
130
+ }
131
+ export {
132
+ PlatformError,
133
+ createPageClient
134
+ };
135
+ //# sourceMappingURL=page.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/page.ts"],"sourcesContent":["// The page client: runs in an app page that Karpo Land frames in a sandboxed\n// iframe (opaque origin, no cookies). The page gets a launch token (kal_,\n// 5 minutes) from the parent frame by postMessage and calls /v1/page/* with\n// it; the client asks for a fresh token before the old one expires.\n//\n// parent → page {type: \"karpo:launch\", token, expires_at, context, api}\n// {type: \"karpo:event\", event, session_id?, install_id?}\n// (session.updated / install.updated of this frame's session or install)\n// page → parent {type: \"karpo:ready\"} (send the launch again)\n// {type: \"karpo:refresh\"} (the token is about to expire)\n//\n// A page refreshes on those change signals: keep public state in the\n// session's display and read it with sessions.get (read by the platform,\n// not delivered to the app); call a tool only for private state, and poll\n// no more often than every 30 seconds. A page that connects to the app's own\n// service directly gets no trusted viewer identity: writes that depend on\n// who the viewer is go through callTool (the app gets a signed delivery and\n// a trusted ctx.caller).\n\nimport { PlatformError } from \"./errors.js\";\nimport { createTransport, enc, randomKey, type FetchLike, type RetryOptions } from \"./http.js\";\nimport type { AddParticipantResponse, Board, Call, GetBoardQuery, Id, Json, ListBoardsQuery, Participant, Resident, Session } from \"./types.js\";\n\nexport { PlatformError } from \"./errors.js\";\n\n/** What the page was opened for (the launch's context): the only context shape. */\nexport interface PageContext {\n resident_id: Id;\n /** The app's slug. */\n app: string;\n locale?: string;\n room_id?: Id;\n install_id?: Id;\n session_id?: Id;\n /** The viewer: {id, name, kind, avatar_url?}. */\n me?: Resident;\n [k: string]: Json | Resident | undefined;\n}\n\n/** A change signal the parent frame forwards (karpo:event). */\nexport interface PageChange {\n event: \"session.updated\" | \"install.updated\";\n session_id?: Id;\n install_id?: Id;\n}\n\n/** The launch message from the parent frame. */\nexport interface Launch {\n type: \"karpo:launch\";\n token: string;\n expires_at: string;\n context: PageContext;\n /** The page API base, e.g. https://im.karpo.land/v1/page. */\n api: string;\n}\n\nexport interface PageClientOptions {\n /** Ask for a new token this long before expiry; default 30 s. */\n refreshBeforeMs?: number;\n /** How long ready() waits for the launch; default 15 s. */\n launchTimeoutMs?: number;\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n /** The page's window (tests); default globalThis.window. */\n window?: PageWindow;\n /** Use this launch instead of waiting for the parent (tests, pages opened outside Land). */\n launch?: Omit<Launch, \"type\">;\n}\n\n/** The part of Window the client uses. */\nexport interface PageWindow {\n parent: { postMessage(message: unknown, targetOrigin: string): void } | null;\n addEventListener(type: \"message\", fn: (e: { source: unknown; data: unknown }) => void): void;\n removeEventListener(type: \"message\", fn: (e: { source: unknown; data: unknown }) => void): void;\n}\n\nexport type PageEvent = \"launch\" | \"refresh\" | \"error\" | \"session.updated\" | \"install.updated\";\n\nexport interface PageClient {\n /** Resolves with the context once the launch arrived. */\n ready(): Promise<PageContext>;\n /** The context, or null before the launch. */\n readonly context: PageContext | null;\n /** The current launch, or null. */\n readonly launch: Launch | null;\n /**\n * launch: the first launch; refresh: every later one (a new token);\n * error: a failed refresh; session.updated / install.updated: this\n * frame's session or install changed (PageChange) — read it again.\n */\n on(event: PageEvent, fn: (data: any) => void): () => void;\n /**\n * Call one of the app's tools as the viewer. The idempotency key (given,\n * or a new one) goes in the Idempotency-Key header and stays the same\n * when a network failure is retried, so the tool runs once.\n */\n callTool<R = Json>(tool: string, args?: Record<string, unknown>, opts?: { idempotencyKey?: string; sessionId?: Id; installId?: Id }): Promise<Call & { result: R }>;\n sessions: {\n get(sessionId: Id): Promise<Session>;\n join(sessionId: Id, opts?: { observe?: boolean; invite_token?: string }): Promise<AddParticipantResponse>;\n leave(sessionId: Id): Promise<Participant>;\n /** Accept or decline an invite. */\n respond(sessionId: Id, accept: boolean): Promise<Participant>;\n };\n boards: {\n get(ref: string, query?: GetBoardQuery): Promise<Board>;\n list(query?: ListBoardsQuery): Promise<Board[]>;\n };\n residents: {\n /**\n * Names and avatars (avatar_url: a signed URL that expires; show it,\n * don't keep it) of the launch room's members and the session's\n * participants; others are left out. At most 100 ids per request\n * (batched). The same name as the service client's.\n */\n get(ids: Id[]): Promise<Resident[]>;\n };\n /** Ask the parent for a fresh token now. */\n refresh(): Promise<Launch>;\n request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;\n /** Stop listening and cancel the refresh timer. */\n destroy(): void;\n}\n\n/** createPageClient starts listening for the launch and announces the page (karpo:ready). */\n// Single-object answers are unwrapped ({session} → the session), as in the service client.\nconst one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown> | null)?.[key] as T;\n\nexport function createPageClient(opts: PageClientOptions = {}): PageClient {\n const win = opts.window ?? ((globalThis as { window?: PageWindow }).window as PageWindow | undefined);\n const before = opts.refreshBeforeMs ?? 30_000;\n let launch: Launch | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const listeners: Record<PageEvent, Set<(d: any) => void>> = { launch: new Set(), refresh: new Set(), error: new Set(), \"session.updated\": new Set(), \"install.updated\": new Set() };\n const emit = (ev: PageEvent, d: unknown) => listeners[ev].forEach((fn) => fn(d));\n let readyWaiters: ((l: Launch) => void)[] = [];\n let refreshWaiters: { resolve: (l: Launch) => void; reject: (e: unknown) => void }[] = [];\n\n const post = (type: string) => win?.parent?.postMessage({ type }, \"*\");\n\n const schedule = () => {\n if (timer) clearTimeout(timer);\n if (!launch) return;\n const ms = new Date(launch.expires_at).getTime() - Date.now() - before;\n timer = setTimeout(() => void client.refresh().catch((e) => emit(\"error\", e)), Math.max(1000, ms));\n (timer as { unref?: () => void }).unref?.();\n };\n\n const accept = (l: Launch) => {\n const first = !launch;\n launch = l;\n schedule();\n emit(first ? \"launch\" : \"refresh\", l);\n readyWaiters.forEach((r) => r(l));\n readyWaiters = [];\n refreshWaiters.forEach((w) => w.resolve(l));\n refreshWaiters = [];\n };\n\n const onMessage = (e: { source: unknown; data: unknown }) => {\n if (!win || e.source !== win.parent) return;\n const ev = e.data as { type?: string; event?: string; session_id?: Id; install_id?: Id } | null;\n if (ev?.type === \"karpo:event\" && (ev.event === \"session.updated\" || ev.event === \"install.updated\")) {\n emit(ev.event, { event: ev.event, ...(ev.session_id ? { session_id: String(ev.session_id) } : {}), ...(ev.install_id ? { install_id: String(ev.install_id) } : {}) } satisfies PageChange);\n return;\n }\n const d = e.data as Partial<Launch> | null;\n if (!d || d.type !== \"karpo:launch\" || typeof d.token !== \"string\") return;\n accept({ type: \"karpo:launch\", token: d.token, expires_at: String(d.expires_at ?? \"\"), context: (d.context ?? {}) as PageContext, api: String(d.api ?? \"\") });\n };\n\n const waitLaunch = (): Promise<Launch> =>\n launch\n ? Promise.resolve(launch)\n : new Promise((resolve, reject) => {\n const t = setTimeout(() => reject(new Error(\"karpoland: no karpo:launch from the parent frame; is the page opened inside Karpo Land?\")), opts.launchTimeoutMs ?? 15_000);\n readyWaiters.push((l) => (clearTimeout(t), resolve(l)));\n });\n\n const request = async <T>(method: string, path: string, body?: unknown, query?: Record<string, unknown>, extra: { headers?: Record<string, string>; idempotent?: boolean } = {}): Promise<T> => {\n const l = await waitLaunch();\n // The API base comes with the launch.\n const t = createTransport({\n base: l.api,\n fetch: opts.fetch,\n retry: opts.retry,\n headers: () => ({ Authorization: `Bearer ${launch?.token ?? l.token}` }),\n onUnauthorized: async () => {\n try {\n await client.refresh();\n return true;\n } catch {\n return false;\n }\n },\n });\n return t.request<T>(method, path, { body, query, ...extra });\n };\n\n const client: PageClient = {\n ready: async () => (await waitLaunch()).context,\n get context() {\n return launch?.context ?? null;\n },\n get launch() {\n return launch;\n },\n on(ev, fn) {\n listeners[ev].add(fn);\n return () => listeners[ev].delete(fn);\n },\n async callTool<R>(tool: string, args: Record<string, unknown> = {}, o: { idempotencyKey?: string; sessionId?: Id; installId?: Id } = {}) {\n const key = o.idempotencyKey ?? randomKey(\"page-\");\n const r = await request<{ call: Call }>(\"POST\", `/tools/${enc(tool)}`, { args, session_id: o.sessionId, install_id: o.installId }, undefined, { headers: { \"Idempotency-Key\": key }, idempotent: true });\n return r.call as Call & { result: R };\n },\n sessions: {\n get: (id) => one<Session>(\"session\", request(\"GET\", `/sessions/${enc(id)}`)),\n join: (id, o = {}) => request(\"POST\", `/sessions/${enc(id)}/join`, o),\n leave: (id) => one<Participant>(\"participant\", request(\"POST\", `/sessions/${enc(id)}/leave`, {})),\n respond: (id, accept) => one<Participant>(\"participant\", request(\"POST\", `/sessions/${enc(id)}/respond`, { accept })),\n },\n boards: {\n get: (ref, query = {}) => one<Board>(\"board\", request(\"GET\", \"/boards\", undefined, { ref, ...query })),\n list: async (query = {}) => (await one<Board[] | undefined>(\"boards\", request(\"GET\", \"/boards\", undefined, query as Record<string, unknown>))) ?? [],\n },\n residents: {\n async get(ids) {\n const want = [...new Set(ids.filter(Boolean).map(String))];\n const out: Resident[] = [];\n for (let i = 0; i < want.length; i += 100) {\n const r = await request<{ residents?: Resident[] }>(\"GET\", \"/residents\", undefined, { ids: want.slice(i, i + 100).join(\",\") });\n out.push(...(r.residents ?? []));\n }\n return out;\n },\n },\n refresh() {\n if (!win?.parent) return Promise.reject(new PlatformError(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: \"no parent frame to refresh the launch token\" }));\n return new Promise<Launch>((resolve, reject) => {\n const waiter = { resolve: (l: Launch) => (clearTimeout(t), resolve(l)), reject };\n const t = setTimeout(() => {\n refreshWaiters = refreshWaiters.filter((w) => w !== waiter);\n reject(new Error(\"karpoland: the parent frame did not send a fresh launch\"));\n }, opts.launchTimeoutMs ?? 15_000);\n refreshWaiters.push(waiter);\n post(\"karpo:refresh\");\n });\n },\n request: (method, path, body, query) => request(method, path, body, query),\n destroy() {\n if (timer) clearTimeout(timer);\n win?.removeEventListener(\"message\", onMessage);\n },\n };\n\n win?.addEventListener(\"message\", onMessage);\n if (opts.launch) accept({ type: \"karpo:launch\", ...opts.launch });\n else post(\"karpo:ready\");\n return client;\n}\n"],"mappings":";;;;;;;;AA8HA,IAAM,MAAM,OAAU,KAAa,OAAsC,MAAM,KAAwC,GAAG;AAEnH,SAAS,iBAAiB,OAA0B,CAAC,GAAe;AACzE,QAAM,MAAM,KAAK,UAAY,WAAuC;AACpE,QAAM,SAAS,KAAK,mBAAmB;AACvC,MAAI,SAAwB;AAC5B,MAAI;AACJ,QAAM,YAAsD,EAAE,QAAQ,oBAAI,IAAI,GAAG,SAAS,oBAAI,IAAI,GAAG,OAAO,oBAAI,IAAI,GAAG,mBAAmB,oBAAI,IAAI,GAAG,mBAAmB,oBAAI,IAAI,EAAE;AAClL,QA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+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/testing.ts
31
+ var testing_exports = {};
32
+ __export(testing_exports, {
33
+ mockPlatform: () => mockPlatform,
34
+ simulate: () => simulate
35
+ });
36
+ module.exports = __toCommonJS(testing_exports);
37
+
38
+ // src/signing.ts
39
+ var SIGNATURE_HEADER = "MP-Karpo-Signature-V1";
40
+ var TIMESTAMP_HEADER = "MP-Karpo-Timestamp";
41
+ var te = new TextEncoder();
42
+ var subtlePromise;
43
+ async function subtle() {
44
+ const c = globalThis.crypto;
45
+ if (c?.subtle) return c.subtle;
46
+ subtlePromise ??= import("crypto").then((m) => m.webcrypto.subtle);
47
+ return subtlePromise;
48
+ }
49
+ var keys = /* @__PURE__ */ new Map();
50
+ function hmacKey(secret) {
51
+ let k = keys.get(secret);
52
+ if (!k) {
53
+ k = subtle().then((s) => s.importKey("raw", te.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]));
54
+ if (keys.size > 32) keys.clear();
55
+ keys.set(secret, k);
56
+ }
57
+ return k;
58
+ }
59
+ function toBytes(body) {
60
+ if (typeof body === "string") return te.encode(body);
61
+ return body instanceof Uint8Array ? body : new Uint8Array(body);
62
+ }
63
+ function hex(buf) {
64
+ let s = "";
65
+ for (const b of new Uint8Array(buf)) s += b.toString(16).padStart(2, "0");
66
+ return s;
67
+ }
68
+ async function hmacHex(secret, parts) {
69
+ const n = parts.reduce((a, p) => a + p.length, 0);
70
+ const msg = new Uint8Array(n);
71
+ let o = 0;
72
+ for (const p of parts) {
73
+ msg.set(p, o);
74
+ o += p.length;
75
+ }
76
+ return hex(await (await subtle()).sign("HMAC", await hmacKey(secret), msg));
77
+ }
78
+ async function sign(secret, ts, req, body) {
79
+ const head = te.encode(`v1
80
+ ${(req.method ?? "POST").toUpperCase()}
81
+ ${req.path}
82
+ ${ts}
83
+ ${req.id ?? ""}
84
+ `);
85
+ return "v1=" + await hmacHex(secret, [head, toBytes(body)]);
86
+ }
87
+ async function signedHeaders(secret, body, extra) {
88
+ const ts = extra.ts ?? Math.floor(Date.now() / 1e3);
89
+ const h = {
90
+ "Content-Type": "application/json",
91
+ [TIMESTAMP_HEADER]: String(ts),
92
+ [SIGNATURE_HEADER]: await sign(secret, ts, { method: extra.method, path: extra.path, id: extra.callId ?? extra.deliveryId ?? "" }, body)
93
+ };
94
+ if (extra.event) h["MP-Karpo-Event"] = extra.event;
95
+ if (extra.app) h["MP-Karpo-App"] = extra.app;
96
+ if (extra.callId) h["MP-Karpo-Call"] = extra.callId;
97
+ if (extra.deliveryId) h["MP-Karpo-Delivery"] = extra.deliveryId;
98
+ return h;
99
+ }
100
+
101
+ // src/testing.ts
102
+ var DEFAULT_INSTALL = { id: "500", room_id: "900", version: "1.0.0" };
103
+ var DEFAULT_CALLER = { id: "1001", name: "Tester", kind: "person" };
104
+ function simulate(app, opts) {
105
+ if (!opts?.signingSecret) throw new TypeError("simulate: signingSecret is required");
106
+ const slug = opts.app ?? "test-app";
107
+ const base = (opts.basePath ?? "").replace(/\/+$/, "");
108
+ const install = (o) => o.install !== void 0 ? o.install : opts.install !== void 0 ? opts.install : DEFAULT_INSTALL;
109
+ let seq = 0;
110
+ const nextId = () => String(2e6 + ++seq);
111
+ const pending = [];
112
+ async function deliver(path, msg, ids) {
113
+ const body = new TextEncoder().encode(JSON.stringify(msg));
114
+ const full = base + path;
115
+ const ts = opts.now ? opts.now() : Math.floor(Date.now() / 1e3);
116
+ const headers = new Headers(await signedHeaders(opts.signingSecret, body, { path: full, ts, ...ids }));
117
+ const out = await app.handle({ method: "POST", path: full, headers, body }, (p) => void pending.push(p));
118
+ return { status: out.status, body: out.body ? JSON.parse(out.body) : null };
119
+ }
120
+ const strip = (o) => {
121
+ for (const k of Object.keys(o)) if (o[k] === void 0) delete o[k];
122
+ return o;
123
+ };
124
+ return {
125
+ call(tool, args = {}, caller, o = {}) {
126
+ const id = o.id ?? nextId();
127
+ const call = strip({ id, tool, args, idempotency_key: o.idempotencyKey, first_seen: o.firstSeen });
128
+ const msg = strip({
129
+ type: "karpo.call",
130
+ app: slug,
131
+ call,
132
+ caller: caller === void 0 ? opts.caller ?? DEFAULT_CALLER : caller,
133
+ install: install(o) ?? void 0,
134
+ session: o.session ?? void 0,
135
+ event: o.event,
136
+ command_message_id: o.commandMessageId
137
+ });
138
+ return deliver(`/tools/${encodeURIComponent(tool)}`, msg, { callId: id });
139
+ },
140
+ event(name, data, o = {}) {
141
+ const id = o.id ?? nextId();
142
+ const msg = strip({
143
+ type: "karpo.event",
144
+ event: name,
145
+ delivery_id: id,
146
+ app: slug,
147
+ attempt: o.attempt ?? 1,
148
+ data,
149
+ install: install(o) ?? void 0,
150
+ session_id: o.sessionId,
151
+ resident_id: o.residentId
152
+ });
153
+ return deliver(`/hooks/${encodeURIComponent(name)}`, msg, { deliveryId: id });
154
+ },
155
+ gate(input) {
156
+ const id = input.id ?? nextId();
157
+ const inst = install(input);
158
+ const data = {
159
+ join_request_id: input.join_request_id ?? nextId(),
160
+ room_id: input.room_id ?? inst?.room_id ?? "",
161
+ applicant: input.applicant,
162
+ note: input.note ?? ""
163
+ };
164
+ const msg = strip({
165
+ type: "karpo.event",
166
+ event: "member.join",
167
+ delivery_id: id,
168
+ app: slug,
169
+ attempt: 1,
170
+ data,
171
+ install: inst ?? void 0,
172
+ resident_id: input.applicant.id,
173
+ gate: true
174
+ });
175
+ return deliver("/hooks/member.join", msg, { deliveryId: id });
176
+ },
177
+ handshake(input = {}) {
178
+ const msg = strip({
179
+ type: "karpo.handshake",
180
+ app: slug,
181
+ version: input.version ?? "1.0.0",
182
+ challenge: input.challenge ?? `ch-${nextId()}`,
183
+ tools: input.tools,
184
+ hooks: input.hooks
185
+ });
186
+ return deliver("/.karpo/handshake", msg, {});
187
+ },
188
+ async idle() {
189
+ while (pending.length) await Promise.allSettled(pending.splice(0));
190
+ }
191
+ };
192
+ }
193
+ var APP_SERVICE = "/v1/app-service";
194
+ function mockPlatform() {
195
+ const url = "https://platform.test";
196
+ const requests = [];
197
+ let rules = [];
198
+ const pattern = (p) => new RegExp("^" + p.split("/").map((seg) => seg === "*" ? "[^/]+" : seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/") + "$");
199
+ const mock = {
200
+ url,
201
+ requests: () => [...requests],
202
+ async fetch(input, init = {}) {
203
+ const u = new URL(String(input));
204
+ const headers = {};
205
+ new Headers(init.headers).forEach((v, k) => headers[k] = v);
206
+ let body = void 0;
207
+ if (init.body !== void 0 && init.body !== null) {
208
+ const raw = typeof init.body === "string" ? init.body : new Uint8Array(await new Response(init.body).arrayBuffer());
209
+ if (typeof raw === "string" && (headers["content-type"] ?? "").includes("json")) body = JSON.parse(raw);
210
+ else body = typeof raw === "string" ? new TextEncoder().encode(raw) : raw;
211
+ }
212
+ const rec = { method: (init.method ?? "GET").toUpperCase(), path: u.pathname, query: Object.fromEntries(u.searchParams), headers, body };
213
+ requests.push(rec);
214
+ const short = rec.path.startsWith(APP_SERVICE + "/") ? rec.path.slice(APP_SERVICE.length) : null;
215
+ let out;
216
+ for (let i = rules.length - 1; i >= 0 && !out; i--) {
217
+ const r = rules[i];
218
+ if (r.method !== "*" && r.method !== rec.method) continue;
219
+ if (!r.re.test(rec.path) && !(short !== null && r.re.test(short))) continue;
220
+ out = typeof r.answer === "function" ? r.answer(rec) : r.answer;
221
+ }
222
+ const status = out?.status ?? 200;
223
+ const text = out?.body === void 0 ? "{}" : JSON.stringify(out.body);
224
+ return new Response(status === 204 ? null : text, { status, headers: { "Content-Type": "application/json", ...out?.headers } });
225
+ },
226
+ respond(method, path, answer) {
227
+ rules.push({ method: method.toUpperCase(), re: pattern(path), answer });
228
+ return mock;
229
+ },
230
+ last: () => requests[requests.length - 1],
231
+ reset() {
232
+ requests.length = 0;
233
+ rules = [];
234
+ }
235
+ };
236
+ return mock;
237
+ }
238
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing.ts","../src/signing.ts"],"sourcesContent":["// @karpoland/sdk/testing: test an app's service without the platform.\n//\n// import { createApp } from \"@karpoland/sdk\";\n// import { mockPlatform, simulate } from \"@karpoland/sdk/testing\";\n//\n// const platform = mockPlatform();\n// // what GET /v1/app-service/signing answers the app's key with\n// platform.respond(\"GET\", \"/signing\", { body: { signing_secret: \"s\", domain_token: \"t\" } });\n// const app = createApp({ appKey: \"kap_test\", platform: platform.url, fetch: platform.fetch });\n// app.tool(\"roll\", (ctx) => ({ result: { n: 4 }, text: `${ctx.caller?.name} 掷出了 4` }));\n// const sim = simulate(app, { signingSecret: \"s\" });\n// await sim.call(\"roll\", { sides: 6 }); // {status: 200, body: {result: {n: 4}, text: \"…\"}}\n// platform.requests; // what the app sent the platform\n//\n// simulate builds deliveries the way the platform does (body, ids,\n// MP-Karpo-Timestamp and MP-Karpo-Signature-V1) and runs them through\n// app.handle; mockPlatform is a fetch that records the app's requests and\n// answers them as the test scripts. Browser safe.\n\nimport type { App } from \"./app.js\";\nimport type { FetchLike } from \"./http.js\";\nimport { signedHeaders } from \"./signing.js\";\nimport type { HookEvents, Id, InstallRef, Json, Resident, SessionRef } from \"./types.js\";\n\n// ----------------------------------------------------------------- simulate\n\nexport interface SimulateOptions {\n /** The app's signing secret: deliveries are signed with it. */\n signingSecret: string;\n /** The app's slug in deliveries; default \"test-app\". */\n app?: string;\n /** The service's basePath (AppOptions.basePath): deliveries are posted under it. */\n basePath?: string;\n /** The install deliveries carry unless an option says otherwise; null for none. Default {id: \"500\", room_id: \"900\", version: \"1.0.0\"}. */\n install?: InstallRef | null;\n /** The caller of call() when none is given. Default {id: \"1001\", name: \"Tester\", kind: \"person\"}. */\n caller?: Resident;\n /** The MP-Karpo-Timestamp clock in Unix seconds; default now. */\n now?: () => number;\n}\n\n/** The service's answer to a delivery: the HTTP status and the JSON body (null when empty). */\nexport interface Answer<B = any> {\n status: number;\n body: B;\n}\n\nexport interface CallOptions {\n /** The call id; default a new one. Reuse one to replay a call. */\n id?: Id;\n install?: InstallRef | null;\n session?: SessionRef | null;\n idempotencyKey?: string;\n /** The caller's first call to the app. */\n firstSeen?: boolean;\n /** Set when a declarative hook (call) runs the tool: its event. */\n event?: string;\n commandMessageId?: Id;\n}\n\nexport interface EventOptions {\n /** The delivery id; default a new one. Reuse one to redeliver. */\n id?: Id;\n install?: InstallRef | null;\n sessionId?: Id;\n /** The resident the hook may act for. */\n residentId?: Id;\n /** Default 1. */\n attempt?: number;\n}\n\n/** A join request gate delivery: the join request. */\nexport interface GateInput {\n applicant: Resident;\n /** Default the install's room. */\n room_id?: Id;\n /** Default a new id. */\n join_request_id?: Id;\n note?: string;\n /** The delivery id; default a new one. */\n id?: Id;\n install?: InstallRef | null;\n}\n\n/** A publish handshake. */\nexport interface HandshakeInput {\n /** Default \"1.0.0\". */\n version?: string;\n /** Default a new one. */\n challenge?: string;\n tools?: string[];\n hooks?: string[];\n}\n\nexport interface Simulator {\n /** Call a tool as caller (default the simulator's caller; null: a declarative hook's call in the app's own context). */\n call<B = any>(tool: string, args?: Record<string, Json | undefined>, caller?: Resident | null, opts?: CallOptions): Promise<Answer<B>>;\n /** Deliver a hook event. */\n event<B = any>(name: string, data: Record<string, unknown>, opts?: EventOptions): Promise<Answer<B>>;\n /** Ask the join request gate: 200 {decision, reason?}, or 204 without a decision. */\n gate<B = any>(input: GateInput): Promise<Answer<B>>;\n /**\n * The publish handshake: 200 {challenge}; with tools and hooks (the\n * manifest's, as the platform sends them) 422 app.HANDSHAKE_FAILED when a\n * handler is missing.\n */\n handshake<B = any>(input?: HandshakeInput): Promise<Answer<B>>;\n /** Wait for work the handlers left running (ctx.defer, ctx.waitUntil). */\n idle(): Promise<void>;\n}\n\nconst DEFAULT_INSTALL: InstallRef = { id: \"500\", room_id: \"900\", version: \"1.0.0\" };\nconst DEFAULT_CALLER: Resident = { id: \"1001\", name: \"Tester\", kind: \"person\" };\n\n/** simulate drives app with signed deliveries, as the platform sends them. */\nexport function simulate(app: App, opts: SimulateOptions): Simulator {\n if (!opts?.signingSecret) throw new TypeError(\"simulate: signingSecret is required\");\n const slug = opts.app ?? \"test-app\";\n const base = (opts.basePath ?? \"\").replace(/\\/+$/, \"\");\n const install = (o: { install?: InstallRef | null }) => (o.install !== undefined ? o.install : opts.install !== undefined ? opts.install : DEFAULT_INSTALL);\n let seq = 0;\n const nextId = () => String(2_000_000 + ++seq);\n const pending: Promise<unknown>[] = [];\n\n async function deliver(path: string, msg: Record<string, unknown>, ids: { callId?: string; deliveryId?: string }): Promise<Answer> {\n const body = new TextEncoder().encode(JSON.stringify(msg));\n const full = base + path;\n const ts = opts.now ? opts.now() : Math.floor(Date.now() / 1000);\n const headers = new Headers(await signedHeaders(opts.signingSecret, body, { path: full, ts, ...ids }));\n const out = await app.handle({ method: \"POST\", path: full, headers, body }, (p) => void pending.push(p));\n return { status: out.status, body: out.body ? JSON.parse(out.body) : null };\n }\n\n const strip = (o: Record<string, unknown>) => {\n for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k];\n return o;\n };\n\n return {\n call(tool, args = {}, caller, o = {}) {\n const id = o.id ?? nextId();\n const call = strip({ id, tool, args, idempotency_key: o.idempotencyKey, first_seen: o.firstSeen });\n const msg = strip({\n type: \"karpo.call\",\n app: slug,\n call,\n caller: caller === undefined ? (opts.caller ?? DEFAULT_CALLER) : caller,\n install: install(o) ?? undefined,\n session: o.session ?? undefined,\n event: o.event,\n command_message_id: o.commandMessageId,\n });\n return deliver(`/tools/${encodeURIComponent(tool)}`, msg, { callId: id });\n },\n event(name, data, o = {}) {\n const id = o.id ?? nextId();\n const msg = strip({\n type: \"karpo.event\",\n event: name,\n delivery_id: id,\n app: slug,\n attempt: o.attempt ?? 1,\n data,\n install: install(o) ?? undefined,\n session_id: o.sessionId,\n resident_id: o.residentId,\n });\n return deliver(`/hooks/${encodeURIComponent(name)}`, msg, { deliveryId: id });\n },\n gate(input) {\n const id = input.id ?? nextId();\n const inst = install(input);\n const data: HookEvents[\"member.join\"] = {\n join_request_id: input.join_request_id ?? nextId(),\n room_id: input.room_id ?? inst?.room_id ?? \"\",\n applicant: input.applicant,\n note: input.note ?? \"\",\n };\n const msg = strip({\n type: \"karpo.event\",\n event: \"member.join\",\n delivery_id: id,\n app: slug,\n attempt: 1,\n data,\n install: inst ?? undefined,\n resident_id: input.applicant.id,\n gate: true,\n });\n return deliver(\"/hooks/member.join\", msg, { deliveryId: id });\n },\n handshake(input = {}) {\n const msg = strip({\n type: \"karpo.handshake\",\n app: slug,\n version: input.version ?? \"1.0.0\",\n challenge: input.challenge ?? `ch-${nextId()}`,\n tools: input.tools,\n hooks: input.hooks,\n });\n return deliver(\"/.karpo/handshake\", msg, {});\n },\n async idle() {\n while (pending.length) await Promise.allSettled(pending.splice(0));\n },\n };\n}\n\n// ------------------------------------------------------------- mockPlatform\n\n/** A request the app sent the platform. */\nexport interface RecordedRequest {\n method: string;\n /** The URL path, e.g. /v1/app-service/sessions. */\n path: string;\n query: Record<string, string>;\n /** Lower-case names. */\n headers: Record<string, string>;\n /** The JSON body, the raw bytes of another body, or undefined. */\n body: any;\n}\n\n/** A scripted answer; default status 200 and body {}. */\nexport interface MockAnswer {\n status?: number;\n body?: unknown;\n headers?: Record<string, string>;\n}\n\nexport interface PlatformMock {\n /** The platform origin to give createApp / createClient (platform). */\n readonly url: string;\n /** The fetch to give createApp / createClient (fetch): every request lands here. */\n fetch: FetchLike;\n /** Every request so far, oldest first (a copy). */\n requests(): RecordedRequest[];\n /**\n * Answer method (or \"*\") on path with answer from now on; the latest\n * matching rule wins. path is the full path (/v1/apps/dice) or an\n * app-service route (/sessions/*), \"*\" matching one segment.\n */\n respond(method: string, path: string, answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined)): PlatformMock;\n /** The latest request. */\n last(): RecordedRequest | undefined;\n /** Forget the requests and the scripted answers. */\n reset(): void;\n}\n\nconst APP_SERVICE = \"/v1/app-service\";\n\n/** mockPlatform stands in for the platform API: it records requests and answers as scripted. */\nexport function mockPlatform(): PlatformMock {\n const url = \"https://platform.test\";\n const requests: RecordedRequest[] = [];\n let rules: { method: string; re: RegExp; answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined) }[] = [];\n const pattern = (p: string) => new RegExp(\"^\" + p.split(\"/\").map((seg) => (seg === \"*\" ? \"[^/]+\" : seg.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))).join(\"/\") + \"$\");\n\n const mock: PlatformMock = {\n url,\n requests: () => [...requests],\n async fetch(input, init = {}) {\n const u = new URL(String(input));\n const headers: Record<string, string> = {};\n new Headers(init.headers as HeadersInit | undefined).forEach((v, k) => (headers[k] = v));\n let body: unknown = undefined;\n if (init.body !== undefined && init.body !== null) {\n const raw = typeof init.body === \"string\" ? init.body : new Uint8Array(await new Response(init.body as BodyInit).arrayBuffer());\n if (typeof raw === \"string\" && (headers[\"content-type\"] ?? \"\").includes(\"json\")) body = JSON.parse(raw);\n else body = typeof raw === \"string\" ? new TextEncoder().encode(raw) : raw;\n }\n const rec: RecordedRequest = { method: (init.method ?? \"GET\").toUpperCase(), path: u.pathname, query: Object.fromEntries(u.searchParams), headers, body };\n requests.push(rec);\n const short = rec.path.startsWith(APP_SERVICE + \"/\") ? rec.path.slice(APP_SERVICE.length) : null;\n let out: MockAnswer | undefined;\n for (let i = rules.length - 1; i >= 0 && !out; i--) {\n const r = rules[i]!;\n if (r.method !== \"*\" && r.method !== rec.method) continue;\n if (!r.re.test(rec.path) && !(short !== null && r.re.test(short))) continue;\n out = typeof r.answer === \"function\" ? r.answer(rec) : r.answer;\n }\n const status = out?.status ?? 200;\n const text = out?.body === undefined ? \"{}\" : JSON.stringify(out.body);\n return new Response(status === 204 ? null : text, { status, headers: { \"Content-Type\": \"application/json\", ...out?.headers } });\n },\n respond(method, path, answer) {\n rules.push({ method: method.toUpperCase(), re: pattern(path), answer });\n return mock;\n },\n last: () => requests[requests.length - 1],\n reset() {\n requests.length = 0;\n rules = [];\n },\n };\n return mock;\n}\n","// Delivery signatures. The platform sends two headers with every delivery:\n// MP-Karpo-Timestamp (Unix seconds) and MP-Karpo-Signature-V1 = \"v1=\" + hex\n// HMAC-SHA256(secret, \"v1\\n\" + method + \"\\n\" + path + \"\\n\" + timestamp +\n// \"\\n\" + id + \"\\n\" + body). It covers the method, the path the platform\n// posted to, the call or delivery id and the body. id is the MP-Karpo-Call\n// or MP-Karpo-Delivery value, \"\" for the handshake. There is no other\n// signature.\n//\n// Uses Web Crypto, so it runs on Node ≥ 18, Deno, Bun and edge runtimes.\n\n/** The signature header. */\nexport const SIGNATURE_HEADER = \"MP-Karpo-Signature-V1\";\n/** The timestamp header (Unix seconds). */\nexport const TIMESTAMP_HEADER = \"MP-Karpo-Timestamp\";\n/** Largest accepted clock difference by default, in seconds. */\nexport const MAX_SKEW_SECONDS = 300;\n\nconst te = new TextEncoder();\n\nlet subtlePromise: Promise<SubtleCrypto> | undefined;\nasync function subtle(): Promise<SubtleCrypto> {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.subtle) return c.subtle;\n // Node 18 has Web Crypto only on node:crypto.\n subtlePromise ??= import(\"node:crypto\").then((m) => (m.webcrypto as unknown as Crypto).subtle);\n return subtlePromise;\n}\n\nconst keys = new Map<string, Promise<CryptoKey>>();\nfunction hmacKey(secret: string): Promise<CryptoKey> {\n let k = keys.get(secret);\n if (!k) {\n k = subtle().then((s) => s.importKey(\"raw\", te.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]));\n if (keys.size > 32) keys.clear();\n keys.set(secret, k);\n }\n return k;\n}\n\nfunction toBytes(body: string | Uint8Array | ArrayBuffer): Uint8Array {\n if (typeof body === \"string\") return te.encode(body);\n return body instanceof Uint8Array ? body : new Uint8Array(body);\n}\n\nfunction hex(buf: ArrayBuffer): string {\n let s = \"\";\n for (const b of new Uint8Array(buf)) s += b.toString(16).padStart(2, \"0\");\n return s;\n}\n\nasync function hmacHex(secret: string, parts: Uint8Array[]): Promise<string> {\n const n = parts.reduce((a, p) => a + p.length, 0);\n const msg = new Uint8Array(n);\n let o = 0;\n for (const p of parts) {\n msg.set(p, o);\n o += p.length;\n }\n return hex(await (await subtle()).sign(\"HMAC\", await hmacKey(secret), msg));\n}\n\n/** What signedHeaders signs and sends besides the body. */\nexport interface SignedHeadersOptions {\n /** The path the delivery is posted to. */\n path: string;\n /** Default \"POST\". */\n method?: string;\n callId?: string;\n deliveryId?: string;\n /** Unix seconds; default now. */\n ts?: number;\n event?: string;\n app?: string;\n}\n\n/** The parts a signature covers besides the timestamp and the body. */\nexport interface SignedRequest {\n /** Default \"POST\". */\n method?: string;\n /** The path the platform posted to, percent-encoded, without query, e.g. /karpo/tools/roll. */\n path: string;\n /** The MP-Karpo-Call or MP-Karpo-Delivery value; \"\" for the handshake. */\n id?: string;\n}\n\n/** sign computes the MP-Karpo-Signature-V1 value (\"v1=\" + hex) for a body sent at ts (Unix seconds). */\nexport async function sign(secret: string, ts: number | string, req: SignedRequest, body: string | Uint8Array | ArrayBuffer): Promise<string> {\n const head = te.encode(`v1\\n${(req.method ?? \"POST\").toUpperCase()}\\n${req.path}\\n${ts}\\n${req.id ?? \"\"}\\n`);\n return \"v1=\" + (await hmacHex(secret, [head, toBytes(body)]));\n}\n\n/** Constant-time string comparison. */\nexport function safeEqual(a: string, b: string): boolean {\n let diff = a.length ^ b.length;\n const n = Math.max(a.length, b.length);\n for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n return diff === 0;\n}\n\nexport type VerifyFailure = \"missing\" | \"skew\" | \"mismatch\";\n\nexport interface VerifyOptions {\n /** Largest accepted clock difference; default 300 seconds (MAX_SKEW_SECONDS). */\n maxSkewSeconds?: number;\n /** Current time in ms (tests). */\n now?: number;\n}\n\n/**\n * verifySignature checks a delivery's MP-Karpo-Signature-V1 and\n * MP-Karpo-Timestamp: null when valid, else why not. \"missing\": no secret,\n * timestamp or signature; \"skew\": the timestamp is not whole Unix seconds or\n * is more than maxSkewSeconds away from now; \"mismatch\": the signature does\n * not cover this method, path, id and body with this secret.\n */\nexport async function verifySignature(\n secret: string,\n timestamp: string | null | undefined,\n req: SignedRequest,\n body: string | Uint8Array | ArrayBuffer,\n signature: string | null | undefined,\n opts: VerifyOptions = {},\n): Promise<VerifyFailure | null> {\n if (!secret || !timestamp || !signature) return \"missing\";\n const ts = Number(timestamp);\n const now = (opts.now ?? Date.now()) / 1000;\n if (!/^\\d+$/.test(timestamp) || !Number.isFinite(ts) || Math.abs(now - ts) > (opts.maxSkewSeconds ?? MAX_SKEW_SECONDS)) return \"skew\";\n const want = await sign(secret, timestamp, req, body);\n return safeEqual(want, signature.trim()) ? null : \"mismatch\";\n}\n\n/**\n * signedHeaders builds the headers the platform sends with a delivery to\n * path (as the platform posted it, base path included); for testing an\n * app's service locally. The test kit (@karpoland/sdk/testing) uses it.\n */\nexport async function signedHeaders(\n secret: string,\n body: string | Uint8Array,\n extra: SignedHeadersOptions,\n): Promise<Record<string, string>> {\n const ts = extra.ts ?? Math.floor(Date.now() / 1000);\n const h: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n [TIMESTAMP_HEADER]: String(ts),\n [SIGNATURE_HEADER]: await sign(secret, ts, { method: extra.method, path: extra.path, id: extra.callId ?? extra.deliveryId ?? \"\" }, body),\n };\n if (extra.event) h[\"MP-Karpo-Event\"] = extra.event;\n if (extra.app) h[\"MP-Karpo-App\"] = extra.app;\n if (extra.callId) h[\"MP-Karpo-Call\"] = extra.callId;\n if (extra.deliveryId) h[\"MP-Karpo-Delivery\"] = extra.deliveryId;\n return h;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,mBAAmB;AAEzB,IAAM,mBAAmB;AAIhC,IAAM,KAAK,IAAI,YAAY;AAE3B,IAAI;AACJ,eAAe,SAAgC;AAC7C,QAAM,IAAK,WAAmC;AAC9C,MAAI,GAAG,OAAQ,QAAO,EAAE;AAExB,oBAAkB,OAAO,QAAa,EAAE,KAAK,CAAC,MAAO,EAAE,UAAgC,MAAM;AAC7F,SAAO;AACT;AAEA,IAAM,OAAO,oBAAI,IAAgC;AACjD,SAAS,QAAQ,QAAoC;AACnD,MAAI,IAAI,KAAK,IAAI,MAAM;AACvB,MAAI,CAAC,GAAG;AACN,QAAI,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,UAAU,OAAO,GAAG,OAAO,MAAM,GAAG,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAClH,QAAI,KAAK,OAAO,GAAI,MAAK,MAAM;AAC/B,SAAK,IAAI,QAAQ,CAAC;AAAA,EACpB;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,MAAqD;AACpE,MAAI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O,KAAK,SAAS,SAAY,OAAO,KAAK,UAAU,IAAI,IAAI;AACrE,aAAO,IAAI,SAAS,WAAW,MAAM,OAAO,MAAM,EAAE,QAAQ,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,KAAK,QAAQ,EAAE,CAAC;AAAA,IAChI;AAAA,IACA,QAAQ,QAAQ,MAAM,QAAQ;AAC5B,YAAM,KAAK,EAAE,QAAQ,OAAO,YAAY,GAAG,IAAI,QAAQ,IAAI,GAAG,OAAO,CAAC;AACtE,aAAO;AAAA,IACT;AAAA,IACA,MAAM,MAAM,SAAS,SAAS,SAAS,CAAC;AAAA,IACxC,QAAQ;AACN,eAAS,SAAS;AAClB,cAAQ,CAAC;AAAA,IACX;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,123 @@
1
+ import { App } from './index.cjs';
2
+ import { Id, InstallRef, SessionRef, Resident, FetchLike, Json } from './index.cjs';
3
+
4
+ interface SimulateOptions {
5
+ /** The app's signing secret: deliveries are signed with it. */
6
+ signingSecret: string;
7
+ /** The app's slug in deliveries; default "test-app". */
8
+ app?: string;
9
+ /** The service's basePath (AppOptions.basePath): deliveries are posted under it. */
10
+ basePath?: string;
11
+ /** The install deliveries carry unless an option says otherwise; null for none. Default {id: "500", room_id: "900", version: "1.0.0"}. */
12
+ install?: InstallRef | null;
13
+ /** The caller of call() when none is given. Default {id: "1001", name: "Tester", kind: "person"}. */
14
+ caller?: Resident;
15
+ /** The MP-Karpo-Timestamp clock in Unix seconds; default now. */
16
+ now?: () => number;
17
+ }
18
+ /** The service's answer to a delivery: the HTTP status and the JSON body (null when empty). */
19
+ interface Answer<B = any> {
20
+ status: number;
21
+ body: B;
22
+ }
23
+ interface CallOptions {
24
+ /** The call id; default a new one. Reuse one to replay a call. */
25
+ id?: Id;
26
+ install?: InstallRef | null;
27
+ session?: SessionRef | null;
28
+ idempotencyKey?: string;
29
+ /** The caller's first call to the app. */
30
+ firstSeen?: boolean;
31
+ /** Set when a declarative hook (call) runs the tool: its event. */
32
+ event?: string;
33
+ commandMessageId?: Id;
34
+ }
35
+ interface EventOptions {
36
+ /** The delivery id; default a new one. Reuse one to redeliver. */
37
+ id?: Id;
38
+ install?: InstallRef | null;
39
+ sessionId?: Id;
40
+ /** The resident the hook may act for. */
41
+ residentId?: Id;
42
+ /** Default 1. */
43
+ attempt?: number;
44
+ }
45
+ /** A join request gate delivery: the join request. */
46
+ interface GateInput {
47
+ applicant: Resident;
48
+ /** Default the install's room. */
49
+ room_id?: Id;
50
+ /** Default a new id. */
51
+ join_request_id?: Id;
52
+ note?: string;
53
+ /** The delivery id; default a new one. */
54
+ id?: Id;
55
+ install?: InstallRef | null;
56
+ }
57
+ /** A publish handshake. */
58
+ interface HandshakeInput {
59
+ /** Default "1.0.0". */
60
+ version?: string;
61
+ /** Default a new one. */
62
+ challenge?: string;
63
+ tools?: string[];
64
+ hooks?: string[];
65
+ }
66
+ interface Simulator {
67
+ /** Call a tool as caller (default the simulator's caller; null: a declarative hook's call in the app's own context). */
68
+ call<B = any>(tool: string, args?: Record<string, Json | undefined>, caller?: Resident | null, opts?: CallOptions): Promise<Answer<B>>;
69
+ /** Deliver a hook event. */
70
+ event<B = any>(name: string, data: Record<string, unknown>, opts?: EventOptions): Promise<Answer<B>>;
71
+ /** Ask the join request gate: 200 {decision, reason?}, or 204 without a decision. */
72
+ gate<B = any>(input: GateInput): Promise<Answer<B>>;
73
+ /**
74
+ * The publish handshake: 200 {challenge}; with tools and hooks (the
75
+ * manifest's, as the platform sends them) 422 app.HANDSHAKE_FAILED when a
76
+ * handler is missing.
77
+ */
78
+ handshake<B = any>(input?: HandshakeInput): Promise<Answer<B>>;
79
+ /** Wait for work the handlers left running (ctx.defer, ctx.waitUntil). */
80
+ idle(): Promise<void>;
81
+ }
82
+ /** simulate drives app with signed deliveries, as the platform sends them. */
83
+ declare function simulate(app: App, opts: SimulateOptions): Simulator;
84
+ /** A request the app sent the platform. */
85
+ interface RecordedRequest {
86
+ method: string;
87
+ /** The URL path, e.g. /v1/app-service/sessions. */
88
+ path: string;
89
+ query: Record<string, string>;
90
+ /** Lower-case names. */
91
+ headers: Record<string, string>;
92
+ /** The JSON body, the raw bytes of another body, or undefined. */
93
+ body: any;
94
+ }
95
+ /** A scripted answer; default status 200 and body {}. */
96
+ interface MockAnswer {
97
+ status?: number;
98
+ body?: unknown;
99
+ headers?: Record<string, string>;
100
+ }
101
+ interface PlatformMock {
102
+ /** The platform origin to give createApp / createClient (platform). */
103
+ readonly url: string;
104
+ /** The fetch to give createApp / createClient (fetch): every request lands here. */
105
+ fetch: FetchLike;
106
+ /** Every request so far, oldest first (a copy). */
107
+ requests(): RecordedRequest[];
108
+ /**
109
+ * Answer method (or "*") on path with answer from now on; the latest
110
+ * matching rule wins. path is the full path (/v1/apps/dice) or an
111
+ * app-service route (/sessions/*), "*" matching one segment.
112
+ */
113
+ respond(method: string, path: string, answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined)): PlatformMock;
114
+ /** The latest request. */
115
+ last(): RecordedRequest | undefined;
116
+ /** Forget the requests and the scripted answers. */
117
+ reset(): void;
118
+ }
119
+ /** mockPlatform stands in for the platform API: it records requests and answers as scripted. */
120
+ declare function mockPlatform(): PlatformMock;
121
+
122
+ export { mockPlatform, simulate };
123
+ export type { Answer, CallOptions, EventOptions, GateInput, HandshakeInput, MockAnswer, PlatformMock, RecordedRequest, SimulateOptions, Simulator };