@crvouga/mockingbird-service-microsoft 0.0.0-stage → 0.2.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,1878 @@
1
+ /*! Adapted from vercel-labs/emulate (Apache-2.0), modified for Mockingbird. See port.json, LICENSE_EMULATE and THIRD_PARTY_NOTICES.md. */
2
+ /*!
3
+ * This HTTP compatibility layer builds on Hono's API and design.
4
+ * https://github.com/honojs/hono
5
+ * Copyright (c) 2021 - present, Yusuke Wada and Hono contributors
6
+ * MIT license: see THIRD_PARTY_NOTICES.md in the repository and npm packages.
7
+ */
8
+ type BodyInit = ConstructorParameters<typeof Response>[0];
9
+ type HeadersInit = ConstructorParameters<typeof Headers>[0];
10
+ type FormDataEntryValue = string | File;
11
+ type ContentfulStatusCode = number;
12
+ type Next = () => Promise<void>;
13
+ type VariablesOf<E> = unknown extends E ? Record<string, any> : E extends {
14
+ Variables: infer V;
15
+ } ? V : Record<string, any>;
16
+ type HandlerResult = Response | void | Promise<Response | void>;
17
+ type Handler<E = unknown, P extends string = string> = (c: Context<E, P>, next: Next) => HandlerResult;
18
+ type ErrorHandler<E = unknown> = (err: unknown, c: Context<E>) => Response | Promise<Response>;
19
+ interface HttpOptions {
20
+ strictRoutes?: boolean;
21
+ strictJson?: boolean;
22
+ onError?: (error: unknown, request: Request) => void;
23
+ }
24
+ interface RouteInfo {
25
+ method: string;
26
+ path: string;
27
+ source?: string;
28
+ }
29
+ declare class HonoRequest<P extends string = string> {
30
+ private readonly params;
31
+ private readonly strictJson;
32
+ readonly raw: Request;
33
+ readonly url: string;
34
+ readonly method: string;
35
+ readonly path: string;
36
+ constructor(request: Request, params: Record<string, string>, strictJson?: boolean);
37
+ header(): Record<string, string>;
38
+ header(name: string): string | undefined;
39
+ query(name: string): string | undefined;
40
+ queries(name: string): string[] | undefined;
41
+ param(): Record<string, string>;
42
+ param(name: string): string;
43
+ json<T = any>(): Promise<T>;
44
+ text(): Promise<string>;
45
+ arrayBuffer(): Promise<ArrayBuffer>;
46
+ parseBody(): Promise<Record<string, FormDataEntryValue | FormDataEntryValue[]>>;
47
+ }
48
+ declare class Context<E = unknown, P extends string = string> {
49
+ private readonly notFoundHandler;
50
+ readonly req: HonoRequest<P>;
51
+ private readonly vars;
52
+ private readonly responseHeaders;
53
+ private readonly headerOperations;
54
+ private readonly appliedHeaders;
55
+ private responseStatus;
56
+ constructor(request: Request, params: Record<string, string>, notFoundHandler: (c: Context<E>) => Response | Promise<Response>, strictJson?: boolean);
57
+ get<K extends keyof VariablesOf<E> & string>(key: K): VariablesOf<E>[K] | undefined;
58
+ set<K extends keyof VariablesOf<E> & string>(key: K, value: VariablesOf<E>[K]): void;
59
+ header(name: string, value: string, options?: {
60
+ append?: boolean;
61
+ }): void;
62
+ status(status: number): void;
63
+ json(data: unknown, status?: ContentfulStatusCode, headers?: HeadersInit): Response;
64
+ text(text: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response;
65
+ html(html: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response;
66
+ body(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response;
67
+ redirect(location: string, status?: ContentfulStatusCode): Response;
68
+ notFound(): Response | Promise<Response>;
69
+ finalize(response: Response): Response;
70
+ private response;
71
+ }
72
+ declare class Hono<E = unknown> {
73
+ private readonly options;
74
+ constructor(options?: HttpOptions);
75
+ get routeTable(): RouteInfo[];
76
+ matchedRoute(method: string, path: string): RouteInfo | undefined;
77
+ private readonly middleware;
78
+ private readonly routes;
79
+ private errorHandler;
80
+ private notFoundHandler;
81
+ use<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
82
+ use(...handlers: Handler<E>[]): this;
83
+ on<P extends string = string>(method: string, path: string, ...handlers: Handler<E, P>[]): this;
84
+ get<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
85
+ post<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
86
+ put<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
87
+ patch<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
88
+ delete<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;
89
+ onError(handler: ErrorHandler<E>): this;
90
+ notFound(handler: (c: Context<E>) => Response | Promise<Response>): this;
91
+ request(input: string | Request, init?: RequestInit): Promise<Response>;
92
+ fetch: (request: Request) => Promise<Response>;
93
+ private match;
94
+ private dispatch;
95
+ }
96
+
97
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
98
+ type SqliteValue$3 = null | number | bigint | string | Uint8Array | boolean;
99
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
100
+ type SqliteRunResult$3 = {
101
+ changes: number;
102
+ lastInsertRowid: number | bigint;
103
+ };
104
+ /**
105
+ * Prepared statement bound to a {@link SqliteClient}.
106
+ *
107
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
108
+ */
109
+ interface SqliteStatement$3 {
110
+ run(...params: SqliteValue$3[]): SqliteRunResult$3;
111
+ all<T = Record<string, unknown>>(...params: SqliteValue$3[]): T[];
112
+ get<T = Record<string, unknown>>(...params: SqliteValue$3[]): T | undefined;
113
+ }
114
+ /**
115
+ * Sync SQLite client port owned by Mockingbird.
116
+ *
117
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
118
+ * `bun:sqlite` instances all work when they expose this surface.
119
+ */
120
+ interface SqliteClient$3 {
121
+ exec(sql: string): void;
122
+ prepare(sql: string): SqliteStatement$3;
123
+ transaction<T>(fn: () => T): T;
124
+ }
125
+
126
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
127
+ type Stored<T> = {
128
+ seq: number;
129
+ value: T;
130
+ };
131
+ type ListRecordsOptions<T> = {
132
+ /** Keep only records passing the predicate. */
133
+ where?: (value: T, seq: number) => boolean;
134
+ /** Sort order; default newest first. */
135
+ order?: "newest" | "oldest";
136
+ };
137
+ /**
138
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
139
+ * sequence, never by id lexicographic order, so list semantics stay stable.
140
+ */
141
+ declare class Collection$1<T> {
142
+ private readonly sqlite;
143
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
144
+ readonly namespace: string;
145
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
146
+ readonly collectionName: string;
147
+ constructor(sqlite: SqliteClient$3,
148
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
149
+ namespace: string,
150
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
151
+ collectionName: string);
152
+ private bumpCollectionSeq;
153
+ nextSequence(): number;
154
+ get(id: string): T | undefined;
155
+ has(id: string): boolean;
156
+ /** Insert a new record, assigning it the next sequence number. */
157
+ insert(id: string, value: T): Stored<T>;
158
+ /** Replace an existing record's value, keeping its position. */
159
+ update(id: string, value: T): Stored<T> | undefined;
160
+ delete(id: string): boolean;
161
+ /** How many records the collection holds, without reading them. */
162
+ count(): number;
163
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
164
+ id: string;
165
+ }>;
166
+ }
167
+
168
+ /** Options every provider constructor accepts. */
169
+ type APIOptions = {
170
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
171
+ sqlite?: SqliteClient$3;
172
+ /** Clock used for `created`-style fields. Default `Date.now`. */
173
+ now?: () => number;
174
+ /**
175
+ * Storage namespace for this instance's records. Instances sharing one SQLite
176
+ * client stay isolated when their namespaces differ. Defaults to the service name.
177
+ */
178
+ namespace?: string;
179
+ };
180
+
181
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
182
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
183
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
184
+ type SqliteRunResult$2 = {
185
+ changes: number;
186
+ lastInsertRowid: number | bigint;
187
+ };
188
+ /**
189
+ * Prepared statement bound to a {@link SqliteClient}.
190
+ *
191
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
192
+ */
193
+ interface SqliteStatement$2 {
194
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
195
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
196
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
197
+ }
198
+ /**
199
+ * Sync SQLite client port owned by Mockingbird.
200
+ *
201
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
202
+ * `bun:sqlite` instances all work when they expose this surface.
203
+ */
204
+ interface SqliteClient$2 {
205
+ exec(sql: string): void;
206
+ prepare(sql: string): SqliteStatement$2;
207
+ transaction<T>(fn: () => T): T;
208
+ }
209
+
210
+ /*! Adapted from vercel-labs/emulate (Apache-2.0), modified for Mockingbird. See port.json, LICENSE_EMULATE and THIRD_PARTY_NOTICES.md. */
211
+
212
+ interface Entity {
213
+ id: number;
214
+ created_at: string;
215
+ updated_at: string;
216
+ }
217
+ type InsertInput<T extends Entity> = Omit<T, "id" | "created_at" | "updated_at"> & {
218
+ id?: number;
219
+ };
220
+ type FilterFn<T> = (item: T) => boolean;
221
+ type SortFn<T> = (a: T, b: T) => number;
222
+ interface QueryOptions<T> {
223
+ filter?: FilterFn<T>;
224
+ sort?: SortFn<T>;
225
+ page?: number;
226
+ per_page?: number;
227
+ }
228
+ interface PaginatedResult<T> {
229
+ items: T[];
230
+ total_count: number;
231
+ page: number;
232
+ per_page: number;
233
+ has_next: boolean;
234
+ has_prev: boolean;
235
+ }
236
+ /** Provider entities live in the same namespace and history as every native service. */
237
+ declare class Collection<T extends Entity> {
238
+ readonly store: Store;
239
+ readonly name: string;
240
+ readonly fieldNames: string[];
241
+ private readonly records;
242
+ constructor(store: Store, name: string, fields?: (keyof T)[]);
243
+ insert(data: InsertInput<T>): T;
244
+ get(id: number): T | undefined;
245
+ findBy(field: keyof T, value: T[keyof T] | string | number): T[];
246
+ findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined;
247
+ update(id: number, data: Partial<T>): T | undefined;
248
+ delete(id: number): boolean;
249
+ all(): T[];
250
+ count(filter?: FilterFn<T>): number;
251
+ clear(): void;
252
+ query(options?: QueryOptions<T>): PaginatedResult<T>;
253
+ }
254
+ declare class Store {
255
+ readonly sqlite: SqliteClient$2;
256
+ readonly namespace: string;
257
+ readonly now: () => number;
258
+ readonly meta: Collection$1<unknown>;
259
+ private readonly collections;
260
+ private readonly data;
261
+ constructor(sqlite?: SqliteClient$2, namespace?: string, now?: () => number);
262
+ isoNow(): string;
263
+ collection<T extends Entity>(name: string, fields?: (keyof T)[]): Collection<T>;
264
+ getData<V>(key: string): V | undefined;
265
+ setData<V>(key: string, value: V): void;
266
+ /** Drop request caches so checkout/reset and namespace selection always read SQLite. */
267
+ begin(): void;
268
+ flush(): void;
269
+ reset(): void;
270
+ }
271
+
272
+ interface WebhookSubscription {
273
+ id: number;
274
+ url: string;
275
+ events: string[];
276
+ active: boolean;
277
+ secret?: string;
278
+ owner: string;
279
+ repo?: string;
280
+ }
281
+ interface WebhookDelivery$1 {
282
+ id: number;
283
+ hook_id: number;
284
+ event: string;
285
+ action?: string;
286
+ payload: unknown;
287
+ status_code: number | null;
288
+ delivered_at: string;
289
+ duration: number | null;
290
+ success: boolean;
291
+ }
292
+ interface WebhookHeaderContext {
293
+ event: string;
294
+ action?: string;
295
+ body: string;
296
+ subscription: Readonly<WebhookSubscription>;
297
+ deliveryId: number;
298
+ }
299
+ type WebhookHeaderFactory = (context: WebhookHeaderContext) => Record<string, string>;
300
+ declare class WebhookDispatcher {
301
+ private readonly options;
302
+ private readonly records;
303
+ private readonly now;
304
+ private headerFactory;
305
+ constructor(options?: {
306
+ signal?: AbortSignal;
307
+ neutral?: boolean;
308
+ store?: Store;
309
+ });
310
+ private load;
311
+ private save;
312
+ setHeaderFactory(factory: WebhookHeaderFactory): void;
313
+ register(sub: Omit<WebhookSubscription, "id"> & {
314
+ id?: number;
315
+ }): WebhookSubscription;
316
+ unregister(id: number): boolean;
317
+ getSubscription(id: number): WebhookSubscription | undefined;
318
+ getSubscriptions(owner?: string, repo?: string): WebhookSubscription[];
319
+ updateSubscription(id: number, data: Partial<Pick<WebhookSubscription, "url" | "events" | "active" | "secret">>): WebhookSubscription | undefined;
320
+ dispatch(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): Promise<void>;
321
+ getDeliveries(hookId?: number): WebhookDelivery$1[];
322
+ clear(): void;
323
+ }
324
+
325
+ interface AuthUser {
326
+ login: string;
327
+ id: number;
328
+ scopes: string[];
329
+ installation?: AuthInstallation;
330
+ }
331
+ interface AuthApp {
332
+ appId: number;
333
+ slug: string;
334
+ name: string;
335
+ }
336
+ interface AuthInstallation {
337
+ installationId: number;
338
+ appId: number;
339
+ accountId: number;
340
+ accountType: "User" | "Organization";
341
+ permissions: Record<string, string>;
342
+ repositoryIds: number[];
343
+ repositorySelection: "all" | "selected";
344
+ }
345
+ type TokenMap = Map<string, AuthUser>;
346
+ type AppEnv = {
347
+ Variables: {
348
+ authUser?: AuthUser;
349
+ authApp?: AuthApp;
350
+ authToken?: string;
351
+ authScopes?: string[];
352
+ docsUrl?: string;
353
+ };
354
+ };
355
+ interface AuthFallback {
356
+ login: string;
357
+ id: number;
358
+ scopes: string[];
359
+ }
360
+
361
+ /*! Adapted from vercel-labs/emulate (Apache-2.0), modified for Mockingbird. See port.json, LICENSE_EMULATE and THIRD_PARTY_NOTICES.md. */
362
+
363
+ interface ServicePlugin {
364
+ name: string;
365
+ register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void;
366
+ seed?(store: Store, baseUrl: string): void;
367
+ }
368
+
369
+ interface MicrosoftSeedConfig {
370
+ users?: Array<{
371
+ email: string;
372
+ name?: string;
373
+ given_name?: string;
374
+ family_name?: string;
375
+ tenant_id?: string;
376
+ }>;
377
+ oauth_clients?: Array<{
378
+ client_id: string;
379
+ client_secret: string;
380
+ name: string;
381
+ redirect_uris: string[];
382
+ tenant_id?: string;
383
+ }>;
384
+ }
385
+
386
+ type ProviderOptions = APIOptions & {
387
+ baseUrl?: string;
388
+ tokens?: Record<string, AuthUser>;
389
+ fallbackUser?: AuthFallback;
390
+ publicNamespace?: string;
391
+ adminPrefix?: string;
392
+ /**
393
+ * A seeded stream of `[0, 1)` that ids and tokens are minted from, so a run replays from
394
+ * its seed. Default: the platform's randomness.
395
+ */
396
+ random?: () => number;
397
+ };
398
+ /** Portable vendor API backed by the shared namespace; it owns no separate history or listener. */
399
+ declare class ProviderAPI {
400
+ readonly plugin: ServicePlugin;
401
+ readonly options: ProviderOptions;
402
+ readonly sqlite: SqliteClient$2;
403
+ readonly namespace: string;
404
+ readonly store: Store;
405
+ private activeApp;
406
+ private activeBaseUrl;
407
+ private readonly facade;
408
+ get app(): Hono<AppEnv>;
409
+ get routeTable(): RouteInfo[];
410
+ readonly tokenMap: Map<string, AuthUser>;
411
+ readonly webhooks: WebhookDispatcher;
412
+ private configured;
413
+ private tail;
414
+ constructor(plugin: ServicePlugin, options?: ProviderOptions);
415
+ private buildApp;
416
+ private initialize;
417
+ /** Persist seed configuration before the shared runtime captures its initial checkpoint. */
418
+ seed(config: unknown, apply: (store: Store, baseUrl: string, config: never) => void): void;
419
+ configureFixtures(config: unknown, apply: (store: Store, baseUrl: string, config: never) => void): void;
420
+ fetch(request: Request): Promise<Response>;
421
+ reset(): Promise<void>;
422
+ }
423
+
424
+ /**
425
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
426
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
427
+ */
428
+ type JsonPrimitive$1 = string | number | boolean | null;
429
+ type JsonValue$1 = JsonPrimitive$1 | JsonValue$1[] | {
430
+ [key: string]: JsonValue$1;
431
+ };
432
+ type ReferenceObject$1 = {
433
+ $ref: string;
434
+ description?: string;
435
+ summary?: string;
436
+ };
437
+ type SchemaType$1 = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
438
+ type SchemaObject$1 = {
439
+ $ref?: string;
440
+ type?: SchemaType$1 | SchemaType$1[];
441
+ title?: string;
442
+ description?: string;
443
+ format?: string;
444
+ enum?: JsonValue$1[];
445
+ const?: JsonValue$1;
446
+ default?: JsonValue$1;
447
+ example?: JsonValue$1;
448
+ examples?: JsonValue$1[];
449
+ nullable?: boolean;
450
+ deprecated?: boolean;
451
+ readOnly?: boolean;
452
+ writeOnly?: boolean;
453
+ minimum?: number;
454
+ maximum?: number;
455
+ exclusiveMinimum?: number;
456
+ exclusiveMaximum?: number;
457
+ multipleOf?: number;
458
+ minLength?: number;
459
+ maxLength?: number;
460
+ pattern?: string;
461
+ minItems?: number;
462
+ maxItems?: number;
463
+ uniqueItems?: boolean;
464
+ items?: SchemaObject$1;
465
+ prefixItems?: SchemaObject$1[];
466
+ minProperties?: number;
467
+ maxProperties?: number;
468
+ required?: string[];
469
+ properties?: Record<string, SchemaObject$1>;
470
+ additionalProperties?: boolean | SchemaObject$1;
471
+ propertyNames?: SchemaObject$1;
472
+ oneOf?: SchemaObject$1[];
473
+ anyOf?: SchemaObject$1[];
474
+ allOf?: SchemaObject$1[];
475
+ not?: SchemaObject$1;
476
+ discriminator?: {
477
+ propertyName: string;
478
+ mapping?: Record<string, string>;
479
+ };
480
+ [extension: `x-${string}`]: unknown;
481
+ };
482
+ type ParameterLocation$1 = "path" | "query" | "header" | "cookie";
483
+ type ParameterObject$1 = {
484
+ name: string;
485
+ in: ParameterLocation$1;
486
+ description?: string;
487
+ required?: boolean;
488
+ deprecated?: boolean;
489
+ style?: string;
490
+ explode?: boolean;
491
+ schema?: SchemaObject$1;
492
+ content?: Record<string, MediaTypeObject$1>;
493
+ example?: JsonValue$1;
494
+ [extension: `x-${string}`]: unknown;
495
+ };
496
+ type MediaTypeObject$1 = {
497
+ schema?: SchemaObject$1;
498
+ example?: JsonValue$1;
499
+ examples?: Record<string, unknown>;
500
+ encoding?: Record<string, unknown>;
501
+ [extension: `x-${string}`]: unknown;
502
+ };
503
+ type RequestBodyObject$1 = {
504
+ description?: string;
505
+ required?: boolean;
506
+ content: Record<string, MediaTypeObject$1>;
507
+ [extension: `x-${string}`]: unknown;
508
+ };
509
+ type HeaderObject$1 = {
510
+ description?: string;
511
+ required?: boolean;
512
+ schema?: SchemaObject$1;
513
+ [extension: `x-${string}`]: unknown;
514
+ };
515
+ type ResponseObject$1 = {
516
+ description: string;
517
+ headers?: Record<string, HeaderObject$1 | ReferenceObject$1>;
518
+ content?: Record<string, MediaTypeObject$1>;
519
+ [extension: `x-${string}`]: unknown;
520
+ };
521
+ type ResponsesObject$1 = Record<string, ResponseObject$1 | ReferenceObject$1>;
522
+ type SecurityRequirementObject$1 = Record<string, string[]>;
523
+ type OperationObject$1 = {
524
+ operationId?: string;
525
+ summary?: string;
526
+ description?: string;
527
+ tags?: string[];
528
+ deprecated?: boolean;
529
+ parameters?: Array<ParameterObject$1 | ReferenceObject$1>;
530
+ requestBody?: RequestBodyObject$1 | ReferenceObject$1;
531
+ responses: ResponsesObject$1;
532
+ security?: SecurityRequirementObject$1[];
533
+ [extension: `x-${string}`]: unknown;
534
+ };
535
+ declare const HTTP_METHODS$1: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
536
+ type HttpMethod$1 = (typeof HTTP_METHODS$1)[number];
537
+ type PathItemObject$1 = {
538
+ summary?: string;
539
+ description?: string;
540
+ parameters?: Array<ParameterObject$1 | ReferenceObject$1>;
541
+ [extension: `x-${string}`]: unknown;
542
+ } & Partial<Record<HttpMethod$1, OperationObject$1>>;
543
+ type SecuritySchemeObject$1 = {
544
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
545
+ description?: string;
546
+ name?: string;
547
+ in?: ParameterLocation$1;
548
+ scheme?: string;
549
+ bearerFormat?: string;
550
+ flows?: Record<string, unknown>;
551
+ openIdConnectUrl?: string;
552
+ [extension: `x-${string}`]: unknown;
553
+ };
554
+ type ComponentsObject$1 = {
555
+ schemas?: Record<string, SchemaObject$1>;
556
+ responses?: Record<string, ResponseObject$1>;
557
+ parameters?: Record<string, ParameterObject$1>;
558
+ requestBodies?: Record<string, RequestBodyObject$1>;
559
+ headers?: Record<string, HeaderObject$1>;
560
+ securitySchemes?: Record<string, SecuritySchemeObject$1>;
561
+ [extension: `x-${string}`]: unknown;
562
+ };
563
+ type ServerObject$1 = {
564
+ url: string;
565
+ description?: string;
566
+ variables?: Record<string, unknown>;
567
+ [extension: `x-${string}`]: unknown;
568
+ };
569
+ type InfoObject$1 = {
570
+ title: string;
571
+ version: string;
572
+ description?: string;
573
+ [extension: `x-${string}`]: unknown;
574
+ };
575
+ type OpenAPIDocument$1 = {
576
+ openapi: string;
577
+ info: InfoObject$1;
578
+ servers?: ServerObject$1[];
579
+ paths: Record<string, PathItemObject$1>;
580
+ components?: ComponentsObject$1;
581
+ security?: SecurityRequirementObject$1[];
582
+ tags?: Array<{
583
+ name: string;
584
+ description?: string;
585
+ }>;
586
+ [extension: `x-${string}`]: unknown;
587
+ };
588
+
589
+ declare const document: OpenAPIDocument$1;
590
+ declare const operationIds: readonly ["GET /.well-known/openid-configuration", "GET /:tenant/v2.0/.well-known/openid-configuration", "GET /discovery/v2.0/keys", "GET /oauth2/v2.0/authorize", "GET /oauth2/v2.0/logout", "GET /oidc/userinfo", "GET /v1.0/me", "GET /v1.0/users/:id", "POST /:tenant/oauth2/token", "POST /oauth2/v2.0/authorize/callback", "POST /oauth2/v2.0/revoke", "POST /oauth2/v2.0/token"];
591
+ declare const supportedOperationIds: readonly ["GET /.well-known/openid-configuration", "GET /:tenant/v2.0/.well-known/openid-configuration", "GET /discovery/v2.0/keys", "GET /oauth2/v2.0/authorize", "GET /oauth2/v2.0/logout", "GET /oidc/userinfo", "GET /v1.0/me", "GET /v1.0/users/:id", "POST /:tenant/oauth2/token", "POST /oauth2/v2.0/authorize/callback", "POST /oauth2/v2.0/revoke", "POST /oauth2/v2.0/token"];
592
+
593
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
594
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
595
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
596
+ type SqliteRunResult$1 = {
597
+ changes: number;
598
+ lastInsertRowid: number | bigint;
599
+ };
600
+ /**
601
+ * Prepared statement bound to a {@link SqliteClient}.
602
+ *
603
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
604
+ */
605
+ interface SqliteStatement$1 {
606
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
607
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
608
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
609
+ }
610
+ /**
611
+ * Sync SQLite client port owned by Mockingbird.
612
+ *
613
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
614
+ * `bun:sqlite` instances all work when they expose this surface.
615
+ */
616
+ interface SqliteClient$1 {
617
+ exec(sql: string): void;
618
+ prepare(sql: string): SqliteStatement$1;
619
+ transaction<T>(fn: () => T): T;
620
+ }
621
+
622
+ type MountedAPI = FetchAPI & {
623
+ readonly prefix: string;
624
+ GET: FetchHandler;
625
+ POST: FetchHandler;
626
+ PUT: FetchHandler;
627
+ PATCH: FetchHandler;
628
+ DELETE: FetchHandler;
629
+ HEAD: FetchHandler;
630
+ OPTIONS: FetchHandler;
631
+ };
632
+
633
+ /** A stable identifier for a point in a {@link Timeline}. */
634
+ type CheckpointId = string;
635
+ /** An immutable node in a timeline's checkpoint DAG. */
636
+ type Checkpoint<T> = Readonly<{
637
+ id: CheckpointId;
638
+ branch: string;
639
+ parent: CheckpointId | null;
640
+ /** Logical time supplied by the timeline's injected clock. */
641
+ at: number;
642
+ value: T;
643
+ }>;
644
+ type TimelineOptions = {
645
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
646
+ now?: () => number;
647
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
648
+ maxCheckpoints?: number;
649
+ /** Customize deterministic checkpoint IDs. */
650
+ id?: (sequence: number) => CheckpointId;
651
+ };
652
+ type CommitOptions = {
653
+ branch?: string;
654
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
655
+ parent?: CheckpointId | null;
656
+ };
657
+ type ForkOptions = {
658
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
659
+ from?: CheckpointId;
660
+ };
661
+ /**
662
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
663
+ * records, namespace images, or copy-on-write SQL engine snapshots.
664
+ *
665
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
666
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
667
+ * (the logical clock) is injected.
668
+ */
669
+ declare class Timeline<T> {
670
+ readonly maxCheckpoints: number;
671
+ private readonly now;
672
+ private readonly makeId;
673
+ private readonly nodes;
674
+ private readonly heads;
675
+ /** Unreferenced nodes in the exact order they became collectible. */
676
+ private readonly evictable;
677
+ /** Branch heads plus explicit retainers. Absent means zero. */
678
+ private readonly references;
679
+ private readonly explicitPins;
680
+ private sequence;
681
+ constructor(options?: TimelineOptions);
682
+ /** Capture a new immutable value and move `branch` to it. */
683
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
684
+ /** Create a branch pointer without copying its checkpoint value. */
685
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
686
+ /** Move a branch pointer to an existing checkpoint. */
687
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
688
+ get(id: CheckpointId): Checkpoint<T>;
689
+ head(branch?: string): Checkpoint<T> | undefined;
690
+ hasBranch(branch: string): boolean;
691
+ branches(): Readonly<Record<string, CheckpointId>>;
692
+ checkpoints(): readonly Checkpoint<T>[];
693
+ /** Number of retained checkpoints without allocating an array. */
694
+ get size(): number;
695
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
696
+ retain(id: CheckpointId): Checkpoint<T>;
697
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
698
+ release(id: CheckpointId): boolean;
699
+ deleteBranch(branch: string): boolean;
700
+ /**
701
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
702
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
703
+ * storage dependency, so a retained node remains usable after pruning.
704
+ */
705
+ gc(max?: number): CheckpointId[];
706
+ private collect;
707
+ private moveHead;
708
+ private addReference;
709
+ private removeReference;
710
+ private assertBranch;
711
+ }
712
+
713
+ /**
714
+ * Anything that can answer a Fetch `Request` with a `Response`.
715
+ *
716
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
717
+ * It is the only contract shared across the whole graph.
718
+ */
719
+ interface FetchAPI {
720
+ fetch(request: Request): Promise<Response>;
721
+ }
722
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
723
+ type FetchHandler = (request: Request) => Promise<Response>;
724
+
725
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
726
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
727
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
728
+ type SqliteRunResult = {
729
+ changes: number;
730
+ lastInsertRowid: number | bigint;
731
+ };
732
+ /**
733
+ * Prepared statement bound to a {@link SqliteClient}.
734
+ *
735
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
736
+ */
737
+ interface SqliteStatement {
738
+ run(...params: SqliteValue[]): SqliteRunResult;
739
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
740
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
741
+ }
742
+ /**
743
+ * Sync SQLite client port owned by Mockingbird.
744
+ *
745
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
746
+ * `bun:sqlite` instances all work when they expose this surface.
747
+ */
748
+ interface SqliteClient {
749
+ exec(sql: string): void;
750
+ prepare(sql: string): SqliteStatement;
751
+ transaction<T>(fn: () => T): T;
752
+ }
753
+
754
+ /**
755
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
756
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
757
+ */
758
+ type JsonPrimitive = string | number | boolean | null;
759
+ type JsonValue = JsonPrimitive | JsonValue[] | {
760
+ [key: string]: JsonValue;
761
+ };
762
+ type ReferenceObject = {
763
+ $ref: string;
764
+ description?: string;
765
+ summary?: string;
766
+ };
767
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
768
+ type SchemaObject = {
769
+ $ref?: string;
770
+ type?: SchemaType | SchemaType[];
771
+ title?: string;
772
+ description?: string;
773
+ format?: string;
774
+ enum?: JsonValue[];
775
+ const?: JsonValue;
776
+ default?: JsonValue;
777
+ example?: JsonValue;
778
+ examples?: JsonValue[];
779
+ nullable?: boolean;
780
+ deprecated?: boolean;
781
+ readOnly?: boolean;
782
+ writeOnly?: boolean;
783
+ minimum?: number;
784
+ maximum?: number;
785
+ exclusiveMinimum?: number;
786
+ exclusiveMaximum?: number;
787
+ multipleOf?: number;
788
+ minLength?: number;
789
+ maxLength?: number;
790
+ pattern?: string;
791
+ minItems?: number;
792
+ maxItems?: number;
793
+ uniqueItems?: boolean;
794
+ items?: SchemaObject;
795
+ prefixItems?: SchemaObject[];
796
+ minProperties?: number;
797
+ maxProperties?: number;
798
+ required?: string[];
799
+ properties?: Record<string, SchemaObject>;
800
+ additionalProperties?: boolean | SchemaObject;
801
+ propertyNames?: SchemaObject;
802
+ oneOf?: SchemaObject[];
803
+ anyOf?: SchemaObject[];
804
+ allOf?: SchemaObject[];
805
+ not?: SchemaObject;
806
+ discriminator?: {
807
+ propertyName: string;
808
+ mapping?: Record<string, string>;
809
+ };
810
+ [extension: `x-${string}`]: unknown;
811
+ };
812
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
813
+ type ParameterObject = {
814
+ name: string;
815
+ in: ParameterLocation;
816
+ description?: string;
817
+ required?: boolean;
818
+ deprecated?: boolean;
819
+ style?: string;
820
+ explode?: boolean;
821
+ schema?: SchemaObject;
822
+ content?: Record<string, MediaTypeObject>;
823
+ example?: JsonValue;
824
+ [extension: `x-${string}`]: unknown;
825
+ };
826
+ type MediaTypeObject = {
827
+ schema?: SchemaObject;
828
+ example?: JsonValue;
829
+ examples?: Record<string, unknown>;
830
+ encoding?: Record<string, unknown>;
831
+ [extension: `x-${string}`]: unknown;
832
+ };
833
+ type RequestBodyObject = {
834
+ description?: string;
835
+ required?: boolean;
836
+ content: Record<string, MediaTypeObject>;
837
+ [extension: `x-${string}`]: unknown;
838
+ };
839
+ type HeaderObject = {
840
+ description?: string;
841
+ required?: boolean;
842
+ schema?: SchemaObject;
843
+ [extension: `x-${string}`]: unknown;
844
+ };
845
+ type ResponseObject = {
846
+ description: string;
847
+ headers?: Record<string, HeaderObject | ReferenceObject>;
848
+ content?: Record<string, MediaTypeObject>;
849
+ [extension: `x-${string}`]: unknown;
850
+ };
851
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
852
+ type SecurityRequirementObject = Record<string, string[]>;
853
+ type OperationObject = {
854
+ operationId?: string;
855
+ summary?: string;
856
+ description?: string;
857
+ tags?: string[];
858
+ deprecated?: boolean;
859
+ parameters?: Array<ParameterObject | ReferenceObject>;
860
+ requestBody?: RequestBodyObject | ReferenceObject;
861
+ responses: ResponsesObject;
862
+ security?: SecurityRequirementObject[];
863
+ [extension: `x-${string}`]: unknown;
864
+ };
865
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
866
+ type HttpMethod = (typeof HTTP_METHODS)[number];
867
+ type PathItemObject = {
868
+ summary?: string;
869
+ description?: string;
870
+ parameters?: Array<ParameterObject | ReferenceObject>;
871
+ [extension: `x-${string}`]: unknown;
872
+ } & Partial<Record<HttpMethod, OperationObject>>;
873
+ type SecuritySchemeObject = {
874
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
875
+ description?: string;
876
+ name?: string;
877
+ in?: ParameterLocation;
878
+ scheme?: string;
879
+ bearerFormat?: string;
880
+ flows?: Record<string, unknown>;
881
+ openIdConnectUrl?: string;
882
+ [extension: `x-${string}`]: unknown;
883
+ };
884
+ type ComponentsObject = {
885
+ schemas?: Record<string, SchemaObject>;
886
+ responses?: Record<string, ResponseObject>;
887
+ parameters?: Record<string, ParameterObject>;
888
+ requestBodies?: Record<string, RequestBodyObject>;
889
+ headers?: Record<string, HeaderObject>;
890
+ securitySchemes?: Record<string, SecuritySchemeObject>;
891
+ [extension: `x-${string}`]: unknown;
892
+ };
893
+ type ServerObject = {
894
+ url: string;
895
+ description?: string;
896
+ variables?: Record<string, unknown>;
897
+ [extension: `x-${string}`]: unknown;
898
+ };
899
+ type InfoObject = {
900
+ title: string;
901
+ version: string;
902
+ description?: string;
903
+ [extension: `x-${string}`]: unknown;
904
+ };
905
+ type OpenAPIDocument = {
906
+ openapi: string;
907
+ info: InfoObject;
908
+ servers?: ServerObject[];
909
+ paths: Record<string, PathItemObject>;
910
+ components?: ComponentsObject;
911
+ security?: SecurityRequirementObject[];
912
+ tags?: Array<{
913
+ name: string;
914
+ description?: string;
915
+ }>;
916
+ [extension: `x-${string}`]: unknown;
917
+ };
918
+
919
+ /**
920
+ * The single source of time for a service.
921
+ *
922
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
923
+ * sleeping: appointment windows, result delays and expiries become reachable in
924
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
925
+ */
926
+ type ClockState = {
927
+ /** Current epoch milliseconds. */
928
+ now: number;
929
+ /** True while time does not advance on its own. */
930
+ frozen: boolean;
931
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
932
+ offsetMs: number;
933
+ };
934
+ type Clock = {
935
+ now(): number;
936
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
937
+ set(epochMs: number): void;
938
+ /** Move the clock forward, or back with a negative delta. */
939
+ advance(deltaMs: number): void;
940
+ /** Stop time at the current instant. */
941
+ freeze(): void;
942
+ /** Resume from the current instant. */
943
+ unfreeze(): void;
944
+ /** Drop back to the underlying source, live. */
945
+ reset(): void;
946
+ state(): ClockState;
947
+ };
948
+
949
+ /**
950
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
951
+ * request a percentage fault hits — is reproducible from a seed.
952
+ *
953
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
954
+ * than statistical quality.
955
+ */
956
+ type Rng = {
957
+ /** Next value in `[0, 1)`. */
958
+ next(): number;
959
+ /** Next integer in `[min, max]`. */
960
+ int(min: number, max: number): number;
961
+ /** Restart the stream from its seed. */
962
+ reset(): void;
963
+ /** Serializable engine state used by deterministic checkpoints. */
964
+ state(): number;
965
+ /** Restore a state previously returned by {@link state}. */
966
+ setState(state: number): void;
967
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
968
+ reseed(seed: number | string): void;
969
+ /** The seed the stream currently starts from. */
970
+ readonly seed: number;
971
+ };
972
+
973
+ /**
974
+ * A deliberate failure injected in front of an operation.
975
+ *
976
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
977
+ * quota error that only appears when a shared sandbox is full, the 429 that only
978
+ * appears under load, the 5xx that proves a retry path works.
979
+ *
980
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
981
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
982
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
983
+ */
984
+ type FaultRule = {
985
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
986
+ id: string;
987
+ /** Fault only this operation. Omit to match every operation. */
988
+ operationId?: string;
989
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
990
+ method?: string;
991
+ /** Fault only this exact path. */
992
+ path?: string;
993
+ /** Fault only paths starting with this prefix. Omit to match every path. */
994
+ pathPrefix?: string;
995
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
996
+ pathPattern?: string;
997
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
998
+ requestHeaders?: Record<string, string>;
999
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
1000
+ query?: Record<string, string>;
1001
+ /**
1002
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
1003
+ * an in-process caller usually wants, and what a parallel worker usually does not:
1004
+ * rules added through `POST /__admin/faults` default to the calling namespace.
1005
+ */
1006
+ namespace?: string;
1007
+ /** Let this many matching requests through first. */
1008
+ after?: number;
1009
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
1010
+ every?: number;
1011
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
1012
+ count?: number;
1013
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
1014
+ rate?: number;
1015
+ /**
1016
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
1017
+ * clock when the rule was added. Listed as epoch ms.
1018
+ */
1019
+ from?: Instant | Duration;
1020
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
1021
+ until?: Instant | Duration;
1022
+ /**
1023
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
1024
+ * truncates, or switches on an `effect`: the request then still reaches the service.
1025
+ */
1026
+ status?: number;
1027
+ /** Response body, serialized as JSON. A string is sent as-is. */
1028
+ body?: unknown;
1029
+ /** Response headers. */
1030
+ headers?: Record<string, string>;
1031
+ /** Hold the response back this long. Listed as `delayMs`. */
1032
+ delay?: Duration;
1033
+ /** `delay`, in milliseconds. */
1034
+ delayMs?: number;
1035
+ /** Alias of `delayMs`. */
1036
+ latencyMs?: number;
1037
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
1038
+ jitter?: Duration;
1039
+ jitterMs?: number;
1040
+ /**
1041
+ * Never answer: hold the request this long, then drop the connection. Listed as
1042
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
1043
+ */
1044
+ timeout?: Duration;
1045
+ timeoutMs?: number;
1046
+ /**
1047
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
1048
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
1049
+ */
1050
+ drop?: boolean;
1051
+ /**
1052
+ * Cut the response body off after this many bytes: the status and headers arrive, then
1053
+ * the connection dies mid-body.
1054
+ */
1055
+ truncate?: number;
1056
+ /**
1057
+ * A named service behaviour to switch on for the matching request instead of (or
1058
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
1059
+ * read it with `faultEffects(request)`.
1060
+ */
1061
+ effect?: string;
1062
+ /** Parameters for `effect`. */
1063
+ params?: Record<string, unknown>;
1064
+ /** The preset this rule was expanded from, if any. */
1065
+ fromPreset?: string;
1066
+ };
1067
+ /** A fault that fired for one request. */
1068
+ type FaultHit = {
1069
+ id: string;
1070
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
1071
+ response?: Response;
1072
+ drop?: boolean;
1073
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
1074
+ timeout?: boolean;
1075
+ /** Bytes of response body to let through before the connection dies. */
1076
+ truncate?: number;
1077
+ effect?: {
1078
+ name: string;
1079
+ params: Record<string, unknown>;
1080
+ };
1081
+ };
1082
+ /**
1083
+ * A named, documented fault a suite switches on by name
1084
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
1085
+ * webhook delivery fault.
1086
+ */
1087
+ type FaultPreset = {
1088
+ description: string;
1089
+ rules?: Omit<FaultRule, "id">[];
1090
+ webhook?: {
1091
+ mode: "duplicate" | "reorder" | "drop";
1092
+ count?: number;
1093
+ };
1094
+ };
1095
+ /** What a request looks like to the fault matcher. */
1096
+ type FaultCandidate = {
1097
+ operationId: string | undefined;
1098
+ method: string;
1099
+ path: string;
1100
+ namespace: string;
1101
+ /** Request headers and query, for rules that match on them. */
1102
+ headers?: Headers;
1103
+ query?: URLSearchParams;
1104
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
1105
+ now?: number;
1106
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
1107
+ wait?: (ms: number) => Promise<void>;
1108
+ };
1109
+ /** A stored rule and how often it was consulted. */
1110
+ type FaultListing = FaultRule & {
1111
+ /** Faults left before the rule retires. `null` when it has no `count`. */
1112
+ remaining: number | null;
1113
+ /** Times the rule faulted a request. */
1114
+ hits: number;
1115
+ /** Requests that matched the rule, faulted or not. */
1116
+ seen: number;
1117
+ };
1118
+ /** A namespace's own rules, with their counters, in the order they are tried. */
1119
+ type FaultSnapshot = {
1120
+ /**
1121
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
1122
+ * in the order means to a request and holds in any process.
1123
+ */
1124
+ rules: (FaultListing & {
1125
+ position?: number;
1126
+ })[];
1127
+ /** How many `fault_<n>` ids the namespace has handed out. */
1128
+ nextId?: number;
1129
+ };
1130
+ type FaultRegistry = {
1131
+ snapshot(namespace: string): FaultSnapshot;
1132
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
1133
+ add(rule: FaultRule): FaultRule;
1134
+ /** The next unused `fault_<n>` id in `namespace`. */
1135
+ nextId(namespace: string): string;
1136
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
1137
+ list(namespace?: string): FaultListing[];
1138
+ get(id: string, namespace?: string): FaultListing | undefined;
1139
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
1140
+ remove(id: string, namespace?: string): boolean;
1141
+ /** Remove every rule, or one namespace's own rules. */
1142
+ clear(namespace?: string): void;
1143
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
1144
+ restore(namespace: string, state: FaultSnapshot): void;
1145
+ /**
1146
+ * Every fault this request should get, in rule order, stopping at the first that answers
1147
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
1148
+ * each matching rule's remaining uses.
1149
+ */
1150
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
1151
+ /**
1152
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
1153
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
1154
+ */
1155
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
1156
+ };
1157
+
1158
+ /**
1159
+ * The admin controls every mock shares, as one document.
1160
+ *
1161
+ * The same shape is accepted in three places, and means the same thing in each:
1162
+ *
1163
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
1164
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
1165
+ * - over HTTP: `PUT /__admin/controls`
1166
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
1167
+ *
1168
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
1169
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
1170
+ */
1171
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
1172
+ type Duration = number | string;
1173
+ /** Epoch milliseconds, or an ISO-8601 string. */
1174
+ type Instant = number | string;
1175
+ type ClockControls = {
1176
+ /** Move the clock to this instant. */
1177
+ now?: Instant;
1178
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
1179
+ frozen?: boolean;
1180
+ /**
1181
+ * Step the clock forward by this much before every vendor request. With a frozen clock
1182
+ * each request still gets its own, reproducible timestamp.
1183
+ */
1184
+ autoAdvance?: Duration;
1185
+ };
1186
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
1187
+ type LatencyRuleInput = {
1188
+ delay?: Duration;
1189
+ jitter?: Duration;
1190
+ };
1191
+ type LatencyControls = LatencyRuleInput & {
1192
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
1193
+ operations?: Record<string, Duration | LatencyRuleInput>;
1194
+ };
1195
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
1196
+ type FaultInput = (Omit<FaultRule, "id"> & {
1197
+ id?: string;
1198
+ }) | ({
1199
+ preset: string;
1200
+ } & Partial<FaultRule>);
1201
+ /** Identifies a {@link SnapshotDocument}. */
1202
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
1203
+ /**
1204
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
1205
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
1206
+ * `records` are required, so a hand-written seed file is a valid snapshot.
1207
+ */
1208
+ type SnapshotDocument = {
1209
+ format: typeof SNAPSHOT_FORMAT;
1210
+ /** The service that wrote it. A snapshot is rejected by any other service. */
1211
+ service?: string;
1212
+ /**
1213
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
1214
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
1215
+ */
1216
+ records: {
1217
+ collection: string;
1218
+ id: string;
1219
+ seq?: number;
1220
+ value?: unknown;
1221
+ raw?: string;
1222
+ }[];
1223
+ /** Id counters, so the next generated id continues where the snapshot left off. */
1224
+ sequences?: {
1225
+ name: string;
1226
+ kind: string;
1227
+ value: number;
1228
+ }[];
1229
+ clock?: {
1230
+ now: number;
1231
+ frozen: boolean;
1232
+ autoAdvanceMs?: number;
1233
+ };
1234
+ seed?: number | string;
1235
+ /** Positions of the seeded random streams. */
1236
+ rng?: {
1237
+ state: number;
1238
+ faults?: number;
1239
+ latency?: number;
1240
+ };
1241
+ faults?: unknown;
1242
+ latency?: unknown;
1243
+ virtualTime?: boolean;
1244
+ };
1245
+ /** Controls for one namespace. */
1246
+ type NamespaceControls = {
1247
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
1248
+ seed?: number | string;
1249
+ clock?: ClockControls;
1250
+ /**
1251
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
1252
+ * wall clock: the request returns at once, the clock has moved, and the journal records
1253
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
1254
+ */
1255
+ virtualTime?: boolean;
1256
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
1257
+ latency?: Duration | LatencyControls;
1258
+ faults?: readonly FaultInput[];
1259
+ /** Start from this state instead of the service's own seed data. */
1260
+ snapshot?: SnapshotDocument;
1261
+ };
1262
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
1263
+ type MockControls = NamespaceControls & {
1264
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
1265
+ credentials?: Record<string, string>;
1266
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
1267
+ namespaces?: Record<string, NamespaceControls>;
1268
+ };
1269
+ /** A latency rule in milliseconds. */
1270
+ type LatencyRule = {
1271
+ delayMs: number;
1272
+ jitterMs: number;
1273
+ };
1274
+ /** Baseline latency for a namespace, normalized. */
1275
+ type LatencyState = LatencyRule & {
1276
+ operations: Record<string, LatencyRule>;
1277
+ };
1278
+ /** What {@link controlHeaders} turns into request headers. */
1279
+ type ControlHeaderInput = {
1280
+ namespace?: string;
1281
+ adminKey?: string;
1282
+ branch?: string;
1283
+ at?: string;
1284
+ reset?: boolean;
1285
+ restore?: string;
1286
+ seed?: number | string;
1287
+ time?: Instant | Date;
1288
+ advance?: Duration;
1289
+ virtualTime?: boolean;
1290
+ delay?: Duration;
1291
+ timeout?: Duration;
1292
+ /** A status, `"drop"`, a preset name, or a fault rule. */
1293
+ fault?: number | string | Record<string, unknown>;
1294
+ snapshot?: string;
1295
+ };
1296
+
1297
+ /**
1298
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
1299
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
1300
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
1301
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
1302
+ */
1303
+ type BodyIssue = {
1304
+ path: string;
1305
+ message: string;
1306
+ kind?: "media_type" | "syntax" | "required" | "schema";
1307
+ };
1308
+
1309
+ /**
1310
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
1311
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
1312
+ */
1313
+ type RejectedRequest = {
1314
+ /** The raw `content-type` header, or `null` when the request sent none. */
1315
+ contentType: string | null;
1316
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
1317
+ bodyBytes: number | null;
1318
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
1319
+ transferEncoding: string | null;
1320
+ };
1321
+ /** One handled request, as the structured log sees it. */
1322
+ type RequestLog = {
1323
+ service: string;
1324
+ namespace: string;
1325
+ operationId: string | undefined;
1326
+ method: string;
1327
+ path: string;
1328
+ status: number;
1329
+ durationMs: number;
1330
+ /** True when the path matched no operation in the contract. */
1331
+ unmatched: boolean;
1332
+ /** Set when a fault rule produced the response. */
1333
+ faultId?: string;
1334
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
1335
+ delayMs?: number;
1336
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
1337
+ ids?: Record<string, string>;
1338
+ /** Set when the service created a resource the request referred to but that did not exist. */
1339
+ adopted?: boolean;
1340
+ /** Explicit durable acceptance, independent of response delivery. */
1341
+ accepted?: boolean;
1342
+ /** Checkpoint captured at explicit acceptance. */
1343
+ checkpoint?: string;
1344
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
1345
+ request?: RejectedRequest;
1346
+ /** The validation issues behind a rejection, when the service found any. */
1347
+ issues?: BodyIssue[];
1348
+ };
1349
+ type MetricsReport = {
1350
+ requests: number;
1351
+ /** Counts keyed `<operationId> <status>`. */
1352
+ byOperation: Record<string, number>;
1353
+ /**
1354
+ * Paths that matched no operation, most frequent first.
1355
+ *
1356
+ * This is the early-warning signal: a consumer calling something the mock does
1357
+ * not implement shows up here as a count, before it fails a suite as a 404.
1358
+ */
1359
+ unmatched: {
1360
+ method: string;
1361
+ path: string;
1362
+ count: number;
1363
+ }[];
1364
+ faults: number;
1365
+ totalDurationMs: number;
1366
+ };
1367
+ type Metrics = {
1368
+ record(entry: RequestLog): void;
1369
+ report(namespace?: string): MetricsReport;
1370
+ reset(namespace?: string): void;
1371
+ };
1372
+
1373
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
1374
+ type JournalEntry = RequestLog & {
1375
+ at: string;
1376
+ };
1377
+ type JournalQuery = {
1378
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
1379
+ namespace?: string;
1380
+ operationId?: string;
1381
+ /** Only this HTTP method, case-insensitive. */
1382
+ method?: string;
1383
+ /** Only this exact path. */
1384
+ path?: string;
1385
+ /** Only requests this fault rule answered or shaped. */
1386
+ faultId?: string;
1387
+ status?: number;
1388
+ /** Only entries at or after this instant (epoch ms). */
1389
+ since?: number;
1390
+ /** At most this many, the most recent kept. */
1391
+ limit?: number;
1392
+ };
1393
+ type Journal = {
1394
+ readonly size: number;
1395
+ record(entry: JournalEntry): void;
1396
+ list(query?: JournalQuery): JournalEntry[];
1397
+ /** Forget one namespace's entries, or every namespace's. */
1398
+ clear(namespace?: string): void;
1399
+ };
1400
+
1401
+ /**
1402
+ * Baseline response time, per namespace: how long every vendor request takes before any
1403
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
1404
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
1405
+ * fault hits.
1406
+ */
1407
+ type LatencyRegistry = {
1408
+ get(namespace: string): LatencyState;
1409
+ set(namespace: string, state: LatencyState): LatencyState;
1410
+ /** Remove one namespace's latency, or every namespace's. */
1411
+ clear(namespace?: string): void;
1412
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
1413
+ take(namespace: string, operationId: string | undefined): number;
1414
+ };
1415
+
1416
+ /** Clock state as the admin API reports it. */
1417
+ type ControlClock = ClockState & {
1418
+ /** `now`, as ISO-8601. */
1419
+ iso: string;
1420
+ /** Milliseconds the clock steps before every vendor request. */
1421
+ autoAdvanceMs: number;
1422
+ };
1423
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
1424
+ type ControlState = {
1425
+ namespace: string;
1426
+ seed: number | string;
1427
+ clock: ControlClock;
1428
+ virtualTime: boolean;
1429
+ latency: LatencyState;
1430
+ faults: FaultListing[];
1431
+ };
1432
+
1433
+ type AdminRequest = {
1434
+ request: Request;
1435
+ url: URL;
1436
+ /** `:param` segments of the matched route. */
1437
+ params: Record<string, string>;
1438
+ /** Namespace the request targets: `?namespace=`, then the header, then the default. */
1439
+ namespace: string;
1440
+ /** Parsed JSON body, or `undefined` when there is none. */
1441
+ body: unknown;
1442
+ };
1443
+ type AdminRoute = (request: AdminRequest) => Response | Promise<Response>;
1444
+ /**
1445
+ * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with
1446
+ * `:param` segments — e.g. `"POST /orders/:id/transition"`.
1447
+ */
1448
+ type AdminRoutes = Record<string, AdminRoute>;
1449
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
1450
+ type SnapshotInfo = {
1451
+ id: string;
1452
+ namespace: string;
1453
+ /** Stored rows in the snapshot. */
1454
+ records: number;
1455
+ /** The namespace clock when it was taken, epoch ms. */
1456
+ at: number;
1457
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
1458
+ portable: boolean;
1459
+ };
1460
+
1461
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
1462
+ type CredentialRegistry = {
1463
+ set(credential: string, namespace: string): void;
1464
+ get(credential: string): string | undefined;
1465
+ remove(credential: string): boolean;
1466
+ clear(): void;
1467
+ entries(): {
1468
+ credential: string;
1469
+ namespace: string;
1470
+ }[];
1471
+ };
1472
+
1473
+ /**
1474
+ * A point-in-time copy of everything a service namespace holds.
1475
+ *
1476
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
1477
+ * is generic: any service gets per-test rollback without knowing its own schema.
1478
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
1479
+ */
1480
+ type NamespaceSnapshot = {
1481
+ namespace: string;
1482
+ records: {
1483
+ collection: string;
1484
+ id: string;
1485
+ seq: number;
1486
+ value: string;
1487
+ }[];
1488
+ sequences: {
1489
+ name: string;
1490
+ kind: string;
1491
+ value: number;
1492
+ }[];
1493
+ };
1494
+
1495
+ declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
1496
+ type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
1497
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
1498
+ type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
1499
+ type StateField = {
1500
+ name: string;
1501
+ kind: StateFieldKind;
1502
+ optional: boolean;
1503
+ description?: string;
1504
+ /** One level of nested object fields. */
1505
+ fields?: StateField[];
1506
+ meta?: StateMeta;
1507
+ };
1508
+ /**
1509
+ * What a service knows about a collection before any row exists.
1510
+ * Stored rows still appear, including fields this declaration does not mention.
1511
+ */
1512
+ type StateDeclaration = {
1513
+ name: string;
1514
+ label?: string;
1515
+ description?: string;
1516
+ fields?: readonly StateField[];
1517
+ meta?: StateMeta;
1518
+ };
1519
+ type StateCollectionView = {
1520
+ name: string;
1521
+ label: string;
1522
+ description?: string;
1523
+ count: number;
1524
+ /** `mixed` when a declaration and stored rows both contribute fields. */
1525
+ source: "declared" | "inferred" | "mixed";
1526
+ fields: StateField[];
1527
+ meta?: StateMeta;
1528
+ };
1529
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
1530
+ type StateView = {
1531
+ namespace: string;
1532
+ storageNamespace: string;
1533
+ collections: StateCollectionView[];
1534
+ };
1535
+
1536
+ /**
1537
+ * A contribution the admin shell mounts beside the shared views.
1538
+ * `panel` is author-owned markup. `sql` turns on the built-in table explorer
1539
+ * and query runner, which call `GET /sql/tables` and `POST /sql/query`.
1540
+ * `route` presents an admin action with the shell's prebuilt form and response view.
1541
+ */
1542
+ type AdminExtension = {
1543
+ kind: "route";
1544
+ id: string;
1545
+ title: string;
1546
+ description?: string;
1547
+ /** An existing admin route, including its method and any path parameters. */
1548
+ route: string;
1549
+ /** Initial JSON body shown in the request form. */
1550
+ body?: unknown;
1551
+ } | {
1552
+ kind: "panel";
1553
+ id: string;
1554
+ title: string;
1555
+ description?: string;
1556
+ html: string;
1557
+ script?: string;
1558
+ } | {
1559
+ kind: "sql";
1560
+ /** DOM id suffix. Default `sql`. */
1561
+ id?: string;
1562
+ title?: string;
1563
+ description?: string;
1564
+ };
1565
+ /** A panel the default admin shell mounts after the shared views. */
1566
+ type AdminPanel = {
1567
+ /** DOM id suffix. Lowercase letters, digits, and hyphens. */
1568
+ id: string;
1569
+ title: string;
1570
+ description?: string;
1571
+ /** Markup placed inside the panel body. The service author owns it. */
1572
+ html: string;
1573
+ /**
1574
+ * Function body called as `(root, api) => void` once the shell has loaded.
1575
+ * `root` is the panel body. `api` is `{ get, send, namespace }` against `/__admin`.
1576
+ */
1577
+ script?: string;
1578
+ };
1579
+ /**
1580
+ * How a service customizes the admin UI without leaving the shared shell.
1581
+ * `panels` add views. `render` replaces the document and can call `defaultHtml()`
1582
+ * to wrap the shared shell instead of discarding it.
1583
+ */
1584
+ type AdminUi = {
1585
+ panels?: readonly AdminPanel[];
1586
+ /** First-class shell contributions. `sql` mounts the shared database explorer. */
1587
+ extensions?: readonly AdminExtension[];
1588
+ render?: (input: {
1589
+ service: string;
1590
+ defaultHtml: () => string;
1591
+ }) => string;
1592
+ };
1593
+
1594
+ type WebhookEndpoint = {
1595
+ /** Stable id; generated when omitted. */
1596
+ id?: string;
1597
+ url: string;
1598
+ secret?: string;
1599
+ /** Event types to deliver; omit or include `"*"` for every type. */
1600
+ events?: string[];
1601
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
1602
+ tags?: Record<string, string>;
1603
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
1604
+ signUrl?: string;
1605
+ headers?: Record<string, string>;
1606
+ };
1607
+ type WebhookMessage = {
1608
+ id: string;
1609
+ namespace: string;
1610
+ type: string;
1611
+ body: string;
1612
+ contentType: string;
1613
+ tags: Record<string, string>;
1614
+ headers?: Record<string, string>;
1615
+ /** Wall-clock ISO-8601 time of publication. */
1616
+ publishedAt: string;
1617
+ };
1618
+ type WebhookAttempt = {
1619
+ attempt: number;
1620
+ at: string;
1621
+ status: number | null;
1622
+ error: string | null;
1623
+ durationMs: number;
1624
+ /** Exact receiver response body, when one was returned. */
1625
+ responseBody?: string | null;
1626
+ };
1627
+ type WebhookDelivery = {
1628
+ id: string;
1629
+ messageId: string;
1630
+ namespace: string;
1631
+ type: string;
1632
+ endpointId: string;
1633
+ url: string;
1634
+ state: "pending" | "delivered" | "failed" | "dropped";
1635
+ attempts: WebhookAttempt[];
1636
+ };
1637
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
1638
+ type WebhookFault = {
1639
+ mode: "duplicate" | "reorder" | "drop";
1640
+ /** Messages affected; default 1. */
1641
+ count?: number;
1642
+ };
1643
+ type PublishInput = {
1644
+ namespace: string;
1645
+ type: string;
1646
+ /** Exact body; objects are JSON-encoded. */
1647
+ body: string | Record<string, unknown> | unknown[];
1648
+ /** Default `application/json`, or form-encoded when `form` is given. */
1649
+ contentType?: string;
1650
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
1651
+ form?: Record<string, string>;
1652
+ tags?: Record<string, string>;
1653
+ /** Message-specific delivery headers, captured as part of durable message state. */
1654
+ headers?: Record<string, string>;
1655
+ /** Message id; generated when omitted. */
1656
+ id?: string;
1657
+ };
1658
+ type WebhookHub = {
1659
+ pending(namespace: string): number;
1660
+ snapshot(namespace: string): unknown;
1661
+ restore(namespace: string, snapshot: unknown): void;
1662
+ publish(input: PublishInput): WebhookMessage;
1663
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
1664
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
1665
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
1666
+ endpoints(namespace: string): WebhookEndpoint[];
1667
+ messages(namespace?: string): WebhookMessage[];
1668
+ deliveries(namespace?: string): WebhookDelivery[];
1669
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
1670
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
1671
+ flush(): Promise<void>;
1672
+ /** Resolve once nothing is in flight. */
1673
+ idle(): Promise<void>;
1674
+ fault(namespace: string, fault: WebhookFault): void;
1675
+ clear(namespace?: string): void;
1676
+ };
1677
+
1678
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
1679
+ type ServiceInstance = FetchAPI & {
1680
+ reset(): Promise<void>;
1681
+ };
1682
+ /** Everything an instance shares with the runtime that owns it. */
1683
+ type InstanceContext = {
1684
+ /** Storage namespace for this instance's records. */
1685
+ namespace: string;
1686
+ /** The public namespace name a request selects it by. */
1687
+ adminPrefix: string;
1688
+ publicNamespace: string;
1689
+ sqlite: SqliteClient;
1690
+ clock: Clock;
1691
+ rng: Rng;
1692
+ };
1693
+ type RuntimeOptions<T extends ServiceInstance> = {
1694
+ /** Service name, e.g. `"junction"`. Also the default namespace's storage key. */
1695
+ name: string;
1696
+ /** Build the instance backing one namespace. Called once per namespace, on first use. */
1697
+ create: (context: InstanceContext) => T;
1698
+ /** The vendor contract, used to name each request's operation in logs, metrics and faults. */
1699
+ document?: OpenAPIDocument;
1700
+ /** Shared by every namespace. Defaults to a fresh `@crvouga/mockingbird-service-sqlite`. */
1701
+ sqlite?: SqliteClient;
1702
+ /** Defaults to a live clock over `Date.now`. */
1703
+ clock?: Clock;
1704
+ /** Seeds every random choice the runtime makes (fault rates, jitter). Default `0`. */
1705
+ seed?: number | string;
1706
+ /**
1707
+ * Admin controls to boot with: clock, latency, faults, a starting snapshot, credential
1708
+ * mappings and per-namespace overrides. `reset` returns a namespace to exactly this.
1709
+ */
1710
+ adminControls?: MockControls;
1711
+ /** Extra `GET /__admin/health` fields, such as the loaded corpus version. */
1712
+ describe?: () => Record<string, unknown>;
1713
+ /** Service-specific admin routes, given the runtime so they can reach any namespace. */
1714
+ admin?: (runtime: ServiceRuntime<T>) => AdminRoutes;
1715
+ /** Reserved tree for every internal HTTP endpoint, UI and namespace carrier. Default /__admin. */
1716
+ adminPrefix?: string;
1717
+ /**
1718
+ * A namespace's clock was moved — by `/__admin/clock`, a header, a restore, a reset, or a
1719
+ * wait spent in virtual time. Run whatever the service schedules by that clock, so what
1720
+ * came due is seen at once and not on the next request. Moving the base clock in process
1721
+ * (`runtime.clock`) is the caller's own doing and is not reported here.
1722
+ */
1723
+ onClockChange?: (namespace: string) => void;
1724
+ /** Invalidate transient handles before replacing an existing instance's stored state. */
1725
+ beforeRestore?: (instance: T) => void;
1726
+ /** Require this value in `x-mockingbird-admin-key` on admin data routes. */
1727
+ adminKey?: string;
1728
+ /** Structured request log sink, called once per request. */
1729
+ onLog?: (entry: RequestLog) => void;
1730
+ /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000; 0 turns it off. */
1731
+ journalSize?: number;
1732
+ /** Reported in the `x-mockingbird` header. Default: the bundled package's version. */
1733
+ version?: string;
1734
+ /**
1735
+ * The vendor credential a request carries (API key, token, account SID, AWS access key
1736
+ * id), for SDKs that cannot send `x-mockingbird-namespace`: a suite maps credentials to
1737
+ * namespaces with `PUT /__admin/credentials`. See `bearerToken`, `basicAuth`,
1738
+ * `sigV4AccessKeyId`.
1739
+ */
1740
+ credential?: (request: Request) => string | undefined;
1741
+ /**
1742
+ * Named faults, switched on with `POST /__admin/faults {"preset": "<name>"}`. They join the
1743
+ * standard presets every mock has; one with a standard name replaces it.
1744
+ */
1745
+ presets?: Record<string, FaultPreset>;
1746
+ /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */
1747
+ webhooks?: WebhookHub;
1748
+ /** Retained time-travel checkpoints per namespace. Default 1,000. */
1749
+ maxCheckpoints?: number;
1750
+ /** Injectable process IO used for observability and delays; logical service time uses `clock`. */
1751
+ io?: Partial<RuntimeIO>;
1752
+ /**
1753
+ * Collections the admin UI should show even before any row exists.
1754
+ * Stored collections are always included, whether or not they are declared.
1755
+ * A function may describe collections that depend on the live instance.
1756
+ */
1757
+ state?: readonly StateDeclaration[] | ((api: T, namespace: string) => readonly StateDeclaration[]);
1758
+ /**
1759
+ * Panels added to the default admin UI, or a function that replaces the document.
1760
+ * `render` receives `defaultHtml()` so a bespoke UI can wrap the shared shell.
1761
+ */
1762
+ adminUi?: AdminUi;
1763
+ };
1764
+ type RuntimeIO = {
1765
+ wallNow(): number;
1766
+ monotonicNow(): number;
1767
+ /** Wait on the wall clock. Rejects with the signal's reason when it aborts first. */
1768
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
1769
+ };
1770
+ type ServiceTimelineState = Readonly<{
1771
+ snapshot: NamespaceSnapshot;
1772
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
1773
+ clock: Readonly<ClockState & {
1774
+ pinned?: boolean;
1775
+ }>;
1776
+ rngState: number;
1777
+ }>;
1778
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1779
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1780
+ /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1781
+ stop?(): void;
1782
+ readonly name: string;
1783
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1784
+ mount(prefix: string): MountedAPI;
1785
+ readonly sqlite: SqliteClient;
1786
+ readonly clock: Clock;
1787
+ readonly faults: FaultRegistry;
1788
+ /** Baseline response time per namespace. */
1789
+ readonly latency: LatencyRegistry;
1790
+ readonly metrics: Metrics;
1791
+ readonly journal: Journal;
1792
+ readonly rng: Rng;
1793
+ readonly credentials: CredentialRegistry;
1794
+ /** The webhook hub, when the service has outbound webhooks. */
1795
+ readonly webhooks: WebhookHub | undefined;
1796
+ /**
1797
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
1798
+ * offset and a freeze of its own, so moving one never moves another.
1799
+ */
1800
+ namespaceClock(namespace?: string): Clock;
1801
+ namespaceOf(request: Request): string;
1802
+ /** Opaque in-process checkpoint including records, controls and webhook history. */
1803
+ fleetSnapshot(namespace: string): object;
1804
+ fleetRestore(snapshot: unknown, namespace: string): void;
1805
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1806
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1807
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
1808
+ instance(namespace?: string): T;
1809
+ /** Public names of every namespace created so far. */
1810
+ namespaces(): string[];
1811
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
1812
+ reset(namespace?: string): Promise<void>;
1813
+ /** Reset a namespace and forget it, releasing everything it held. */
1814
+ dropNamespace(namespace: string): Promise<void>;
1815
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
1816
+ controls(namespace?: string): ControlState & {
1817
+ snapshots: SnapshotInfo[];
1818
+ };
1819
+ /** Apply a control document to a namespace. A given key replaces that control. */
1820
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
1821
+ snapshots: SnapshotInfo[];
1822
+ };
1823
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
1824
+ readonly snapshots: {
1825
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
1826
+ create(options?: {
1827
+ name?: string;
1828
+ namespace?: string;
1829
+ }): SnapshotInfo;
1830
+ list(namespace?: string): SnapshotInfo[];
1831
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
1832
+ export(id: string, namespace?: string): SnapshotDocument;
1833
+ /** Store a document as a snapshot without restoring it. */
1834
+ import(document: SnapshotDocument, options?: {
1835
+ name?: string;
1836
+ namespace?: string;
1837
+ }): SnapshotInfo;
1838
+ restore(id: string, namespace?: string): void;
1839
+ delete(id: string, namespace?: string): boolean;
1840
+ };
1841
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
1842
+ headers(input: ControlHeaderInput): Record<string, string>;
1843
+ snapshot(namespace?: string): NamespaceSnapshot;
1844
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1845
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
1846
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1847
+ /** Create an isolated branch, optionally from a historical checkpoint. */
1848
+ branch(name: string, options?: {
1849
+ namespace?: string;
1850
+ at?: string;
1851
+ }): ServiceCheckpoint;
1852
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
1853
+ checkout(checkpoint: string, options?: {
1854
+ namespace?: string;
1855
+ branch?: string;
1856
+ }): void;
1857
+ /** Inspect the retained history for a namespace. */
1858
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
1859
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
1860
+ state(namespace?: string): StateView;
1861
+ };
1862
+
1863
+ type MicrosoftRuntimeOptions = Pick<RuntimeOptions<MicrosoftAPI>, "sqlite" | "clock" | "seed" | "adminPrefix" | "adminKey" | "adminControls" | "onLog" | "journalSize" | "maxCheckpoints"> & Pick<MicrosoftAPIOptions, "fixtures" | "baseUrl" | "tokens">;
1864
+ type MicrosoftRuntime = ServiceRuntime<MicrosoftAPI>;
1865
+ declare function createRuntime(options?: MicrosoftRuntimeOptions): MicrosoftRuntime;
1866
+
1867
+ declare const MICROSOFT_NAMESPACE = "microsoft";
1868
+ type MicrosoftAPIOptions = ProviderOptions & {
1869
+ fixtures?: MicrosoftSeedConfig;
1870
+ };
1871
+ declare class MicrosoftAPI extends ProviderAPI {
1872
+ private readonly fixtures;
1873
+ constructor(options?: MicrosoftAPIOptions);
1874
+ reset(): Promise<void>;
1875
+ }
1876
+
1877
+ export { MICROSOFT_NAMESPACE, MicrosoftAPI, createRuntime, document, operationIds, supportedOperationIds };
1878
+ export type { MicrosoftAPIOptions, MicrosoftRuntime, MicrosoftRuntimeOptions, SqliteClient$1 as SqliteClient };