@crvouga/mockingbird-service-turnstile 1.12.0 → 1.14.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/CHANGELOG.md CHANGED
@@ -1,6 +1,26 @@
1
1
  # Changelog — @crvouga/mockingbird-service-turnstile
2
2
 
3
- ## 1.12.0 (2026-11-13)
3
+ ## 1.14.0 (2026-11-17)
4
+
5
+ ### Features
6
+
7
+ - let a runtime skip the checkpoint it records after every write ([40a7387](https://github.com/crvouga/mockingbird/commit/40a7387208ec5f1fc0108859eded818efc3e3b5e))
8
+
9
+ ### Dependencies
10
+
11
+ - `@crvouga/mockingbird-runtime`
12
+
13
+ ## 1.13.0 (2026-11-14)
14
+
15
+ ### Features
16
+
17
+ - expand in-process emulation and resolve Plane and streaming gaps ([e6733fd](https://github.com/crvouga/mockingbird/commit/e6733fd00f5dd03259f36cc0f452780a7e0deea4))
18
+ - add browser runtime polyfills and edge-snapping app cycle ([815b739](https://github.com/crvouga/mockingbird/commit/815b7399f1e058b89b3fa025f79a5014172b3ab8))
19
+ - run lab systems in browser PR previews ([df14882](https://github.com/crvouga/mockingbird/commit/df148828ca66db1e20cf9fa2fdf38b56b5116da4))
20
+ - publish the shared runtime once; services depend on it instead of inlining it ([4903c4a](https://github.com/crvouga/mockingbird/commit/4903c4a748fd801001ad3fd34b6016b55e0f9953))
21
+ - add transcript storage, signature and meetings; tags, teams, messages, macros and calls ([ee21e12](https://github.com/crvouga/mockingbird/commit/ee21e12024768bd52c6902b1722fb35a94d2444b))
22
+
23
+ ## 1.12.0 (2026-11-12)
4
24
 
5
25
  ### Features
6
26
 
@@ -0,0 +1,33 @@
1
+ import {
2
+ createRuntime
3
+ } from "./chunk-Q6K2CEQS.js";
4
+
5
+ // src/server.ts
6
+ import { listen } from "@crvouga/mockingbird-runtime/adapter-node";
7
+ var DEFAULT_PORT = 12126;
8
+ var createServer = async (options = {}) => {
9
+ const { port, host, ...rest } = options;
10
+ const runtime = createRuntime(rest);
11
+ const listening = await listen(runtime, { port: port ?? 0, ...host ? { host } : {} });
12
+ return { ...listening, runtime };
13
+ };
14
+ var serveTarget = {
15
+ name: "turnstile",
16
+ defaultPort: DEFAULT_PORT,
17
+ options: {},
18
+ create: (_values, common) => createRuntime({
19
+ ...common.adminPrefix !== void 0 ? { adminPrefix: common.adminPrefix } : {},
20
+ ...common.adminKey !== void 0 ? { adminKey: common.adminKey } : {},
21
+ ...common.adminControls !== void 0 ? { adminControls: common.adminControls } : {},
22
+ ...common.seed !== void 0 ? { seed: common.seed } : {},
23
+ ...common.onLog ? { onLog: common.onLog } : {}
24
+ }),
25
+ banner: () => ["auth: request body secret=mock_secret", "verify: POST /turnstile/v0/siteverify"]
26
+ };
27
+
28
+ export {
29
+ DEFAULT_PORT,
30
+ createServer,
31
+ serveTarget
32
+ };
33
+ //# sourceMappingURL=chunk-ASITCN3V.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/server.ts"],
4
+ "sourcesContent": ["/// <reference types=\"node\" />\nimport { type Listening, listen, type ServeTarget } from \"@crvouga/mockingbird-adapter-node\"\nimport { createRuntime, type TurnstileRuntime, type TurnstileRuntimeOptions } from \"./runtime.js\"\nexport const DEFAULT_PORT = 12126\nexport type TurnstileServerOptions = TurnstileRuntimeOptions & { port?: number; host?: string }\nexport type TurnstileServer = Listening & { runtime: TurnstileRuntime }\nexport const createServer = async (\n options: TurnstileServerOptions = {},\n): Promise<TurnstileServer> => {\n const { port, host, ...rest } = options\n const runtime = createRuntime(rest)\n const listening = await listen(runtime, { port: port ?? 0, ...(host ? { host } : {}) })\n return { ...listening, runtime }\n}\nexport const serveTarget: ServeTarget = {\n name: \"turnstile\",\n defaultPort: DEFAULT_PORT,\n options: {},\n create: (_values, common) =>\n createRuntime({\n ...(common.adminPrefix !== undefined ? { adminPrefix: common.adminPrefix } : {}),\n ...(common.adminKey !== undefined ? { adminKey: common.adminKey } : {}),\n ...(common.adminControls !== undefined ? { adminControls: common.adminControls } : {}),\n ...(common.seed !== undefined ? { seed: common.seed } : {}),\n ...(common.onLog ? { onLog: common.onLog } : {}),\n }),\n banner: () => [\"auth: request body secret=mock_secret\", \"verify: POST /turnstile/v0/siteverify\"],\n}\n"],
5
+ "mappings": ";;;;;AACA,SAAyB,cAAgC;AAElD,IAAM,eAAe;AAGrB,IAAM,eAAe,OAC1B,UAAkC,CAAC,MACN;AAC7B,QAAM,EAAE,MAAM,MAAM,GAAG,KAAK,IAAI;AAChC,QAAM,UAAU,cAAc,IAAI;AAClC,QAAM,YAAY,MAAM,OAAO,SAAS,EAAE,MAAM,QAAQ,GAAG,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,CAAC;AACtF,SAAO,EAAE,GAAG,WAAW,QAAQ;AACjC;AACO,IAAM,cAA2B;AAAA,EACtC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,QAAQ,CAAC,SAAS,WAChB,cAAc;AAAA,IACZ,GAAI,OAAO,gBAAgB,SAAY,EAAE,aAAa,OAAO,YAAY,IAAI,CAAC;AAAA,IAC9E,GAAI,OAAO,aAAa,SAAY,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;AAAA,IACrE,GAAI,OAAO,kBAAkB,SAAY,EAAE,eAAe,OAAO,cAAc,IAAI,CAAC;AAAA,IACpF,GAAI,OAAO,SAAS,SAAY,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;AAAA,IACzD,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,EAChD,CAAC;AAAA,EACH,QAAQ,MAAM,CAAC,yCAAyC,uCAAuC;AACjG;",
6
+ "names": []
7
+ }
@@ -0,0 +1,211 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // <define:__MOCKINGBIRD_ADMIN_BRAND__>
20
+ var define_MOCKINGBIRD_ADMIN_BRAND_default = { vendor: "Cloudflare Turnstile", website: "https://www.cloudflare.com/products/turnstile/", docs: "https://developers.cloudflare.com/turnstile/get-started/server-side-validation/", guide: "https://mockingbird.chrisvouga.dev/services/turnstile", logo: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGMAAABgCAMAAAA+cTwJAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAABCUExURUdwTP9QCv9PC/9PCf//6/9PD5NwcP9QCv/79fZNCf1PCvpOCvRMCf/s4P3Nt/1eH/ujfvy6nf2RZv17Rv/byf2vjnXJwEoAAAAHdFJOUwDWVIwBEAHHGD0SAAAC1UlEQVRo3u3aCY+rIBAA4NpLmJFD0P//Vx8eVVCwhUKzeXGSptsqfDvDYXfr5TLG43qrKqyzBVbV7Xpx4pqx+zUqW7nVheJWnliRa10wpnI9q5IGPoqnMSdyK2uMI1KVNapfGVjWgMGoC8dpnMZpnMZp/HFD6J4zQgjruBJFDN0P/S/BVXZDcLINpvIakhFPcJHPEC3xB9O5DNGRYKg8xhFBiM5i9EcEYSKDochxdN8bgr0xiPzaaN8Rh9U6NEBrPbQV5H3IJENM+4ZZye0HxkEiYUOuzdkHxsEiCRqSREYba0A0QRhEGoJFG7zWUiotPjZUNEEUdIFrSsDg8aUSInRN8RsQn0aLKjSRsxkaeejy6DUg3mCILLRcfAZA/LTSVASvKXtDSB4/cSXdGeuYbA0h4wFDNJRSHlr4G0OkCExRY6AOXYFdQycQrBdDFgbZloD7DF8W5jPnK9pX9PIVymweTTMZtBFayb41Z7oj4hi+LFTzPug2uDN/bcO7STFmZbKmsiQyF4qieZg0ZGvyYO6o20bKeJuOxEigZ0Z2sDU0SYt+ENA3XdjOaBMNIgzhvxgAgGNAl2ooxEANRmIxjMhSDY2BpcsQ3FoBSTcCn4Y7dGsFycZuW18XumuYWqWORx8aDTNQo3G/DwYYw0yOYR2FlvH0NP+8vB5XxhLTsbnRsE3iOLHmPGA0/MSouHuGZbvC2oFlPO+vWh2m0Yy/HnWQXR4OMh3yGzS44TXWk8VtiLle1DLutoF2b02z7c0buDesDKc87PGYz3vXrZ+wE1kO2XkAgJNJiuE5MO0l93V9YLZYZJjyWNf5F0ig6ZTGazzscsX27284vb3ZE2soEHUeI9ww+FkU5sfQdH1nfgnzq92fZWCftj3l/L/oaZzGsVH4u1T8n753/sV39L+41+CBxUv1k3s/fnIPy0/uxTHlKjKB0b6n6Pm8ZL43CoZ7ox5z9/8AXA8Zr53RgkAAAAAASUVORK5CYII=", color: null, description: "Server-side challenge token verification." };
21
+
22
+ // mockingbird-service-runtime:@crvouga/mockingbird-runtime/service
23
+ var service_exports = {};
24
+ __export(service_exports, {
25
+ PACKAGE_VERSION: () => PACKAGE_VERSION,
26
+ createRuntime: () => createRuntime
27
+ });
28
+ __reExport(service_exports, service_star);
29
+ import * as service_star from "@crvouga/mockingbird-runtime/service";
30
+ import { PACKAGE_VERSION as SHARED_VERSION, createRuntime as sharedRuntime } from "@crvouga/mockingbird-runtime/service";
31
+ var PACKAGE_VERSION = true ? "1.14.0" : SHARED_VERSION;
32
+ var ADMIN_BRAND = typeof define_MOCKINGBIRD_ADMIN_BRAND_default === "object" ? define_MOCKINGBIRD_ADMIN_BRAND_default : void 0;
33
+ var createRuntime = (options) => sharedRuntime({
34
+ ...options,
35
+ version: options.version ?? PACKAGE_VERSION,
36
+ adminBrand: options.adminBrand ?? ADMIN_BRAND
37
+ });
38
+
39
+ // src/generated/openapi.ts
40
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Cloudflare Turnstile Siteverify","version":"v0","x-mockingbird-upstream":{"url":"https://developers.cloudflare.com/turnstile/get-started/server-side-validation/"}},"servers":[{"url":"https://challenges.cloudflare.com"}],"paths":{"/turnstile/v0/siteverify":{"post":{"operationId":"Siteverify","requestBody":{"required":true,"content":{"application/json":{"example":{"secret":"mock_secret","response":"missing-token"},"schema":{"$ref":"#/components/schemas/verification"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/verification"}}}},"responses":{"200":{"description":"Verification result, including rejected tokens","content":{"application/json":{"schema":{"type":"object","required":["success","error-codes"],"properties":{"success":{"type":"boolean"},"error-codes":{"type":"array","items":{"type":"string"}},"challenge_ts":{"type":"string","format":"date-time"},"hostname":{"type":"string"},"action":{"type":"string"},"cdata":{"type":"string"}}}}}}},"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}}}}},"components":{"schemas":{"verification":{"type":"object","properties":{"secret":{"type":"string","maxLength":100},"response":{"type":"string","maxLength":2048},"remoteip":{"type":"string","maxLength":100},"idempotency_key":{"type":"string","maxLength":36}}}}}}`);
41
+ var operationIds = ["Siteverify"];
42
+ var supportedOperationIds = ["Siteverify"];
43
+
44
+ // src/runtime.ts
45
+ var TURNSTILE_PRESETS = {
46
+ internal_error: {
47
+ description: "Verification failure, not transport failure",
48
+ rules: [{ status: 200, body: { success: false, "error-codes": ["internal-error"] } }]
49
+ },
50
+ rate_limited: {
51
+ description: "Scripted transport throttle",
52
+ rules: [{ status: 429, body: { success: false }, headers: { "retry-after": "1" } }]
53
+ },
54
+ server_error: {
55
+ description: "Scripted transport failure",
56
+ rules: [{ status: 503, body: { success: false } }]
57
+ },
58
+ connection_drop: {
59
+ description: "Connection closes before verification",
60
+ rules: [{ drop: true }]
61
+ }
62
+ };
63
+ var createRuntime2 = (options = {}) => createRuntime({
64
+ name: TURNSTILE_NAMESPACE,
65
+ document,
66
+ presets: TURNSTILE_PRESETS,
67
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
68
+ ...options.clock ? { clock: options.clock } : {},
69
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
70
+ ...options.adminPrefix ? { adminPrefix: options.adminPrefix } : {},
71
+ ...options.adminKey ? { adminKey: options.adminKey } : {},
72
+ ...options.adminControls !== void 0 ? { adminControls: options.adminControls } : {},
73
+ ...options.onLog ? { onLog: options.onLog } : {},
74
+ create: ({ sqlite, namespace, clock }) => new TurnstileAPI({
75
+ sqlite,
76
+ namespace,
77
+ now: clock.now,
78
+ ...options.sites ? { sites: options.sites } : {},
79
+ ...options.tokens ? { tokens: options.tokens } : {}
80
+ }),
81
+ admin: (runtime) => ({
82
+ "POST /issue": ({ body, namespace }) => runtime.instance(namespace).issue(body),
83
+ "GET /attempts": ({ namespace }) => Response.json({
84
+ data: runtime.instance(namespace).attempts.list().map(({ value }) => value)
85
+ })
86
+ })
87
+ });
88
+
89
+ // src/index.ts
90
+ var TURNSTILE_NAMESPACE = "turnstile";
91
+ var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
92
+ var failure = (code) => (0, service_exports.jsonRes)(200, { success: false, "error-codes": [code] });
93
+ var TurnstileAPI = class {
94
+ app;
95
+ tokens;
96
+ attempts;
97
+ sites;
98
+ initialized;
99
+ ids;
100
+ idempotency;
101
+ service;
102
+ now;
103
+ fixtures;
104
+ constructor(options = {}) {
105
+ const sqlite = (0, service_exports.bootSqlite)(options.sqlite), namespace = options.namespace ?? TURNSTILE_NAMESPACE;
106
+ this.now = options.now ?? Date.now;
107
+ this.tokens = new service_exports.Collection(sqlite, namespace, "tokens");
108
+ this.attempts = new service_exports.Collection(sqlite, namespace, "attempts");
109
+ this.sites = new service_exports.Collection(sqlite, namespace, "sites");
110
+ this.initialized = new service_exports.Collection(sqlite, namespace, "initialized");
111
+ this.ids = new service_exports.IdSequence(sqlite, namespace, `turnstile:${namespace}`);
112
+ this.idempotency = new service_exports.IdempotencyStore(sqlite, namespace);
113
+ this.fixtures = structuredClone({
114
+ sites: options.sites ?? [{ siteKey: "mock_site", secret: "mock_secret" }],
115
+ tokens: options.tokens ?? []
116
+ });
117
+ this.seed();
118
+ this.service = (0, service_exports.createService)({
119
+ sqlite,
120
+ namespace,
121
+ document,
122
+ now: this.now,
123
+ notFound: () => (0, service_exports.jsonRes)(404, { error: "Not found" }),
124
+ onError: (error) => {
125
+ throw error;
126
+ },
127
+ handlers: (0, service_exports.defineOperations)({
128
+ Siteverify: (context) => this.verify(context)
129
+ })
130
+ });
131
+ this.app = this.service.app;
132
+ }
133
+ seed() {
134
+ if (this.initialized.has("seed")) return;
135
+ for (const site of this.fixtures.sites) this.sites.insert(site.siteKey, site);
136
+ for (const token of this.fixtures.tokens) this.tokens.insert(token.token, token);
137
+ this.initialized.insert("seed", { value: true });
138
+ }
139
+ fetch(request) {
140
+ return this.service.fetch(request);
141
+ }
142
+ async reset() {
143
+ await this.service.reset();
144
+ this.seed();
145
+ }
146
+ issue(input) {
147
+ if (!record(input)) return (0, service_exports.jsonRes)(400, { error: "Expected token fixture object" });
148
+ const siteKey = input.siteKey ?? "mock_site", hostname = input.hostname ?? "example.test", action = input.action ?? "", cdata = input.cdata ?? "";
149
+ if (typeof siteKey !== "string" || !this.sites.has(siteKey) || typeof hostname !== "string" || !hostname || typeof action !== "string" || !/^[A-Za-z0-9_-]{0,32}$/.test(action) || typeof cdata !== "string" || !/^[A-Za-z0-9_-]{0,255}$/.test(cdata))
150
+ return (0, service_exports.jsonRes)(400, { error: "Invalid site, hostname, action or cdata" });
151
+ const token = this.ids.next("mock_turnstile_", 24);
152
+ this.tokens.insert(token, {
153
+ token,
154
+ siteKey,
155
+ hostname,
156
+ action,
157
+ cdata,
158
+ issuedAt: this.now(),
159
+ used: false
160
+ });
161
+ return (0, service_exports.jsonRes)(200, { token });
162
+ }
163
+ async verify(context) {
164
+ const body = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
165
+ if (!record(body)) return failure("bad-request");
166
+ if (!body.secret) return failure("missing-input-secret");
167
+ const site = this.sites.list().map(({ value }) => value).find((value) => value.secret === body.secret);
168
+ if (!site) return failure("invalid-input-secret");
169
+ if (!body.response) return failure("missing-input-response");
170
+ if (typeof body.response !== "string" || body.response.length > 2048)
171
+ return failure("invalid-input-response");
172
+ const token = this.tokens.get(body.response);
173
+ if (!token || token.siteKey !== site.siteKey) return failure("invalid-input-response");
174
+ const key = body.idempotency_key;
175
+ if (key !== void 0 && (typeof key !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(key)))
176
+ return failure("bad-request");
177
+ const validate = () => {
178
+ const expired = token.used || this.now() - token.issuedAt >= 3e5;
179
+ this.attempts.insert(this.ids.next("attempt_", 20), { at: this.now(), success: !expired });
180
+ if (expired) return failure("timeout-or-duplicate");
181
+ this.tokens.insert(token.token, { ...token, used: true });
182
+ return (0, service_exports.jsonRes)(200, {
183
+ success: true,
184
+ "error-codes": [],
185
+ challenge_ts: new Date(token.issuedAt).toISOString(),
186
+ hostname: token.hostname,
187
+ action: token.action,
188
+ cdata: token.cdata
189
+ });
190
+ };
191
+ if (typeof key === "string")
192
+ return this.idempotency.run(
193
+ key,
194
+ JSON.stringify([site.siteKey, token.token, body.remoteip ?? null]),
195
+ { mismatch: () => failure("bad-request"), conflict: () => failure("internal-error") },
196
+ validate
197
+ );
198
+ return validate();
199
+ }
200
+ };
201
+
202
+ export {
203
+ document,
204
+ operationIds,
205
+ supportedOperationIds,
206
+ TURNSTILE_PRESETS,
207
+ createRuntime2 as createRuntime,
208
+ TURNSTILE_NAMESPACE,
209
+ TurnstileAPI
210
+ };
211
+ //# sourceMappingURL=chunk-Q6K2CEQS.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["<define:__MOCKINGBIRD_ADMIN_BRAND__>", "mockingbird-service-runtime:@crvouga/mockingbird-runtime/service", "../src/generated/openapi.ts", "../src/runtime.ts", "../src/index.ts"],
4
+ "sourcesContent": ["{\"vendor\":\"Cloudflare Turnstile\",\"website\":\"https://www.cloudflare.com/products/turnstile/\",\"docs\":\"https://developers.cloudflare.com/turnstile/get-started/server-side-validation/\",\"guide\":\"https://mockingbird.chrisvouga.dev/services/turnstile\",\"logo\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGMAAABgCAMAAAA+cTwJAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAABCUExURUdwTP9QCv9PC/9PCf//6/9PD5NwcP9QCv/79fZNCf1PCvpOCvRMCf/s4P3Nt/1eH/ujfvy6nf2RZv17Rv/byf2vjnXJwEoAAAAHdFJOUwDWVIwBEAHHGD0SAAAC1UlEQVRo3u3aCY+rIBAA4NpLmJFD0P//Vx8eVVCwhUKzeXGSptsqfDvDYXfr5TLG43qrKqyzBVbV7Xpx4pqx+zUqW7nVheJWnliRa10wpnI9q5IGPoqnMSdyK2uMI1KVNapfGVjWgMGoC8dpnMZpnMZp/HFD6J4zQgjruBJFDN0P/S/BVXZDcLINpvIakhFPcJHPEC3xB9O5DNGRYKg8xhFBiM5i9EcEYSKDochxdN8bgr0xiPzaaN8Rh9U6NEBrPbQV5H3IJENM+4ZZye0HxkEiYUOuzdkHxsEiCRqSREYba0A0QRhEGoJFG7zWUiotPjZUNEEUdIFrSsDg8aUSInRN8RsQn0aLKjSRsxkaeejy6DUg3mCILLRcfAZA/LTSVASvKXtDSB4/cSXdGeuYbA0h4wFDNJRSHlr4G0OkCExRY6AOXYFdQycQrBdDFgbZloD7DF8W5jPnK9pX9PIVymweTTMZtBFayb41Z7oj4hi+LFTzPug2uDN/bcO7STFmZbKmsiQyF4qieZg0ZGvyYO6o20bKeJuOxEigZ0Z2sDU0SYt+ENA3XdjOaBMNIgzhvxgAgGNAl2ooxEANRmIxjMhSDY2BpcsQ3FoBSTcCn4Y7dGsFycZuW18XumuYWqWORx8aDTNQo3G/DwYYw0yOYR2FlvH0NP+8vB5XxhLTsbnRsE3iOLHmPGA0/MSouHuGZbvC2oFlPO+vWh2m0Yy/HnWQXR4OMh3yGzS44TXWk8VtiLle1DLutoF2b02z7c0buDesDKc87PGYz3vXrZ+wE1kO2XkAgJNJiuE5MO0l93V9YLZYZJjyWNf5F0ig6ZTGazzscsX27284vb3ZE2soEHUeI9ww+FkU5sfQdH1nfgnzq92fZWCftj3l/L/oaZzGsVH4u1T8n753/sV39L+41+CBxUv1k3s/fnIPy0/uxTHlKjKB0b6n6Pm8ZL43CoZ7ox5z9/8AXA8Zr53RgkAAAAAASUVORK5CYII=\",\"color\":null,\"description\":\"Server-side challenge token verification.\"}", "export * from \"@crvouga/mockingbird-runtime/service\"\nimport { PACKAGE_VERSION as SHARED_VERSION, createRuntime as sharedRuntime } from \"@crvouga/mockingbird-runtime/service\"\nexport const PACKAGE_VERSION =\n typeof __MOCKINGBIRD_PACKAGE_VERSION__ === \"string\" ? __MOCKINGBIRD_PACKAGE_VERSION__ : SHARED_VERSION\nconst ADMIN_BRAND =\n typeof __MOCKINGBIRD_ADMIN_BRAND__ === \"object\" ? __MOCKINGBIRD_ADMIN_BRAND__ : undefined\nexport const createRuntime = (options) =>\n sharedRuntime({\n ...options,\n version: options.version ?? PACKAGE_VERSION,\n adminBrand: options.adminBrand ?? ADMIN_BRAND,\n })\n", "// Generated by @crvouga/mockingbird-openapi-codegen from openapi.yaml. Do not edit.\n\nimport type { OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\n\nexport const document: OpenAPIDocument = JSON.parse(`{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Cloudflare Turnstile Siteverify\",\"version\":\"v0\",\"x-mockingbird-upstream\":{\"url\":\"https://developers.cloudflare.com/turnstile/get-started/server-side-validation/\"}},\"servers\":[{\"url\":\"https://challenges.cloudflare.com\"}],\"paths\":{\"/turnstile/v0/siteverify\":{\"post\":{\"operationId\":\"Siteverify\",\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"example\":{\"secret\":\"mock_secret\",\"response\":\"missing-token\"},\"schema\":{\"$ref\":\"#/components/schemas/verification\"}},\"application/x-www-form-urlencoded\":{\"schema\":{\"$ref\":\"#/components/schemas/verification\"}}}},\"responses\":{\"200\":{\"description\":\"Verification result, including rejected tokens\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"success\",\"error-codes\"],\"properties\":{\"success\":{\"type\":\"boolean\"},\"error-codes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"challenge_ts\":{\"type\":\"string\",\"format\":\"date-time\"},\"hostname\":{\"type\":\"string\"},\"action\":{\"type\":\"string\"},\"cdata\":{\"type\":\"string\"}}}}}}},\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}}}}},\"components\":{\"schemas\":{\"verification\":{\"type\":\"object\",\"properties\":{\"secret\":{\"type\":\"string\",\"maxLength\":100},\"response\":{\"type\":\"string\",\"maxLength\":2048},\"remoteip\":{\"type\":\"string\",\"maxLength\":100},\"idempotency_key\":{\"type\":\"string\",\"maxLength\":36}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"Siteverify\"\nexport type SupportedOperationId = \"Siteverify\"\nexport const operationIds = [\"Siteverify\"] as const\nexport const supportedOperationIds = [\"Siteverify\"] as const\n", "import {\n type Clock,\n createRuntime as createServiceRuntime,\n type FaultPreset,\n type MockControls,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { document } from \"./generated/openapi.js\"\nimport { type Site, type Token, TURNSTILE_NAMESPACE, TurnstileAPI } from \"./index.js\"\nexport const TURNSTILE_PRESETS: Record<string, FaultPreset> = {\n internal_error: {\n description: \"Verification failure, not transport failure\",\n rules: [{ status: 200, body: { success: false, \"error-codes\": [\"internal-error\"] } }],\n },\n rate_limited: {\n description: \"Scripted transport throttle\",\n rules: [{ status: 429, body: { success: false }, headers: { \"retry-after\": \"1\" } }],\n },\n server_error: {\n description: \"Scripted transport failure\",\n rules: [{ status: 503, body: { success: false } }],\n },\n connection_drop: {\n description: \"Connection closes before verification\",\n rules: [{ drop: true }],\n },\n}\nexport type TurnstileRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: string | number\n adminPrefix?: string\n adminKey?: string\n /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */\n adminControls?: MockControls\n onLog?: (entry: RequestLog) => void\n sites?: Site[]\n tokens?: Token[]\n}\nexport type TurnstileRuntime = ServiceRuntime<TurnstileAPI>\nexport const createRuntime = (options: TurnstileRuntimeOptions = {}): TurnstileRuntime =>\n createServiceRuntime({\n name: TURNSTILE_NAMESPACE,\n document,\n presets: TURNSTILE_PRESETS,\n ...(options.sqlite ? { sqlite: options.sqlite } : {}),\n ...(options.clock ? { clock: options.clock } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.adminPrefix ? { adminPrefix: options.adminPrefix } : {}),\n ...(options.adminKey ? { adminKey: options.adminKey } : {}),\n ...(options.adminControls !== undefined ? { adminControls: options.adminControls } : {}),\n ...(options.onLog ? { onLog: options.onLog } : {}),\n create: ({ sqlite, namespace, clock }) =>\n new TurnstileAPI({\n sqlite,\n namespace,\n now: clock.now,\n ...(options.sites ? { sites: options.sites } : {}),\n ...(options.tokens ? { tokens: options.tokens } : {}),\n }),\n admin: (runtime) => ({\n \"POST /issue\": ({ body, namespace }) => runtime.instance(namespace).issue(body),\n \"GET /attempts\": ({ namespace }) =>\n Response.json({\n data: runtime\n .instance(namespace)\n .attempts.list()\n .map(({ value }) => value),\n }),\n }),\n })\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n bootSqlite,\n Collection,\n createService,\n defineOperations,\n IdempotencyStore,\n IdSequence,\n jsonRes,\n type OperationContext,\n type Service,\n} from \"@crvouga/mockingbird-service\"\nimport type { Hono } from \"hono\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\n\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport { createRuntime, TURNSTILE_PRESETS } from \"./runtime.js\"\nexport const TURNSTILE_NAMESPACE = \"turnstile\"\nexport type Site = { siteKey: string; secret: string }\nexport type Token = {\n token: string\n siteKey: string\n issuedAt: number\n hostname: string\n action: string\n cdata: string\n used: boolean\n}\nexport type TurnstileAPIOptions = APIOptions & { sites?: Site[]; tokens?: Token[] }\nconst record = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value)\nconst failure = (code: string) => jsonRes(200, { success: false, \"error-codes\": [code] })\nexport class TurnstileAPI implements FetchAPI {\n readonly app: Hono\n readonly tokens: Collection<Token>\n readonly attempts: Collection<{ at: number; success: boolean }>\n readonly sites: Collection<Site>\n private readonly initialized: Collection<{ value: boolean }>\n private readonly ids: IdSequence\n private readonly idempotency: IdempotencyStore\n private readonly service: Service\n private readonly now: () => number\n private readonly fixtures: { sites: Site[]; tokens: Token[] }\n constructor(options: TurnstileAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite),\n namespace = options.namespace ?? TURNSTILE_NAMESPACE\n this.now = options.now ?? Date.now\n this.tokens = new Collection(sqlite, namespace, \"tokens\")\n this.attempts = new Collection(sqlite, namespace, \"attempts\")\n this.sites = new Collection(sqlite, namespace, \"sites\")\n this.initialized = new Collection(sqlite, namespace, \"initialized\")\n this.ids = new IdSequence(sqlite, namespace, `turnstile:${namespace}`)\n this.idempotency = new IdempotencyStore(sqlite, namespace)\n this.fixtures = structuredClone({\n sites: options.sites ?? [{ siteKey: \"mock_site\", secret: \"mock_secret\" }],\n tokens: options.tokens ?? [],\n })\n this.seed()\n this.service = createService({\n sqlite,\n namespace,\n document,\n now: this.now,\n notFound: () => jsonRes(404, { error: \"Not found\" }),\n onError: (error) => {\n throw error\n },\n handlers: defineOperations<SupportedOperationId>({\n Siteverify: (context) => this.verify(context),\n }),\n })\n this.app = this.service.app\n }\n private seed(): void {\n if (this.initialized.has(\"seed\")) return\n for (const site of this.fixtures.sites) this.sites.insert(site.siteKey, site)\n for (const token of this.fixtures.tokens) this.tokens.insert(token.token, token)\n this.initialized.insert(\"seed\", { value: true })\n }\n fetch(request: Request): Promise<Response> {\n return this.service.fetch(request)\n }\n async reset(): Promise<void> {\n await this.service.reset()\n this.seed()\n }\n issue(input: unknown): Response {\n if (!record(input)) return jsonRes(400, { error: \"Expected token fixture object\" })\n const siteKey = input.siteKey ?? \"mock_site\",\n hostname = input.hostname ?? \"example.test\",\n action = input.action ?? \"\",\n cdata = input.cdata ?? \"\"\n if (\n typeof siteKey !== \"string\" ||\n !this.sites.has(siteKey) ||\n typeof hostname !== \"string\" ||\n !hostname ||\n typeof action !== \"string\" ||\n !/^[A-Za-z0-9_-]{0,32}$/.test(action) ||\n typeof cdata !== \"string\" ||\n !/^[A-Za-z0-9_-]{0,255}$/.test(cdata)\n )\n return jsonRes(400, { error: \"Invalid site, hostname, action or cdata\" })\n const token = this.ids.next(\"mock_turnstile_\", 24)\n this.tokens.insert(token, {\n token,\n siteKey,\n hostname,\n action,\n cdata,\n issuedAt: this.now(),\n used: false,\n })\n return jsonRes(200, { token })\n }\n private async verify(context: OperationContext): Promise<Response> {\n const body =\n context.body.kind === \"json\" || context.body.kind === \"form\" ? context.body.value : undefined\n if (!record(body)) return failure(\"bad-request\")\n if (!body.secret) return failure(\"missing-input-secret\")\n const site = this.sites\n .list()\n .map(({ value }) => value)\n .find((value) => value.secret === body.secret)\n if (!site) return failure(\"invalid-input-secret\")\n if (!body.response) return failure(\"missing-input-response\")\n if (typeof body.response !== \"string\" || body.response.length > 2048)\n return failure(\"invalid-input-response\")\n const token = this.tokens.get(body.response)\n if (!token || token.siteKey !== site.siteKey) return failure(\"invalid-input-response\")\n const key = body.idempotency_key\n if (\n key !== undefined &&\n (typeof key !== \"string\" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(key))\n )\n return failure(\"bad-request\")\n const validate = () => {\n const expired = token.used || this.now() - token.issuedAt >= 300_000\n this.attempts.insert(this.ids.next(\"attempt_\", 20), { at: this.now(), success: !expired })\n if (expired) return failure(\"timeout-or-duplicate\")\n this.tokens.insert(token.token, { ...token, used: true })\n return jsonRes(200, {\n success: true,\n \"error-codes\": [],\n challenge_ts: new Date(token.issuedAt).toISOString(),\n hostname: token.hostname,\n action: token.action,\n cdata: token.cdata,\n })\n }\n if (typeof key === \"string\")\n return this.idempotency.run(\n key,\n JSON.stringify([site.siteKey, token.token, body.remoteip ?? null]),\n { mismatch: () => failure(\"bad-request\"), conflict: () => failure(\"internal-error\") },\n validate,\n )\n return validate()\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA,+CAAC,QAAS,wBAAuB,SAAU,kDAAiD,MAAO,mFAAkF,OAAQ,yDAAwD,MAAO,stCAAqtC,OAAQ,MAAK,aAAc,4CAA2C;;;ACAvhD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAAc;AACd,SAAS,mBAAmB,gBAAgB,iBAAiB,qBAAqB;AAC3E,IAAM,kBACX,OAAsD,sBAAkC;AAC1F,IAAM,cACJ,OAAO,2CAAgC,WAAW,yCAA8B;AAC3E,IAAM,gBAAgB,CAAC,YAC5B,cAAc;AAAA,EACZ,GAAG;AAAA,EACH,SAAS,QAAQ,WAAW;AAAA,EAC5B,YAAY,QAAQ,cAAc;AACpC,CAAC;;;ACPI,IAAM,WAA4B,KAAK,MAAM,+0CAA+0C;AAI53C,IAAM,eAAe,CAAC,YAAY;AAClC,IAAM,wBAAwB,CAAC,YAAY;;;ACE3C,IAAM,oBAAiD;AAAA,EAC5D,gBAAgB;AAAA,IACd,aAAa;AAAA,IACb,OAAO,CAAC,EAAE,QAAQ,KAAK,MAAM,EAAE,SAAS,O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AAK,IAAI,IAAI,MAAM,YAAY;AAC7D,WAAK,SAAS,OAAO,KAAK,IAAI,KAAK,YAAY,EAAE,GAAG,EAAE,IAAI,KAAK,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC;AACzF,UAAI,QAAS,QAAO,QAAQ,sBAAsB;AAClD,WAAK,OAAO,OAAO,MAAM,OAAO,EAAE,GAAG,OAAO,MAAM,KAAK,CAAC;AACxD,iBAAO,yBAAQ,KAAK;AAAA,QAClB,SAAS;AAAA,QACT,eAAe,CAAC;AAAA,QAChB,cAAc,IAAI,KAAK,MAAM,QAAQ,EAAE,YAAY;AAAA,QACnD,UAAU,MAAM;AAAA,QAChB,QAAQ,MAAM;AAAA,QACd,OAAO,MAAM;AAAA,MACf,CAAC;AAAA,IACH;AACA,QAAI,OAAO,QAAQ;AACjB,aAAO,KAAK,YAAY;AAAA,QACtB;AAAA,QACA,KAAK,UAAU,CAAC,KAAK,SAAS,MAAM,OAAO,KAAK,YAAY,IAAI,CAAC;AAAA,QACjE,EAAE,UAAU,MAAM,QAAQ,aAAa,GAAG,UAAU,MAAM,QAAQ,gBAAgB,EAAE;AAAA,QACpF;AAAA,MACF;AACF,WAAO,SAAS;AAAA,EAClB;AACF;",
6
+ "names": ["createRuntime"]
7
+ }
package/dist/cli.js CHANGED
@@ -1,13 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- runCli,
4
- serveCommand,
5
3
  serveTarget
6
- } from "./chunk-HYASGOG5.js";
7
- import "./chunk-WBNRB3VS.js";
8
- import "./chunk-WJVNP2N6.js";
4
+ } from "./chunk-ASITCN3V.js";
5
+ import "./chunk-Q6K2CEQS.js";
9
6
 
10
7
  // src/cli.ts
8
+ import { runCli, serveCommand } from "@crvouga/mockingbird-runtime/adapter-node";
11
9
  var code = await runCli(
12
10
  {
13
11
  bin: "mockingbird-turnstile",
package/dist/cli.js.map CHANGED
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/cli.ts"],
4
4
  "sourcesContent": ["#!/usr/bin/env node\n/// <reference types=\"node\" />\nimport { runCli, serveCommand } from \"@crvouga/mockingbird-adapter-node\"\nimport { serveTarget } from \"./server.js\"\n\nconst code = await runCli(\n {\n bin: \"mockingbird-turnstile\",\n description: \"Local Turnstile contacts mock\",\n commands: { serve: serveCommand(serveTarget) },\n },\n process.argv.slice(2),\n)\nif (code !== 0) process.exitCode = code\n"],
5
- "mappings": ";;;;;;;;;;AAKA,IAAM,OAAO,MAAM;AAAA,EACjB;AAAA,IACE,KAAK;AAAA,IACL,aAAa;AAAA,IACb,UAAU,EAAE,OAAO,aAAa,WAAW,EAAE;AAAA,EAC/C;AAAA,EACA,QAAQ,KAAK,MAAM,CAAC;AACtB;AACA,IAAI,SAAS,EAAG,SAAQ,WAAW;",
5
+ "mappings": ";;;;;;;AAEA,SAAS,QAAQ,oBAAoB;AAGrC,IAAM,OAAO,MAAM;AAAA,EACjB;AAAA,IACE,KAAK;AAAA,IACL,aAAa;AAAA,IACb,UAAU,EAAE,OAAO,aAAa,WAAW,EAAE;AAAA,EAC/C;AAAA,EACA,QAAQ,KAAK,MAAM,CAAC;AACtB;AACA,IAAI,SAAS,EAAG,SAAQ,WAAW;",
6
6
  "names": []
7
7
  }
package/dist/index.d.ts CHANGED
@@ -113,98 +113,6 @@ interface FetchAPI {
113
113
  /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
114
114
  type FetchHandler = (request: Request) => Promise<Response>;
115
115
 
116
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
117
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
118
- /** Mutation counters returned by {@link SqliteStatement.run}. */
119
- type SqliteRunResult$1 = {
120
- changes: number;
121
- lastInsertRowid: number | bigint;
122
- };
123
- /**
124
- * Prepared statement bound to a {@link SqliteClient}.
125
- *
126
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
127
- */
128
- interface SqliteStatement$1 {
129
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
130
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
131
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
132
- }
133
- /**
134
- * Sync SQLite client port owned by Mockingbird.
135
- *
136
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
137
- * `bun:sqlite` instances all work when they expose this surface.
138
- */
139
- interface SqliteClient$1 {
140
- exec(sql: string): void;
141
- prepare(sql: string): SqliteStatement$1;
142
- transaction<T>(fn: () => T): T;
143
- }
144
-
145
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
146
- type Stored<T> = {
147
- seq: number;
148
- value: T;
149
- };
150
- type ListRecordsOptions<T> = {
151
- /** Keep only records passing the predicate. */
152
- where?: (value: T, seq: number) => boolean;
153
- /** Sort order; default newest first. */
154
- order?: "newest" | "oldest";
155
- };
156
- /**
157
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
158
- * sequence, never by id lexicographic order, so list semantics stay stable.
159
- */
160
- declare class Collection<T> {
161
- private readonly sqlite;
162
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
163
- readonly namespace: string;
164
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
165
- readonly collectionName: string;
166
- private readonly statements;
167
- private prepare;
168
- constructor(sqlite: SqliteClient$1,
169
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
170
- namespace: string,
171
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
172
- collectionName: string);
173
- private bumpCollectionSeq;
174
- nextSequence(): number;
175
- get(id: string): T | undefined;
176
- has(id: string): boolean;
177
- /** Insert a new record, assigning it the next sequence number. */
178
- insert(id: string, value: T): Stored<T>;
179
- /** Replace an existing record's value, keeping its position. */
180
- update(id: string, value: T): Stored<T> | undefined;
181
- delete(id: string): boolean;
182
- /** How many records the collection holds, without reading them. */
183
- count(): number;
184
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
185
- id: string;
186
- }>;
187
- }
188
-
189
- /**
190
- * What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
191
- * which derives the base from the wall clock when the runtime is created.
192
- */
193
- type IdBase = number | string;
194
-
195
- /** Options every provider constructor accepts. */
196
- type APIOptions = {
197
- /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
198
- sqlite?: SqliteClient$1;
199
- /** Clock used for `created`-style fields. Default `Date.now`. */
200
- now?: () => number;
201
- /**
202
- * Storage namespace for this instance's records. Instances sharing one SQLite
203
- * client stay isolated when their namespaces differ. Defaults to the service name.
204
- */
205
- namespace?: string;
206
- };
207
-
208
116
  /**
209
117
  * The single source of time for a service.
210
118
  *
@@ -235,6 +143,11 @@ type Clock = {
235
143
  state(): ClockState;
236
144
  };
237
145
 
146
+ type UpstreamState = {
147
+ mode: "emulated" | "forward";
148
+ baseUrl: string;
149
+ };
150
+
238
151
  /**
239
152
  * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
240
153
  * request a percentage fault hits — is reproducible from a seed.
@@ -511,6 +424,7 @@ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
511
424
  * `records` are required, so a hand-written seed file is a valid snapshot.
512
425
  */
513
426
  type SnapshotDocument = {
427
+ upstream?: UpstreamState;
514
428
  format: typeof SNAPSHOT_FORMAT;
515
429
  /** The service that wrote it. A snapshot is rejected by any other service. */
516
430
  service?: string;
@@ -584,6 +498,7 @@ type LatencyState = LatencyRule & {
584
498
  };
585
499
  /** What {@link controlHeaders} turns into request headers. */
586
500
  type ControlHeaderInput = {
501
+ upstream?: "emulated" | "forward";
587
502
  namespace?: string;
588
503
  adminKey?: string;
589
504
  branch?: string;
@@ -601,6 +516,48 @@ type ControlHeaderInput = {
601
516
  snapshot?: string;
602
517
  };
603
518
 
519
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
520
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
521
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
522
+ type SqliteRunResult$1 = {
523
+ changes: number;
524
+ lastInsertRowid: number | bigint;
525
+ };
526
+ /**
527
+ * Prepared statement bound to a {@link SqliteClient}.
528
+ *
529
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
530
+ */
531
+ interface SqliteStatement$1 {
532
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
533
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
534
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
535
+ }
536
+ /**
537
+ * Sync SQLite client port owned by Mockingbird.
538
+ *
539
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
540
+ * `bun:sqlite` instances all work when they expose this surface.
541
+ */
542
+ interface SqliteClient$1 {
543
+ exec(sql: string): void;
544
+ prepare(sql: string): SqliteStatement$1;
545
+ transaction<T>(fn: () => T): T;
546
+ }
547
+
548
+ /** Options every provider constructor accepts. */
549
+ type APIOptions = {
550
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
551
+ sqlite?: SqliteClient$1;
552
+ /** Clock used for `created`-style fields. Default `Date.now`. */
553
+ now?: () => number;
554
+ /**
555
+ * Storage namespace for this instance's records. Instances sharing one SQLite
556
+ * client stay isolated when their namespaces differ. Defaults to the service name.
557
+ */
558
+ namespace?: string;
559
+ };
560
+
604
561
  /**
605
562
  * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
606
563
  * `kind` is `media_type` when the body is present but its media type is not one the operation
@@ -627,6 +584,7 @@ type RejectedRequest = {
627
584
  };
628
585
  /** One handled request, as the structured log sees it. */
629
586
  type RequestLog = {
587
+ upstream?: boolean;
630
588
  service: string;
631
589
  namespace: string;
632
590
  operationId: string | undefined;
@@ -761,8 +719,6 @@ type CredentialRegistry = {
761
719
  }[];
762
720
  };
763
721
 
764
- type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
765
-
766
722
  /**
767
723
  * A point-in-time copy of everything a service namespace holds.
768
724
  *
@@ -785,6 +741,50 @@ type NamespaceSnapshot = {
785
741
  }[];
786
742
  };
787
743
 
744
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
745
+ type Stored<T> = {
746
+ seq: number;
747
+ value: T;
748
+ };
749
+ type ListRecordsOptions<T> = {
750
+ /** Keep only records passing the predicate. */
751
+ where?: (value: T, seq: number) => boolean;
752
+ /** Sort order; default newest first. */
753
+ order?: "newest" | "oldest";
754
+ };
755
+ /**
756
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
757
+ * sequence, never by id lexicographic order, so list semantics stay stable.
758
+ */
759
+ declare class Collection<T> {
760
+ private readonly sqlite;
761
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
762
+ readonly namespace: string;
763
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
764
+ readonly collectionName: string;
765
+ private readonly statements;
766
+ private prepare;
767
+ constructor(sqlite: SqliteClient$1,
768
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
769
+ namespace: string,
770
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
771
+ collectionName: string);
772
+ private bumpCollectionSeq;
773
+ nextSequence(): number;
774
+ get(id: string): T | undefined;
775
+ has(id: string): boolean;
776
+ /** Insert a new record, assigning it the next sequence number. */
777
+ insert(id: string, value: T): Stored<T>;
778
+ /** Replace an existing record's value, keeping its position. */
779
+ update(id: string, value: T): Stored<T> | undefined;
780
+ delete(id: string): boolean;
781
+ /** How many records the collection holds, without reading them. */
782
+ count(): number;
783
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
784
+ id: string;
785
+ }>;
786
+ }
787
+
788
788
  declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
789
789
  type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
790
790
  /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
@@ -815,6 +815,14 @@ type StateView = {
815
815
  collections: StateCollectionView[];
816
816
  };
817
817
 
818
+ /**
819
+ * What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
820
+ * which derives the base from the wall clock when the runtime is created.
821
+ */
822
+ type IdBase = number | string;
823
+
824
+ type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
825
+
818
826
  type WebhookEndpoint = {
819
827
  /** Stable id; generated when omitted. */
820
828
  id?: string;
package/dist/index.js CHANGED
@@ -6,8 +6,7 @@ import {
6
6
  document,
7
7
  operationIds,
8
8
  supportedOperationIds
9
- } from "./chunk-WBNRB3VS.js";
10
- import "./chunk-WJVNP2N6.js";
9
+ } from "./chunk-Q6K2CEQS.js";
11
10
  export {
12
11
  TURNSTILE_NAMESPACE,
13
12
  TURNSTILE_PRESETS,