@crvouga/mockingbird-service-formbricks 0.1.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.
@@ -0,0 +1,1200 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /**
14
+ * The single source of time for a service.
15
+ *
16
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
17
+ * sleeping: appointment windows, result delays and expiries become reachable in
18
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
19
+ */
20
+ type ClockState = {
21
+ /** Current epoch milliseconds. */
22
+ now: number;
23
+ /** True while time does not advance on its own. */
24
+ frozen: boolean;
25
+ /** Milliseconds this clock adds to its underlying source. */
26
+ offsetMs: number;
27
+ };
28
+ type Clock = {
29
+ now(): number;
30
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
31
+ set(epochMs: number): void;
32
+ /** Move the clock forward, or back with a negative delta. */
33
+ advance(deltaMs: number): void;
34
+ /** Stop time at the current instant. */
35
+ freeze(): void;
36
+ /** Resume from the current instant. */
37
+ unfreeze(): void;
38
+ /** Drop back to the underlying source, live. */
39
+ reset(): void;
40
+ state(): ClockState;
41
+ };
42
+
43
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
45
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
46
+ type SqliteRunResult$1 = {
47
+ changes: number;
48
+ lastInsertRowid: number | bigint;
49
+ };
50
+ /**
51
+ * Prepared statement bound to a {@link SqliteClient}.
52
+ *
53
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
+ */
55
+ interface SqliteStatement$1 {
56
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
57
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
58
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
59
+ }
60
+ /**
61
+ * Sync SQLite client port owned by Mockingbird.
62
+ *
63
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
+ * `bun:sqlite` instances all work when they expose this surface.
65
+ */
66
+ interface SqliteClient$1 {
67
+ exec(sql: string): void;
68
+ prepare(sql: string): SqliteStatement$1;
69
+ transaction<T>(fn: () => T): T;
70
+ }
71
+
72
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
+ type Stored<T> = {
74
+ seq: number;
75
+ value: T;
76
+ };
77
+ type ListRecordsOptions<T> = {
78
+ /** Keep only records passing the predicate. */
79
+ where?: (value: T, seq: number) => boolean;
80
+ /** Sort order; default newest first. */
81
+ order?: "newest" | "oldest";
82
+ };
83
+ /**
84
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
+ * sequence, never by id lexicographic order, so list semantics stay stable.
86
+ */
87
+ declare class Collection<T> {
88
+ private readonly sqlite;
89
+ private readonly namespace;
90
+ private readonly name;
91
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
92
+ private bumpCollectionSeq;
93
+ nextSequence(): number;
94
+ get(id: string): T | undefined;
95
+ has(id: string): boolean;
96
+ /** Insert a new record, assigning it the next sequence number. */
97
+ insert(id: string, value: T): Stored<T>;
98
+ /** Replace an existing record's value, keeping its position. */
99
+ update(id: string, value: T): Stored<T> | undefined;
100
+ delete(id: string): boolean;
101
+ /** How many records the collection holds, without reading them. */
102
+ count(): number;
103
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
104
+ id: string;
105
+ }>;
106
+ }
107
+
108
+ /**
109
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
110
+ * request a percentage fault hits — is reproducible from a seed.
111
+ *
112
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
113
+ * than statistical quality.
114
+ */
115
+ type Rng = {
116
+ /** Next value in `[0, 1)`. */
117
+ next(): number;
118
+ /** Next integer in `[min, max]`. */
119
+ int(min: number, max: number): number;
120
+ /** Restart the stream from its seed. */
121
+ reset(): void;
122
+ /** Serializable engine state used by deterministic checkpoints. */
123
+ state(): number;
124
+ /** Restore a state previously returned by {@link state}. */
125
+ setState(state: number): void;
126
+ seed: number;
127
+ };
128
+
129
+ /**
130
+ * A deliberate failure injected in front of an operation.
131
+ *
132
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
133
+ * quota error that only appears when a shared sandbox is full, the 429 that only
134
+ * appears under load, the 5xx that proves a retry path works.
135
+ */
136
+ type FaultRule = {
137
+ /** Stable id, so a suite can retire exactly the rule it added. */
138
+ id: string;
139
+ /** Fault only this operation. Omit to match every operation. */
140
+ operationId?: string;
141
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
142
+ method?: string;
143
+ /** Fault only paths starting with this prefix. Omit to match every path. */
144
+ pathPrefix?: string;
145
+ /**
146
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
147
+ * an in-process caller usually wants, and what a parallel worker usually does not:
148
+ * rules added through `POST /__admin/faults` default to the calling namespace.
149
+ */
150
+ namespace?: string;
151
+ /**
152
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
153
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
154
+ * the request then still reaches the service.
155
+ */
156
+ status?: number;
157
+ /** Response body, serialized as JSON. A string is sent as-is. */
158
+ body?: unknown;
159
+ headers?: Record<string, string>;
160
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
161
+ count?: number;
162
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
163
+ rate?: number;
164
+ /** Hold the response back this long, to exercise timeouts. */
165
+ delayMs?: number;
166
+ /** Alias of `delayMs`. */
167
+ latencyMs?: number;
168
+ /**
169
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
170
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
171
+ */
172
+ drop?: boolean;
173
+ /**
174
+ * A named service behaviour to switch on for the matching request instead of (or
175
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
176
+ * read it with `faultEffects(request)`.
177
+ */
178
+ effect?: string;
179
+ /** Parameters for `effect`. */
180
+ params?: Record<string, unknown>;
181
+ /** From the preset this rule was expanded from, if any. */
182
+ preset?: string;
183
+ };
184
+ /** A fault that fired for one request. */
185
+ type FaultHit = {
186
+ id: string;
187
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
188
+ response?: Response;
189
+ drop?: boolean;
190
+ effect?: {
191
+ name: string;
192
+ params: Record<string, unknown>;
193
+ };
194
+ };
195
+ /**
196
+ * A named, documented fault a suite switches on by name
197
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
198
+ * webhook delivery fault.
199
+ */
200
+ type FaultPreset = {
201
+ description: string;
202
+ rules?: Omit<FaultRule, "id">[];
203
+ webhook?: {
204
+ mode: "duplicate" | "reorder" | "drop";
205
+ count?: number;
206
+ };
207
+ };
208
+ /** What a request looks like to the fault matcher. */
209
+ type FaultCandidate = {
210
+ operationId: string | undefined;
211
+ method: string;
212
+ path: string;
213
+ namespace: string;
214
+ };
215
+ type FaultRegistry = {
216
+ add(rule: FaultRule): FaultRule;
217
+ list(): (FaultRule & {
218
+ remaining: number | null;
219
+ hits: number;
220
+ })[];
221
+ remove(id: string): boolean;
222
+ clear(): void;
223
+ /**
224
+ * Every fault this request should get, in rule order, stopping at the first that answers
225
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
226
+ * each matching rule's remaining uses.
227
+ */
228
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
229
+ };
230
+
231
+ /** One handled request, as the structured log sees it. */
232
+ type RequestLog = {
233
+ service: string;
234
+ namespace: string;
235
+ operationId: string | undefined;
236
+ method: string;
237
+ path: string;
238
+ status: number;
239
+ durationMs: number;
240
+ /** True when the path matched no operation in the contract. */
241
+ unmatched: boolean;
242
+ /** Set when a fault rule produced the response. */
243
+ faultId?: string;
244
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
245
+ ids?: Record<string, string>;
246
+ /** Set when the service created a resource the request referred to but that did not exist. */
247
+ adopted?: boolean;
248
+ };
249
+ type MetricsReport = {
250
+ requests: number;
251
+ /** Counts keyed `<operationId> <status>`. */
252
+ byOperation: Record<string, number>;
253
+ /**
254
+ * Paths that matched no operation, most frequent first.
255
+ *
256
+ * This is the early-warning signal: a consumer calling something the mock does
257
+ * not implement shows up here as a count, before it fails a suite as a 404.
258
+ */
259
+ unmatched: {
260
+ method: string;
261
+ path: string;
262
+ count: number;
263
+ }[];
264
+ faults: number;
265
+ totalDurationMs: number;
266
+ };
267
+ type Metrics = {
268
+ record(entry: RequestLog): void;
269
+ report(): MetricsReport;
270
+ reset(): void;
271
+ };
272
+
273
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
274
+ type JournalEntry = RequestLog & {
275
+ at: string;
276
+ };
277
+ type JournalQuery = {
278
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
279
+ namespace?: string;
280
+ operationId?: string;
281
+ status?: number;
282
+ /** Only entries at or after this instant (epoch ms). */
283
+ since?: number;
284
+ /** At most this many, the most recent kept. */
285
+ limit?: number;
286
+ };
287
+ type Journal = {
288
+ readonly size: number;
289
+ record(entry: JournalEntry): void;
290
+ list(query?: JournalQuery): JournalEntry[];
291
+ /** Forget one namespace's entries, or every namespace's. */
292
+ clear(namespace?: string): void;
293
+ };
294
+
295
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
296
+ type CredentialRegistry = {
297
+ set(credential: string, namespace: string): void;
298
+ get(credential: string): string | undefined;
299
+ remove(credential: string): boolean;
300
+ clear(): void;
301
+ entries(): {
302
+ credential: string;
303
+ namespace: string;
304
+ }[];
305
+ };
306
+
307
+ type DecodedBody = {
308
+ kind: "empty";
309
+ } | {
310
+ kind: "json";
311
+ value: unknown;
312
+ } | {
313
+ kind: "form";
314
+ value: Record<string, unknown>;
315
+ } | {
316
+ kind: "text";
317
+ value: string;
318
+ } | {
319
+ kind: "bytes";
320
+ value: Uint8Array;
321
+ } | {
322
+ kind: "invalid";
323
+ mediaType: string;
324
+ text: string;
325
+ error: string;
326
+ };
327
+
328
+ /**
329
+ * Rails/PHP/Stripe-style bracket notation for `application/x-www-form-urlencoded` bodies and
330
+ * query strings:
331
+ *
332
+ * address[city]=Paris -> { address: { city: "Paris" } }
333
+ * items[0][name]=a -> { items: [{ name: "a" }] }
334
+ * tags[]=x&tags[]=y -> { tags: ["x", "y"] }
335
+ * metadata[k]=v -> { metadata: { k: "v" } }
336
+ *
337
+ * Decoding yields only strings, arrays and plain objects — coercion is the caller's concern,
338
+ * exactly like a real HTTP server.
339
+ */
340
+ type FormValue = string | FormValue[] | {
341
+ [key: string]: FormValue;
342
+ };
343
+ type FormObject = {
344
+ [key: string]: FormValue;
345
+ };
346
+
347
+ /**
348
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
349
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
350
+ */
351
+ type JsonPrimitive$1 = string | number | boolean | null;
352
+ type JsonValue$1 = JsonPrimitive$1 | JsonValue$1[] | {
353
+ [key: string]: JsonValue$1;
354
+ };
355
+ type ReferenceObject$1 = {
356
+ $ref: string;
357
+ description?: string;
358
+ summary?: string;
359
+ };
360
+ type SchemaType$1 = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
361
+ type SchemaObject$1 = {
362
+ $ref?: string;
363
+ type?: SchemaType$1 | SchemaType$1[];
364
+ title?: string;
365
+ description?: string;
366
+ format?: string;
367
+ enum?: JsonValue$1[];
368
+ const?: JsonValue$1;
369
+ default?: JsonValue$1;
370
+ example?: JsonValue$1;
371
+ examples?: JsonValue$1[];
372
+ nullable?: boolean;
373
+ deprecated?: boolean;
374
+ readOnly?: boolean;
375
+ writeOnly?: boolean;
376
+ minimum?: number;
377
+ maximum?: number;
378
+ exclusiveMinimum?: number;
379
+ exclusiveMaximum?: number;
380
+ multipleOf?: number;
381
+ minLength?: number;
382
+ maxLength?: number;
383
+ pattern?: string;
384
+ minItems?: number;
385
+ maxItems?: number;
386
+ uniqueItems?: boolean;
387
+ items?: SchemaObject$1;
388
+ prefixItems?: SchemaObject$1[];
389
+ minProperties?: number;
390
+ maxProperties?: number;
391
+ required?: string[];
392
+ properties?: Record<string, SchemaObject$1>;
393
+ additionalProperties?: boolean | SchemaObject$1;
394
+ propertyNames?: SchemaObject$1;
395
+ oneOf?: SchemaObject$1[];
396
+ anyOf?: SchemaObject$1[];
397
+ allOf?: SchemaObject$1[];
398
+ not?: SchemaObject$1;
399
+ discriminator?: {
400
+ propertyName: string;
401
+ mapping?: Record<string, string>;
402
+ };
403
+ [extension: `x-${string}`]: unknown;
404
+ };
405
+ type ParameterLocation$1 = "path" | "query" | "header" | "cookie";
406
+ type ParameterObject$1 = {
407
+ name: string;
408
+ in: ParameterLocation$1;
409
+ description?: string;
410
+ required?: boolean;
411
+ deprecated?: boolean;
412
+ style?: string;
413
+ explode?: boolean;
414
+ schema?: SchemaObject$1;
415
+ content?: Record<string, MediaTypeObject$1>;
416
+ example?: JsonValue$1;
417
+ [extension: `x-${string}`]: unknown;
418
+ };
419
+ type MediaTypeObject$1 = {
420
+ schema?: SchemaObject$1;
421
+ example?: JsonValue$1;
422
+ examples?: Record<string, unknown>;
423
+ encoding?: Record<string, unknown>;
424
+ [extension: `x-${string}`]: unknown;
425
+ };
426
+ type RequestBodyObject$1 = {
427
+ description?: string;
428
+ required?: boolean;
429
+ content: Record<string, MediaTypeObject$1>;
430
+ [extension: `x-${string}`]: unknown;
431
+ };
432
+ type HeaderObject$1 = {
433
+ description?: string;
434
+ required?: boolean;
435
+ schema?: SchemaObject$1;
436
+ [extension: `x-${string}`]: unknown;
437
+ };
438
+ type ResponseObject$1 = {
439
+ description: string;
440
+ headers?: Record<string, HeaderObject$1 | ReferenceObject$1>;
441
+ content?: Record<string, MediaTypeObject$1>;
442
+ [extension: `x-${string}`]: unknown;
443
+ };
444
+ type ResponsesObject$1 = Record<string, ResponseObject$1 | ReferenceObject$1>;
445
+ type SecurityRequirementObject$1 = Record<string, string[]>;
446
+ type OperationObject$1 = {
447
+ operationId?: string;
448
+ summary?: string;
449
+ description?: string;
450
+ tags?: string[];
451
+ deprecated?: boolean;
452
+ parameters?: Array<ParameterObject$1 | ReferenceObject$1>;
453
+ requestBody?: RequestBodyObject$1 | ReferenceObject$1;
454
+ responses: ResponsesObject$1;
455
+ security?: SecurityRequirementObject$1[];
456
+ [extension: `x-${string}`]: unknown;
457
+ };
458
+ declare const HTTP_METHODS$1: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
459
+ type HttpMethod$1 = (typeof HTTP_METHODS$1)[number];
460
+ type PathItemObject$1 = {
461
+ summary?: string;
462
+ description?: string;
463
+ parameters?: Array<ParameterObject$1 | ReferenceObject$1>;
464
+ [extension: `x-${string}`]: unknown;
465
+ } & Partial<Record<HttpMethod$1, OperationObject$1>>;
466
+ type SecuritySchemeObject$1 = {
467
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
468
+ description?: string;
469
+ name?: string;
470
+ in?: ParameterLocation$1;
471
+ scheme?: string;
472
+ bearerFormat?: string;
473
+ flows?: Record<string, unknown>;
474
+ openIdConnectUrl?: string;
475
+ [extension: `x-${string}`]: unknown;
476
+ };
477
+ type ComponentsObject$1 = {
478
+ schemas?: Record<string, SchemaObject$1>;
479
+ responses?: Record<string, ResponseObject$1>;
480
+ parameters?: Record<string, ParameterObject$1>;
481
+ requestBodies?: Record<string, RequestBodyObject$1>;
482
+ headers?: Record<string, HeaderObject$1>;
483
+ securitySchemes?: Record<string, SecuritySchemeObject$1>;
484
+ [extension: `x-${string}`]: unknown;
485
+ };
486
+ type ServerObject$1 = {
487
+ url: string;
488
+ description?: string;
489
+ variables?: Record<string, unknown>;
490
+ [extension: `x-${string}`]: unknown;
491
+ };
492
+ type InfoObject$1 = {
493
+ title: string;
494
+ version: string;
495
+ description?: string;
496
+ [extension: `x-${string}`]: unknown;
497
+ };
498
+ type OpenAPIDocument$1 = {
499
+ openapi: string;
500
+ info: InfoObject$1;
501
+ servers?: ServerObject$1[];
502
+ paths: Record<string, PathItemObject$1>;
503
+ components?: ComponentsObject$1;
504
+ security?: SecurityRequirementObject$1[];
505
+ tags?: Array<{
506
+ name: string;
507
+ description?: string;
508
+ }>;
509
+ [extension: `x-${string}`]: unknown;
510
+ };
511
+ /** One concrete HTTP operation discovered in a document. */
512
+ type Operation = {
513
+ operationId: string;
514
+ method: HttpMethod$1;
515
+ /** OpenAPI path template, e.g. `/v1/customers/{customer}`. */
516
+ path: string;
517
+ operation: OperationObject$1;
518
+ /** Path-level parameters merged with operation-level ones (operation wins), `$ref`s resolved. */
519
+ parameters: ParameterObject$1[];
520
+ requestBody: RequestBodyObject$1 | undefined;
521
+ responses: Record<string, ResponseObject$1>;
522
+ };
523
+
524
+ /**
525
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
526
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
527
+ */
528
+ declare class IdSequence {
529
+ private readonly sqlite;
530
+ private readonly namespace;
531
+ private readonly salt;
532
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
533
+ next(prefix: string, length?: number): string;
534
+ }
535
+
536
+ /** A stable identifier for a point in a {@link Timeline}. */
537
+ type CheckpointId = string;
538
+ /** An immutable node in a timeline's checkpoint DAG. */
539
+ type Checkpoint<T> = Readonly<{
540
+ id: CheckpointId;
541
+ branch: string;
542
+ parent: CheckpointId | null;
543
+ /** Logical time supplied by the timeline's injected clock. */
544
+ at: number;
545
+ value: T;
546
+ }>;
547
+ type TimelineOptions = {
548
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
549
+ now?: () => number;
550
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
551
+ maxCheckpoints?: number;
552
+ /** Customize deterministic checkpoint IDs. */
553
+ id?: (sequence: number) => CheckpointId;
554
+ };
555
+ type CommitOptions = {
556
+ branch?: string;
557
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
558
+ parent?: CheckpointId | null;
559
+ };
560
+ type ForkOptions = {
561
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
562
+ from?: CheckpointId;
563
+ };
564
+ /**
565
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
566
+ * records, namespace images, or copy-on-write SQL engine snapshots.
567
+ *
568
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
569
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
570
+ * (the logical clock) is injected.
571
+ */
572
+ declare class Timeline<T> {
573
+ readonly maxCheckpoints: number;
574
+ private readonly now;
575
+ private readonly makeId;
576
+ private readonly nodes;
577
+ private readonly heads;
578
+ /** Unreferenced nodes in the exact order they became collectible. */
579
+ private readonly evictable;
580
+ /** Branch heads plus explicit retainers. Absent means zero. */
581
+ private readonly references;
582
+ private readonly explicitPins;
583
+ private sequence;
584
+ constructor(options?: TimelineOptions);
585
+ /** Capture a new immutable value and move `branch` to it. */
586
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
587
+ /** Create a branch pointer without copying its checkpoint value. */
588
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
589
+ /** Move a branch pointer to an existing checkpoint. */
590
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
591
+ get(id: CheckpointId): Checkpoint<T>;
592
+ head(branch?: string): Checkpoint<T> | undefined;
593
+ hasBranch(branch: string): boolean;
594
+ branches(): Readonly<Record<string, CheckpointId>>;
595
+ checkpoints(): readonly Checkpoint<T>[];
596
+ /** Number of retained checkpoints without allocating an array. */
597
+ get size(): number;
598
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
599
+ retain(id: CheckpointId): Checkpoint<T>;
600
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
601
+ release(id: CheckpointId): boolean;
602
+ deleteBranch(branch: string): boolean;
603
+ /**
604
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
605
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
606
+ * storage dependency, so a retained node remains usable after pruning.
607
+ */
608
+ gc(max?: number): CheckpointId[];
609
+ private collect;
610
+ private moveHead;
611
+ private addReference;
612
+ private removeReference;
613
+ private assertBranch;
614
+ }
615
+
616
+ /**
617
+ * Anything that can answer a Fetch `Request` with a `Response`.
618
+ *
619
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
620
+ * It is the only contract shared across the whole graph.
621
+ */
622
+ interface FetchAPI {
623
+ fetch(request: Request): Promise<Response>;
624
+ }
625
+
626
+ /**
627
+ * A point-in-time copy of everything a service namespace holds.
628
+ *
629
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
630
+ * is generic: any service gets per-test rollback without knowing its own schema.
631
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
632
+ */
633
+ type NamespaceSnapshot = {
634
+ namespace: string;
635
+ records: {
636
+ collection: string;
637
+ id: string;
638
+ seq: number;
639
+ value: string;
640
+ }[];
641
+ sequences: {
642
+ name: string;
643
+ kind: string;
644
+ value: number;
645
+ }[];
646
+ };
647
+
648
+ type WebhookEndpoint = {
649
+ /** Stable id; generated when omitted. */
650
+ id?: string;
651
+ url: string;
652
+ secret?: string;
653
+ /** Event types to deliver; omit or include `"*"` for every type. */
654
+ events?: string[];
655
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
656
+ tags?: Record<string, string>;
657
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
658
+ signUrl?: string;
659
+ headers?: Record<string, string>;
660
+ };
661
+ type WebhookMessage = {
662
+ id: string;
663
+ namespace: string;
664
+ type: string;
665
+ body: string;
666
+ contentType: string;
667
+ tags: Record<string, string>;
668
+ headers?: Record<string, string>;
669
+ /** Wall-clock ISO-8601 time of publication. */
670
+ publishedAt: string;
671
+ };
672
+ type WebhookAttempt = {
673
+ attempt: number;
674
+ at: string;
675
+ status: number | null;
676
+ error: string | null;
677
+ durationMs: number;
678
+ /** Exact receiver response body, when one was returned. */
679
+ responseBody?: string | null;
680
+ };
681
+ type WebhookDelivery = {
682
+ id: string;
683
+ messageId: string;
684
+ namespace: string;
685
+ type: string;
686
+ endpointId: string;
687
+ url: string;
688
+ state: "pending" | "delivered" | "failed" | "dropped";
689
+ attempts: WebhookAttempt[];
690
+ };
691
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
692
+ type WebhookFault = {
693
+ mode: "duplicate" | "reorder" | "drop";
694
+ /** Messages affected; default 1. */
695
+ count?: number;
696
+ };
697
+ type PublishInput = {
698
+ namespace: string;
699
+ type: string;
700
+ /** Exact body; objects are JSON-encoded. */
701
+ body: string | Record<string, unknown> | unknown[];
702
+ /** Default `application/json`, or form-encoded when `form` is given. */
703
+ contentType?: string;
704
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
705
+ form?: Record<string, string>;
706
+ tags?: Record<string, string>;
707
+ /** Message-specific delivery headers, captured as part of durable message state. */
708
+ headers?: Record<string, string>;
709
+ /** Message id; generated when omitted. */
710
+ id?: string;
711
+ };
712
+ type WebhookHub = {
713
+ publish(input: PublishInput): WebhookMessage;
714
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
715
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
716
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
717
+ endpoints(namespace: string): WebhookEndpoint[];
718
+ messages(namespace?: string): WebhookMessage[];
719
+ deliveries(namespace?: string): WebhookDelivery[];
720
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
721
+ /** Run every pending retry (and release held reordered messages) now. */
722
+ flush(): Promise<void>;
723
+ /** Resolve once nothing is in flight. */
724
+ idle(): Promise<void>;
725
+ fault(namespace: string, fault: WebhookFault): void;
726
+ clear(namespace?: string): void;
727
+ };
728
+
729
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
730
+ type ServiceInstance = FetchAPI & {
731
+ reset(): Promise<void>;
732
+ };
733
+ type ServiceTimelineState = Readonly<{
734
+ snapshot: NamespaceSnapshot;
735
+ clock: Readonly<ReturnType<Clock["state"]>>;
736
+ rngState: number;
737
+ }>;
738
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
739
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
740
+ readonly name: string;
741
+ readonly sqlite: SqliteClient$1;
742
+ readonly clock: Clock;
743
+ readonly faults: FaultRegistry;
744
+ readonly metrics: Metrics;
745
+ readonly journal: Journal;
746
+ readonly rng: Rng;
747
+ readonly credentials: CredentialRegistry;
748
+ /** The webhook hub, when the service has outbound webhooks. */
749
+ readonly webhooks: WebhookHub | undefined;
750
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
751
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
752
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
753
+ instance(namespace?: string): T;
754
+ /** Public names of every namespace created so far. */
755
+ namespaces(): string[];
756
+ /** Reset one namespace, or every namespace with `"*"`. */
757
+ reset(namespace?: string): Promise<void>;
758
+ snapshot(namespace?: string): NamespaceSnapshot;
759
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
760
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
761
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
762
+ /** Create an isolated branch, optionally from a historical checkpoint. */
763
+ branch(name: string, options?: {
764
+ namespace?: string;
765
+ at?: string;
766
+ }): ServiceCheckpoint;
767
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
768
+ checkout(checkpoint: string, options?: {
769
+ namespace?: string;
770
+ branch?: string;
771
+ }): void;
772
+ /** Inspect the retained history for a namespace. */
773
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
774
+ };
775
+
776
+ /** Options every provider constructor accepts. */
777
+ type APIOptions = {
778
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
779
+ sqlite?: SqliteClient$1;
780
+ /** Clock used for `created`-style fields. Default `Date.now`. */
781
+ now?: () => number;
782
+ /**
783
+ * Storage namespace for this instance's records. Instances sharing one SQLite
784
+ * client stay isolated when their namespaces differ. Defaults to the service name.
785
+ */
786
+ namespace?: string;
787
+ };
788
+ type OperationContext = {
789
+ request: Request;
790
+ url: URL;
791
+ /** Path parameters. */
792
+ params: Record<string, string>;
793
+ /** Query string decoded with bracket notation (`created[gte]=1` -> `{ created: { gte: "1" } }`). */
794
+ query: FormObject;
795
+ body: DecodedBody;
796
+ /** Shared SQLite client for this service (already migrated). */
797
+ sqlite: SqliteClient$1;
798
+ /** Service namespace used for records / sequences. */
799
+ namespace: string;
800
+ operation: Operation;
801
+ /** The vendor contract the service was built from. */
802
+ document: OpenAPIDocument$1;
803
+ now: () => number;
804
+ };
805
+
806
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
807
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
808
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
809
+ type SqliteRunResult = {
810
+ changes: number;
811
+ lastInsertRowid: number | bigint;
812
+ };
813
+ /**
814
+ * Prepared statement bound to a {@link SqliteClient}.
815
+ *
816
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
817
+ */
818
+ interface SqliteStatement {
819
+ run(...params: SqliteValue[]): SqliteRunResult;
820
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
821
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
822
+ }
823
+ /**
824
+ * Sync SQLite client port owned by Mockingbird.
825
+ *
826
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
827
+ * `bun:sqlite` instances all work when they expose this surface.
828
+ */
829
+ interface SqliteClient {
830
+ exec(sql: string): void;
831
+ prepare(sql: string): SqliteStatement;
832
+ transaction<T>(fn: () => T): T;
833
+ }
834
+
835
+ /** A survey definition, passed through as Formbricks serves it (blocks, elements, logic, …). */
836
+ type Survey = Record<string, unknown> & {
837
+ id: string;
838
+ name: string;
839
+ type: string;
840
+ status: string;
841
+ /** `null` for the shared fixture surveys, which every configured environment serves. */
842
+ environmentId?: string | null;
843
+ };
844
+ /** One stored response, in Formbricks' `TResponse` shape. */
845
+ type ResponseRecord = {
846
+ id: string;
847
+ createdAt: string;
848
+ updatedAt: string;
849
+ surveyId: string;
850
+ environmentId: string;
851
+ displayId: string | null;
852
+ contact: {
853
+ id: string;
854
+ userId: string;
855
+ } | null;
856
+ contactAttributes: Record<string, string> | null;
857
+ finished: boolean;
858
+ endingId: string | null;
859
+ data: Record<string, unknown>;
860
+ variables: Record<string, unknown>;
861
+ ttc: Record<string, number>;
862
+ tags: unknown[];
863
+ meta: Record<string, unknown>;
864
+ singleUseId: string | null;
865
+ language: string | null;
866
+ };
867
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
868
+ type Settings = {
869
+ /** Environment ids that serve the shared fixture surveys. */
870
+ environments: string[];
871
+ /** Accepted management API keys; empty means any non-empty `x-api-key` works. */
872
+ apiKeys: string[];
873
+ /** The `webhookId` put in webhook bodies. */
874
+ webhookId: string;
875
+ /** Whether a `userId` on a response finds-or-creates a contact (the fork's behaviour). */
876
+ contactsEnabled: boolean;
877
+ };
878
+ /** Our member-app production and development Formbricks environments. */
879
+ declare const PRODUCTION_ENVIRONMENT_ID = "cmlhiza9j0009lj01my5c1g0q";
880
+ declare const DEVELOPMENT_ENVIRONMENT_ID = "cmlhiza9c0004lj01jbuhp0nz";
881
+ declare const DEFAULT_SETTINGS: Settings;
882
+ /**
883
+ * The committed clone of our production survey definitions
884
+ * (`packages/forms-fixtures/formbricks/prod-clone.json` in geviti-monorepo).
885
+ */
886
+ declare const PROD_CLONE_SURVEYS: readonly Survey[];
887
+ declare const PROD_CLONE_EXPORTED_AT: string;
888
+ declare class FormbricksState {
889
+ private readonly seed;
890
+ readonly surveys: Collection<Survey>;
891
+ readonly responses: Collection<ResponseRecord>;
892
+ readonly contacts: Collection<{
893
+ id: string;
894
+ environmentId: string;
895
+ userId: string;
896
+ }>;
897
+ readonly settings: Collection<Settings>;
898
+ readonly ids: IdSequence;
899
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
900
+ surveys: readonly Survey[];
901
+ settings: Partial<Settings>;
902
+ });
903
+ ensureSeeded(): void;
904
+ current(): Settings;
905
+ update(patch: Partial<Settings>): Settings;
906
+ /** Formbricks ids are cuid2: lower-case alphanumerics starting with a letter, 25 long. */
907
+ nextId(): string;
908
+ knownEnvironment(environmentId: string): boolean;
909
+ allSurveys(): Survey[];
910
+ /** Surveys an environment serves: its own, plus the shared fixture when it is configured. */
911
+ surveysOf(environmentId: string): Survey[];
912
+ /** Whether a survey belongs to an environment (the fork's `survey.environmentId` check). */
913
+ belongsTo(survey: Survey, environmentId: string): boolean;
914
+ /** The fork's find-or-create contact for a response `userId` (the member's email). */
915
+ contactFor(environmentId: string, userId: string): {
916
+ id: string;
917
+ userId: string;
918
+ };
919
+ }
920
+
921
+ /**
922
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
923
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
924
+ */
925
+ type JsonPrimitive = string | number | boolean | null;
926
+ type JsonValue = JsonPrimitive | JsonValue[] | {
927
+ [key: string]: JsonValue;
928
+ };
929
+ type ReferenceObject = {
930
+ $ref: string;
931
+ description?: string;
932
+ summary?: string;
933
+ };
934
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
935
+ type SchemaObject = {
936
+ $ref?: string;
937
+ type?: SchemaType | SchemaType[];
938
+ title?: string;
939
+ description?: string;
940
+ format?: string;
941
+ enum?: JsonValue[];
942
+ const?: JsonValue;
943
+ default?: JsonValue;
944
+ example?: JsonValue;
945
+ examples?: JsonValue[];
946
+ nullable?: boolean;
947
+ deprecated?: boolean;
948
+ readOnly?: boolean;
949
+ writeOnly?: boolean;
950
+ minimum?: number;
951
+ maximum?: number;
952
+ exclusiveMinimum?: number;
953
+ exclusiveMaximum?: number;
954
+ multipleOf?: number;
955
+ minLength?: number;
956
+ maxLength?: number;
957
+ pattern?: string;
958
+ minItems?: number;
959
+ maxItems?: number;
960
+ uniqueItems?: boolean;
961
+ items?: SchemaObject;
962
+ prefixItems?: SchemaObject[];
963
+ minProperties?: number;
964
+ maxProperties?: number;
965
+ required?: string[];
966
+ properties?: Record<string, SchemaObject>;
967
+ additionalProperties?: boolean | SchemaObject;
968
+ propertyNames?: SchemaObject;
969
+ oneOf?: SchemaObject[];
970
+ anyOf?: SchemaObject[];
971
+ allOf?: SchemaObject[];
972
+ not?: SchemaObject;
973
+ discriminator?: {
974
+ propertyName: string;
975
+ mapping?: Record<string, string>;
976
+ };
977
+ [extension: `x-${string}`]: unknown;
978
+ };
979
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
980
+ type ParameterObject = {
981
+ name: string;
982
+ in: ParameterLocation;
983
+ description?: string;
984
+ required?: boolean;
985
+ deprecated?: boolean;
986
+ style?: string;
987
+ explode?: boolean;
988
+ schema?: SchemaObject;
989
+ content?: Record<string, MediaTypeObject>;
990
+ example?: JsonValue;
991
+ [extension: `x-${string}`]: unknown;
992
+ };
993
+ type MediaTypeObject = {
994
+ schema?: SchemaObject;
995
+ example?: JsonValue;
996
+ examples?: Record<string, unknown>;
997
+ encoding?: Record<string, unknown>;
998
+ [extension: `x-${string}`]: unknown;
999
+ };
1000
+ type RequestBodyObject = {
1001
+ description?: string;
1002
+ required?: boolean;
1003
+ content: Record<string, MediaTypeObject>;
1004
+ [extension: `x-${string}`]: unknown;
1005
+ };
1006
+ type HeaderObject = {
1007
+ description?: string;
1008
+ required?: boolean;
1009
+ schema?: SchemaObject;
1010
+ [extension: `x-${string}`]: unknown;
1011
+ };
1012
+ type ResponseObject = {
1013
+ description: string;
1014
+ headers?: Record<string, HeaderObject | ReferenceObject>;
1015
+ content?: Record<string, MediaTypeObject>;
1016
+ [extension: `x-${string}`]: unknown;
1017
+ };
1018
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
1019
+ type SecurityRequirementObject = Record<string, string[]>;
1020
+ type OperationObject = {
1021
+ operationId?: string;
1022
+ summary?: string;
1023
+ description?: string;
1024
+ tags?: string[];
1025
+ deprecated?: boolean;
1026
+ parameters?: Array<ParameterObject | ReferenceObject>;
1027
+ requestBody?: RequestBodyObject | ReferenceObject;
1028
+ responses: ResponsesObject;
1029
+ security?: SecurityRequirementObject[];
1030
+ [extension: `x-${string}`]: unknown;
1031
+ };
1032
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
1033
+ type HttpMethod = (typeof HTTP_METHODS)[number];
1034
+ type PathItemObject = {
1035
+ summary?: string;
1036
+ description?: string;
1037
+ parameters?: Array<ParameterObject | ReferenceObject>;
1038
+ [extension: `x-${string}`]: unknown;
1039
+ } & Partial<Record<HttpMethod, OperationObject>>;
1040
+ type SecuritySchemeObject = {
1041
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
1042
+ description?: string;
1043
+ name?: string;
1044
+ in?: ParameterLocation;
1045
+ scheme?: string;
1046
+ bearerFormat?: string;
1047
+ flows?: Record<string, unknown>;
1048
+ openIdConnectUrl?: string;
1049
+ [extension: `x-${string}`]: unknown;
1050
+ };
1051
+ type ComponentsObject = {
1052
+ schemas?: Record<string, SchemaObject>;
1053
+ responses?: Record<string, ResponseObject>;
1054
+ parameters?: Record<string, ParameterObject>;
1055
+ requestBodies?: Record<string, RequestBodyObject>;
1056
+ headers?: Record<string, HeaderObject>;
1057
+ securitySchemes?: Record<string, SecuritySchemeObject>;
1058
+ [extension: `x-${string}`]: unknown;
1059
+ };
1060
+ type ServerObject = {
1061
+ url: string;
1062
+ description?: string;
1063
+ variables?: Record<string, unknown>;
1064
+ [extension: `x-${string}`]: unknown;
1065
+ };
1066
+ type InfoObject = {
1067
+ title: string;
1068
+ version: string;
1069
+ description?: string;
1070
+ [extension: `x-${string}`]: unknown;
1071
+ };
1072
+ type OpenAPIDocument = {
1073
+ openapi: string;
1074
+ info: InfoObject;
1075
+ servers?: ServerObject[];
1076
+ paths: Record<string, PathItemObject>;
1077
+ components?: ComponentsObject;
1078
+ security?: SecurityRequirementObject[];
1079
+ tags?: Array<{
1080
+ name: string;
1081
+ description?: string;
1082
+ }>;
1083
+ [extension: `x-${string}`]: unknown;
1084
+ };
1085
+
1086
+ declare const document: OpenAPIDocument;
1087
+ type OperationId = "GetEnvironmentState" | "CreateClientResponse" | "ListResponses" | "GetResponse" | "ListSurveys" | "CreateSurvey" | "GetSurvey" | "GetWidgetScript";
1088
+ type SupportedOperationId = "GetEnvironmentState" | "CreateClientResponse" | "ListResponses" | "GetResponse" | "ListSurveys" | "CreateSurvey" | "GetSurvey" | "GetWidgetScript";
1089
+ declare const operationIds: readonly ["GetEnvironmentState", "CreateClientResponse", "ListResponses", "GetResponse", "ListSurveys", "CreateSurvey", "GetSurvey", "GetWidgetScript"];
1090
+ declare const supportedOperationIds: readonly ["GetEnvironmentState", "CreateClientResponse", "ListResponses", "GetResponse", "ListSurveys", "CreateSurvey", "GetSurvey", "GetWidgetScript"];
1091
+
1092
+ /**
1093
+ * The fork's response validation (`modules/api/lib/validation.ts` → `validateBlockResponses`
1094
+ * in `packages/surveys/src/lib/validation/evaluator.ts`), trimmed to what our surveys use:
1095
+ * required elements, and the implicit email / url / phone rules of openText elements. When the
1096
+ * response is finished every element is checked (including ones logic would skip); when it is
1097
+ * not, only the elements present in `data`.
1098
+ */
1099
+
1100
+ /** `{<elementId>: [messages]}`, or `null` when the response passes. */
1101
+ declare const validateResponseData: (survey: Survey, data: Record<string, unknown>, finished: boolean) => Record<string, string[]> | null;
1102
+
1103
+ /** Where our backend receives the webhook (`onboarding-tasks.controller.ts`; `?token=` checked). */
1104
+ declare const WEBHOOK_PATH = "/onboarding-tasks/formbricks-webhook";
1105
+ /**
1106
+ * Every named Formbricks misbehaviour our consumers branch on, switched on with
1107
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it).
1108
+ */
1109
+ declare const FORMBRICKS_PRESETS: Record<string, FaultPreset>;
1110
+ type WebhookHubOptionsSubset = {
1111
+ retryDelaysMs?: readonly number[];
1112
+ fetch?: (request: Request) => Promise<Response>;
1113
+ };
1114
+ type FormbricksRuntimeOptions = {
1115
+ sqlite?: SqliteClient;
1116
+ clock?: Clock;
1117
+ seed?: number | string;
1118
+ adminKey?: string;
1119
+ onLog?: (entry: RequestLog) => void;
1120
+ surveys?: readonly Survey[];
1121
+ settings?: Partial<Settings>;
1122
+ /**
1123
+ * Where webhooks go: `url` carries our `?token=<FORMBRICKS_WEBHOOK_SECRET>`; `secret` (a
1124
+ * `whsec_…` Standard Webhooks key) signs `webhook-signature`; `events` defaults to
1125
+ * `["responseFinished"]` (add `"responseCreated"` for both).
1126
+ */
1127
+ webhooks?: Omit<WebhookEndpoint, "id"> & WebhookHubOptionsSubset;
1128
+ };
1129
+ type FormbricksRuntime = ServiceRuntime<FormbricksAPI> & {
1130
+ readonly webhooks: WebhookHub;
1131
+ };
1132
+ /**
1133
+ * The namespace carrier for the client API is the environment id in the path (the member app's
1134
+ * fetch cannot add headers); the management API's is its `x-api-key`.
1135
+ */
1136
+ declare const formbricksCredential: (request: Request) => string | undefined;
1137
+ /**
1138
+ * The Formbricks mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
1139
+ * namespaces by header, by `/ns/<name>` prefix on `FORMBRICKS_APP_URL`, or by environment id /
1140
+ * API key (`PUT /__admin/credentials {"credentials": {"<env id or key>": "<namespace>"}}`),
1141
+ * clock control, fault presets, and Standard-Webhooks-signed `responseFinished` webhooks.
1142
+ */
1143
+ declare const createRuntime: (options?: FormbricksRuntimeOptions) => FormbricksRuntime;
1144
+
1145
+ declare const FORMBRICKS_NAMESPACE = "formbricks";
1146
+ /** The response as the API (and the webhook) renders it: `TResponse`. */
1147
+ type ApiResponse = Omit<ResponseRecord, "environmentId">;
1148
+ /** The body Formbricks' pipeline posts to a webhook (`app/api/(internal)/pipeline/route.ts`). */
1149
+ type FormbricksWebhook = {
1150
+ webhookId: string;
1151
+ event: "responseCreated" | "responseFinished";
1152
+ data: ApiResponse & {
1153
+ survey: {
1154
+ title: string;
1155
+ type: string;
1156
+ status: string;
1157
+ createdAt: string | null;
1158
+ updatedAt: string | null;
1159
+ };
1160
+ };
1161
+ };
1162
+ type FormbricksAPIOptions = APIOptions & {
1163
+ /** Surveys every namespace starts with. Default: our production clone. */
1164
+ surveys?: readonly Survey[];
1165
+ settings?: Partial<Settings>;
1166
+ /** Called for every pipeline event; the runtime signs and delivers it. */
1167
+ onWebhook?: (event: FormbricksWebhook) => void;
1168
+ };
1169
+ type ErrorCode = "not_found" | "bad_request" | "internal_server_error" | "not_authenticated" | "forbidden" | "too_many_requests";
1170
+ /** The fork's error envelope (`app/lib/api/response.ts`), with its CORS/no-store headers. */
1171
+ declare const formbricksError: (status: number, code: ErrorCode, message: string, details?: Record<string, unknown>) => Response;
1172
+ /**
1173
+ * Stateful mock of Formbricks (our fork): environment state and response creation for the
1174
+ * client SDK / member app, the v1 management API, and the `responseFinished` webhook.
1175
+ */
1176
+ declare class FormbricksAPI implements FetchAPI$1 {
1177
+ readonly app: Hono;
1178
+ readonly sqlite: SqliteClient;
1179
+ readonly state: FormbricksState;
1180
+ private readonly service;
1181
+ private readonly now;
1182
+ private readonly onWebhook;
1183
+ constructor(options?: FormbricksAPIOptions);
1184
+ fetch(request: Request): Promise<Response>;
1185
+ reset(): Promise<void>;
1186
+ private iso;
1187
+ /** A survey as the API serves it (no internal `environmentId: null`). */
1188
+ private wireSurvey;
1189
+ render(record: ResponseRecord, context?: OperationContext): ApiResponse;
1190
+ private environmentState;
1191
+ private createResponse;
1192
+ /** Emit a pipeline event for a stored response (also used by `/__admin/responses/:id/finish`). */
1193
+ pipeline(event: FormbricksWebhook["event"], record: ResponseRecord, survey: Survey): void;
1194
+ private listResponses;
1195
+ private createSurvey;
1196
+ responses(): ApiResponse[];
1197
+ }
1198
+
1199
+ export { DEFAULT_SETTINGS, DEVELOPMENT_ENVIRONMENT_ID, FORMBRICKS_NAMESPACE, FORMBRICKS_PRESETS, FormbricksAPI, PRODUCTION_ENVIRONMENT_ID, PROD_CLONE_EXPORTED_AT, PROD_CLONE_SURVEYS, WEBHOOK_PATH, createRuntime, document, formbricksCredential, formbricksError, operationIds, supportedOperationIds, validateResponseData };
1200
+ export type { ApiResponse, FetchAPI$1 as FetchAPI, FormbricksAPIOptions, FormbricksRuntime, FormbricksRuntimeOptions, FormbricksWebhook, OperationId, ResponseRecord, Settings, SqliteClient, SupportedOperationId, Survey };