@fragno-dev/api-fragment 0.0.0-stage → 0.0.1

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.
Files changed (79) hide show
  1. package/LICENSE.md +16 -0
  2. package/README.md +249 -2
  3. package/dist/browser/client/client-3ZV9sw3i.js +2580 -0
  4. package/dist/browser/client/client-3ZV9sw3i.js.map +1 -0
  5. package/dist/browser/client/client-DPjmoaJQ.d.ts +711 -0
  6. package/dist/browser/client/client-DPjmoaJQ.d.ts.map +1 -0
  7. package/dist/browser/client/client.d.ts +1645 -0
  8. package/dist/browser/client/client.d.ts.map +1 -0
  9. package/dist/browser/client/client.js +2 -0
  10. package/dist/browser/client/react.d.ts +1665 -0
  11. package/dist/browser/client/react.d.ts.map +1 -0
  12. package/dist/browser/client/react.js +194 -0
  13. package/dist/browser/client/react.js.map +1 -0
  14. package/dist/browser/client/solid.d.ts +1668 -0
  15. package/dist/browser/client/solid.d.ts.map +1 -0
  16. package/dist/browser/client/solid.js +129 -0
  17. package/dist/browser/client/solid.js.map +1 -0
  18. package/dist/browser/client/svelte.d.ts +1668 -0
  19. package/dist/browser/client/svelte.d.ts.map +1 -0
  20. package/dist/browser/client/svelte.js +131 -0
  21. package/dist/browser/client/svelte.js.map +1 -0
  22. package/dist/browser/client/vanilla.d.ts +1695 -0
  23. package/dist/browser/client/vanilla.d.ts.map +1 -0
  24. package/dist/browser/client/vanilla.js +159 -0
  25. package/dist/browser/client/vanilla.js.map +1 -0
  26. package/dist/browser/client/vue.d.ts +1668 -0
  27. package/dist/browser/client/vue.d.ts.map +1 -0
  28. package/dist/browser/client/vue.js +127 -0
  29. package/dist/browser/client/vue.js.map +1 -0
  30. package/dist/browser/client-D4NnY-zV.d.ts +713 -0
  31. package/dist/browser/client-D4NnY-zV.d.ts.map +1 -0
  32. package/dist/browser/client-DQE0c7GI.d.ts +711 -0
  33. package/dist/browser/client-DQE0c7GI.d.ts.map +1 -0
  34. package/dist/browser/index.d.ts +3130 -0
  35. package/dist/browser/index.d.ts.map +1 -0
  36. package/dist/browser/index.js +2 -0
  37. package/dist/browser/src-BrYPVbAN.js +2404 -0
  38. package/dist/browser/src-BrYPVbAN.js.map +1 -0
  39. package/dist/browser/src-t-4wp9-f.js +2400 -0
  40. package/dist/browser/src-t-4wp9-f.js.map +1 -0
  41. package/dist/node/api-types.d.ts +731 -0
  42. package/dist/node/api-types.d.ts.map +1 -0
  43. package/dist/node/api-types.js +281 -0
  44. package/dist/node/api-types.js.map +1 -0
  45. package/dist/node/crypto.d.ts +6 -0
  46. package/dist/node/crypto.d.ts.map +1 -0
  47. package/dist/node/crypto.js +103 -0
  48. package/dist/node/crypto.js.map +1 -0
  49. package/dist/node/definition.d.ts +638 -0
  50. package/dist/node/definition.d.ts.map +1 -0
  51. package/dist/node/definition.js +315 -0
  52. package/dist/node/definition.js.map +1 -0
  53. package/dist/node/oauth.js +124 -0
  54. package/dist/node/oauth.js.map +1 -0
  55. package/dist/node/routes.d.ts +1585 -0
  56. package/dist/node/routes.d.ts.map +1 -0
  57. package/dist/node/routes.js +1100 -0
  58. package/dist/node/routes.js.map +1 -0
  59. package/dist/node/schema.d.ts +99 -0
  60. package/dist/node/schema.d.ts.map +1 -0
  61. package/dist/node/schema.js +16 -0
  62. package/dist/node/schema.js.map +1 -0
  63. package/dist/node/server.d.ts +1585 -0
  64. package/dist/node/server.d.ts.map +1 -0
  65. package/dist/node/server.js +12 -0
  66. package/dist/node/server.js.map +1 -0
  67. package/dist/node/services.d.ts +10 -0
  68. package/dist/node/services.d.ts.map +1 -0
  69. package/dist/node/services.js +304 -0
  70. package/dist/node/services.js.map +1 -0
  71. package/dist/node/webhooks/auth.d.ts +133 -0
  72. package/dist/node/webhooks/auth.d.ts.map +1 -0
  73. package/dist/node/webhooks/auth.js +268 -0
  74. package/dist/node/webhooks/auth.js.map +1 -0
  75. package/dist/node/webhooks/verification.d.ts +102 -0
  76. package/dist/node/webhooks/verification.d.ts.map +1 -0
  77. package/dist/node/webhooks/verification.js +119 -0
  78. package/dist/node/webhooks/verification.js.map +1 -0
  79. package/package.json +136 -3
@@ -0,0 +1,2404 @@
1
+ import { defineFragment, defineRoutes } from "@fragno-dev/core";
2
+ import "@fragno-dev/db";
3
+ import { z } from "zod";
4
+ import { column, idColumn, referenceColumn, schema } from "@fragno-dev/db/schema";
5
+ //#region ../fragno/dist/api/internal/path.js
6
+ /**
7
+ * Extract parameter names from a path pattern at runtime.
8
+ * Examples:
9
+ * - "/users/:id" => ["id"]
10
+ * - "/files/**" => ["**"]
11
+ * - "/files/**:rest" => ["rest"]
12
+ */
13
+ function extractPathParams(pathPattern) {
14
+ const segments = pathPattern.split("/").filter((s) => s.length > 0);
15
+ const names = [];
16
+ for (const segment of segments) {
17
+ if (segment.startsWith(":")) {
18
+ names.push(segment.slice(1));
19
+ continue;
20
+ }
21
+ if (segment === "**") {
22
+ names.push("**");
23
+ continue;
24
+ }
25
+ if (segment.startsWith("**:")) {
26
+ names.push(segment.slice(3));
27
+ continue;
28
+ }
29
+ }
30
+ return names;
31
+ }
32
+ /**
33
+ * Build a concrete path by replacing placeholders in a path pattern with values.
34
+ *
35
+ * Supports the same placeholder syntax as the matcher:
36
+ * - Named parameter ":name" is URL-encoded as a single segment
37
+ * - Anonymous wildcard "**" inserts the remainder as-is (slashes preserved)
38
+ * - Named wildcard "**:name" inserts the remainder from the named key
39
+ *
40
+ * Examples:
41
+ * - buildPath("/users/:id", { id: "123" }) => "/users/123"
42
+ * - buildPath("/files/**", { "**": "a/b" }) => "/files/a/b"
43
+ * - buildPath("/files/**:rest", { rest: "a/b" }) => "/files/a/b"
44
+ */
45
+ function buildPath(pathPattern, params) {
46
+ const patternSegments = pathPattern.split("/");
47
+ const builtSegments = [];
48
+ for (const segment of patternSegments) {
49
+ if (segment.length === 0) {
50
+ builtSegments.push("");
51
+ continue;
52
+ }
53
+ if (segment.startsWith(":")) {
54
+ const name = segment.slice(1);
55
+ const value = params[name];
56
+ if (value === void 0) throw new Error(`Missing value for path parameter :${name}`);
57
+ builtSegments.push(encodeURIComponent(value));
58
+ continue;
59
+ }
60
+ if (segment === "**") {
61
+ const value = params["**"];
62
+ if (value === void 0) throw new Error("Missing value for path wildcard **");
63
+ builtSegments.push(value);
64
+ continue;
65
+ }
66
+ if (segment.startsWith("**:")) {
67
+ const name = segment.slice(3);
68
+ const value = params[name];
69
+ if (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);
70
+ builtSegments.push(value);
71
+ continue;
72
+ }
73
+ builtSegments.push(segment);
74
+ }
75
+ return builtSegments.join("/");
76
+ }
77
+ //#endregion
78
+ //#region ../fragno/dist/api/request-body.js
79
+ const isBinaryRequestBody = (body) => body instanceof ReadableStream || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body);
80
+ const containsFileBody = (value) => {
81
+ if (value instanceof File || value instanceof Blob || value instanceof FormData) return true;
82
+ return typeof value === "object" && value !== null && Object.values(value).some((entry) => entry instanceof File || entry instanceof Blob || entry instanceof FormData);
83
+ };
84
+ const appendFormDataValue = (formData, key, value) => {
85
+ if (value instanceof File) formData.append(key, value, value.name);
86
+ else if (value instanceof Blob) formData.append(key, value);
87
+ else if (value !== void 0 && value !== null) formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
88
+ };
89
+ const prepareMultipartBody = (body) => {
90
+ if (body instanceof FormData) return body;
91
+ const formData = new FormData();
92
+ if (body instanceof File) {
93
+ formData.append("file", body, body.name);
94
+ return formData;
95
+ }
96
+ if (body instanceof Blob) {
97
+ formData.append("file", body);
98
+ return formData;
99
+ }
100
+ if (typeof body === "object" && body !== null) {
101
+ for (const [key, value] of Object.entries(body)) appendFormDataValue(formData, key, value);
102
+ return formData;
103
+ }
104
+ throw new TypeError("Multipart routes require FormData, File, Blob, or an object body.");
105
+ };
106
+ const prepareClientRequestBody = (body, contentType) => {
107
+ if (body === void 0) return {
108
+ body: void 0,
109
+ contentType: void 0
110
+ };
111
+ if (contentType === "application/octet-stream") {
112
+ if (!isBinaryRequestBody(body)) throw new TypeError("Octet-stream routes require Blob, ArrayBuffer, ArrayBufferView, or ReadableStream bodies.");
113
+ return {
114
+ body,
115
+ contentType
116
+ };
117
+ }
118
+ if (body instanceof FormData || body instanceof File || body instanceof Blob) return {
119
+ body: prepareMultipartBody(body),
120
+ contentType: null
121
+ };
122
+ if (containsFileBody(body)) return {
123
+ body: prepareMultipartBody(body),
124
+ contentType: null
125
+ };
126
+ return {
127
+ body: JSON.stringify(body),
128
+ contentType: "application/json"
129
+ };
130
+ };
131
+ const createRequestInitWithBody = (method, headers, body, options = {}) => {
132
+ const requestInit = {
133
+ ...options,
134
+ method,
135
+ headers,
136
+ body
137
+ };
138
+ if (body instanceof ReadableStream) requestInit.duplex = "half";
139
+ return requestInit;
140
+ };
141
+ //#endregion
142
+ //#region ../fragno/dist/api/internal/route.js
143
+ function getMountRoute(opts) {
144
+ const mountRoute = opts.mountRoute ?? `/api/${opts.name}`;
145
+ if (mountRoute.endsWith("/")) return mountRoute.slice(0, -1);
146
+ return mountRoute;
147
+ }
148
+ //#endregion
149
+ //#region ../fragno/dist/api/error.js
150
+ var FragnoApiError = class extends Error {
151
+ #status;
152
+ #code;
153
+ constructor({ message, code }, status) {
154
+ super(message);
155
+ this.name = "FragnoApiError";
156
+ this.#status = status;
157
+ this.#code = code;
158
+ }
159
+ get status() {
160
+ return this.#status;
161
+ }
162
+ get code() {
163
+ return this.#code;
164
+ }
165
+ toResponse() {
166
+ return Response.json({
167
+ message: this.message,
168
+ code: this.code
169
+ }, { status: this.status });
170
+ }
171
+ };
172
+ var FragnoApiValidationError = class extends FragnoApiError {
173
+ issues;
174
+ constructor(message, issues) {
175
+ super({
176
+ message,
177
+ code: "FRAGNO_VALIDATION_ERROR"
178
+ }, 400);
179
+ this.name = "FragnoApiValidationError";
180
+ this.issues = issues;
181
+ }
182
+ toResponse() {
183
+ return Response.json({
184
+ message: this.message,
185
+ issues: this.issues,
186
+ code: this.code
187
+ }, { status: this.status });
188
+ }
189
+ };
190
+ //#endregion
191
+ //#region ../fragno/dist/api/request-input-context.js
192
+ var RequestInputContext = class RequestInputContext {
193
+ #path;
194
+ #method;
195
+ #pathParams;
196
+ #searchParams;
197
+ #headers;
198
+ #body;
199
+ #request;
200
+ #parsedBody;
201
+ #inputSchema;
202
+ #shouldValidateInput;
203
+ constructor(config) {
204
+ this.#path = config.path;
205
+ this.#method = config.method;
206
+ this.#pathParams = config.pathParams;
207
+ this.#searchParams = config.searchParams;
208
+ this.#headers = config.headers;
209
+ this.#body = config.rawBody;
210
+ this.#request = config.request;
211
+ this.#parsedBody = config.parsedBody;
212
+ this.#inputSchema = config.inputSchema;
213
+ this.#shouldValidateInput = config.shouldValidateInput ?? true;
214
+ }
215
+ /**
216
+ * Create a RequestContext from a Request object for server-side handling
217
+ */
218
+ static async fromRequest(config) {
219
+ return new RequestInputContext({
220
+ method: config.method,
221
+ path: config.path,
222
+ pathParams: config.state.pathParams,
223
+ searchParams: config.state.searchParams,
224
+ headers: config.state.headers,
225
+ request: config.request,
226
+ parsedBody: config.state.body,
227
+ rawBody: config.rawBody,
228
+ inputSchema: config.inputSchema,
229
+ shouldValidateInput: config.shouldValidateInput
230
+ });
231
+ }
232
+ /**
233
+ * Create a RequestContext for server-side rendering contexts (no Request object)
234
+ */
235
+ static fromSSRContext(config) {
236
+ return new RequestInputContext({
237
+ method: config.method,
238
+ path: config.path,
239
+ pathParams: config.pathParams,
240
+ searchParams: config.searchParams ?? new URLSearchParams(),
241
+ headers: config.headers ?? new Headers(),
242
+ parsedBody: "body" in config ? config.body : void 0,
243
+ inputSchema: "inputSchema" in config ? config.inputSchema : void 0,
244
+ shouldValidateInput: false
245
+ });
246
+ }
247
+ /**
248
+ * The HTTP method as string (e.g., `GET`, `POST`)
249
+ */
250
+ get method() {
251
+ return this.#method;
252
+ }
253
+ /**
254
+ * The matched route path (e.g., `/users/:id`)
255
+ * @remarks `string`
256
+ */
257
+ get path() {
258
+ return this.#path;
259
+ }
260
+ /**
261
+ * Extracted path parameters as object (e.g., `{ id: '123' }`)
262
+ * @remarks `Record<string, string>`
263
+ */
264
+ get pathParams() {
265
+ return this.#pathParams;
266
+ }
267
+ /**
268
+ * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters
269
+ * @remarks `URLSearchParams`
270
+ */
271
+ get query() {
272
+ return this.#searchParams;
273
+ }
274
+ /**
275
+ * [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers
276
+ * @remarks `Headers`
277
+ */
278
+ get headers() {
279
+ return this.#headers;
280
+ }
281
+ get rawBody() {
282
+ return this.#body;
283
+ }
284
+ get request() {
285
+ return this.#request;
286
+ }
287
+ /**
288
+ * Access the request body as FormData.
289
+ *
290
+ * Use this method when handling file uploads or multipart form submissions.
291
+ * The request must have been sent with Content-Type: multipart/form-data.
292
+ *
293
+ * @throws Error if the request body is not FormData
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * defineRoute({
298
+ * method: "POST",
299
+ * path: "/upload",
300
+ * async handler(ctx, res) {
301
+ * const formData = ctx.formData();
302
+ * const file = formData.get("file") as File;
303
+ * const description = formData.get("description") as string;
304
+ * // ... process file
305
+ * }
306
+ * });
307
+ * ```
308
+ */
309
+ formData() {
310
+ if (!(this.#parsedBody instanceof FormData)) throw new Error("Request body is not FormData. Ensure the request was sent with Content-Type: multipart/form-data.");
311
+ return this.#parsedBody;
312
+ }
313
+ /**
314
+ * Check if the request body is FormData.
315
+ *
316
+ * Useful for routes that accept both JSON and FormData payloads.
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * defineRoute({
321
+ * method: "POST",
322
+ * path: "/upload",
323
+ * async handler(ctx, res) {
324
+ * if (ctx.isFormData()) {
325
+ * const formData = ctx.formData();
326
+ * // handle file upload
327
+ * } else {
328
+ * const json = await ctx.input.valid();
329
+ * // handle JSON payload
330
+ * }
331
+ * }
332
+ * });
333
+ * ```
334
+ */
335
+ isFormData() {
336
+ return this.#parsedBody instanceof FormData;
337
+ }
338
+ /**
339
+ * Access the request body as a ReadableStream (application/octet-stream).
340
+ *
341
+ * @throws Error if the request body is not a ReadableStream
342
+ */
343
+ bodyStream() {
344
+ if (!(this.#parsedBody instanceof ReadableStream)) throw new Error("Request body is not a ReadableStream. Ensure the request was sent with Content-Type: application/octet-stream.");
345
+ return this.#parsedBody;
346
+ }
347
+ /**
348
+ * Check if the request body is a ReadableStream.
349
+ */
350
+ isBodyStream() {
351
+ return this.#parsedBody instanceof ReadableStream;
352
+ }
353
+ /**
354
+ * Input validation context (only if inputSchema is defined)
355
+ * @remarks `InputContext`
356
+ */
357
+ get input() {
358
+ if (!this.#inputSchema) return;
359
+ return {
360
+ schema: this.#inputSchema,
361
+ valid: async () => {
362
+ if (!this.#shouldValidateInput) return this.#parsedBody;
363
+ return this.#validateInput();
364
+ }
365
+ };
366
+ }
367
+ async #validateInput() {
368
+ if (!this.#inputSchema) throw new Error("No input schema defined for this route");
369
+ if (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error("Schema validation is only supported for JSON data, not FormData or Blob");
370
+ if (this.#parsedBody instanceof ReadableStream) throw new Error("Schema validation is only supported for JSON data, not FormData, Blob, or ReadableStream");
371
+ const result = await this.#inputSchema["~standard"].validate(this.#parsedBody);
372
+ if (result.issues) throw new FragnoApiValidationError("Validation failed", result.issues);
373
+ return result.value;
374
+ }
375
+ };
376
+ //#endregion
377
+ //#region ../fragno/dist/api/internal/response-stream.js
378
+ var ResponseStream = class {
379
+ #writer;
380
+ #encoder;
381
+ #abortSubscribers = [];
382
+ #responseReadable;
383
+ #aborted = false;
384
+ #abortPromise;
385
+ #closed = false;
386
+ /**
387
+ * Whether the stream has been aborted.
388
+ */
389
+ get aborted() {
390
+ return this.#aborted;
391
+ }
392
+ /**
393
+ * Whether the stream has been closed normally.
394
+ */
395
+ get closed() {
396
+ return this.#closed;
397
+ }
398
+ /**
399
+ * The readable stream that the response is piped to.
400
+ */
401
+ get responseReadable() {
402
+ return this.#responseReadable;
403
+ }
404
+ constructor(writable, readable) {
405
+ this.#writer = writable.getWriter();
406
+ this.#encoder = new TextEncoder();
407
+ const reader = readable.getReader();
408
+ this.#abortSubscribers.push(async () => {
409
+ await reader.cancel();
410
+ });
411
+ this.#responseReadable = new ReadableStream({
412
+ async pull(controller) {
413
+ const { done, value } = await reader.read();
414
+ if (done) controller.close();
415
+ else controller.enqueue(value);
416
+ },
417
+ cancel: () => this.abort()
418
+ });
419
+ }
420
+ async writeRaw(input) {
421
+ try {
422
+ if (typeof input === "string") input = this.#encoder.encode(input);
423
+ await this.#writer.write(input);
424
+ } catch {}
425
+ }
426
+ write(input) {
427
+ return this.writeRaw(JSON.stringify(input) + "\n");
428
+ }
429
+ sleep(ms) {
430
+ return new Promise((resolve) => {
431
+ setTimeout(resolve, ms);
432
+ });
433
+ }
434
+ async close() {
435
+ try {
436
+ await this.#writer.close();
437
+ } catch {} finally {
438
+ this.#closed = true;
439
+ }
440
+ }
441
+ onAbort(listener) {
442
+ this.#abortSubscribers.push(listener);
443
+ }
444
+ /**
445
+ * Abort the stream.
446
+ * You can call this method when stream is aborted by external event.
447
+ */
448
+ abort() {
449
+ if (!this.#abortPromise) {
450
+ this.#aborted = true;
451
+ this.#abortPromise = Promise.allSettled(this.#abortSubscribers.map(async (subscriber) => subscriber())).then((results) => {
452
+ const errors = [];
453
+ for (const result of results) if (result.status === "rejected") errors.push(result.reason);
454
+ if (errors.length > 0) throw new AggregateError(errors, "Failed to abort response stream.");
455
+ });
456
+ }
457
+ return this.#abortPromise;
458
+ }
459
+ };
460
+ //#endregion
461
+ //#region ../fragno/dist/api/request-output-context.js
462
+ /**
463
+ * Utility function to merge headers from multiple sources.
464
+ * Later headers override earlier ones.
465
+ */
466
+ function mergeHeaders$1(...headerSources) {
467
+ const mergedHeaders = new Headers();
468
+ for (const headerSource of headerSources) {
469
+ if (!headerSource) continue;
470
+ if (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);
471
+ else if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);
472
+ else for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);
473
+ }
474
+ return mergedHeaders;
475
+ }
476
+ var OutputContext = class {
477
+ #runJsonStreamCallback;
478
+ constructor(options = {}) {
479
+ this.#runJsonStreamCallback = options.runJsonStreamCallback;
480
+ }
481
+ /**
482
+ * Creates an error response.
483
+ *
484
+ * Shortcut for `throw new FragnoApiError(...)`
485
+ */
486
+ error = ({ message, code }, initOrStatus, headers) => {
487
+ if (typeof initOrStatus === "undefined") return Response.json({
488
+ message,
489
+ code
490
+ }, {
491
+ status: 500,
492
+ headers
493
+ });
494
+ if (typeof initOrStatus === "number") return Response.json({
495
+ message,
496
+ code
497
+ }, {
498
+ status: initOrStatus,
499
+ headers
500
+ });
501
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
502
+ return Response.json({
503
+ message,
504
+ code
505
+ }, {
506
+ status: initOrStatus.status,
507
+ headers: mergedHeaders
508
+ });
509
+ };
510
+ empty = (initOrStatus, headers) => {
511
+ const defaultHeaders = {};
512
+ if (typeof initOrStatus === "undefined") {
513
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
514
+ return new Response(null, {
515
+ status: 201,
516
+ headers: mergedHeaders
517
+ });
518
+ }
519
+ if (typeof initOrStatus === "number") {
520
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
521
+ return new Response(null, {
522
+ status: initOrStatus,
523
+ headers: mergedHeaders
524
+ });
525
+ }
526
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, initOrStatus.headers, headers);
527
+ return new Response(null, {
528
+ status: initOrStatus.status,
529
+ headers: mergedHeaders
530
+ });
531
+ };
532
+ json = (object, initOrStatus, headers) => {
533
+ if (typeof initOrStatus === "undefined") return Response.json(object, {
534
+ status: 200,
535
+ headers
536
+ });
537
+ if (typeof initOrStatus === "number") return Response.json(object, {
538
+ status: initOrStatus,
539
+ headers
540
+ });
541
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
542
+ return Response.json(object, {
543
+ status: initOrStatus.status,
544
+ headers: mergedHeaders
545
+ });
546
+ };
547
+ jsonStream = (cb, { onError, headers } = {}) => {
548
+ const defaultHeaders = {
549
+ "content-type": "application/x-ndjson; charset=utf-8",
550
+ "transfer-encoding": "chunked",
551
+ "cache-control": "no-cache"
552
+ };
553
+ const { readable, writable } = new TransformStream();
554
+ const stream = new ResponseStream(writable, readable);
555
+ const runStreamCallback = async () => {
556
+ try {
557
+ await cb(stream);
558
+ } catch (e) {
559
+ if (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);
560
+ else console.error(e);
561
+ } finally {
562
+ await stream.close();
563
+ }
564
+ };
565
+ try {
566
+ Promise.resolve(this.#runJsonStreamCallback ? this.#runJsonStreamCallback(runStreamCallback) : runStreamCallback()).catch(async (error) => {
567
+ console.error(error);
568
+ await stream.close();
569
+ });
570
+ } catch (error) {
571
+ console.error(error);
572
+ stream.close();
573
+ }
574
+ return new Response(stream.responseReadable, {
575
+ status: 200,
576
+ headers: mergeHeaders$1(defaultHeaders, headers)
577
+ });
578
+ };
579
+ };
580
+ var RequestOutputContext = class extends OutputContext {
581
+ #outputSchema;
582
+ constructor(outputSchema, options) {
583
+ super(options);
584
+ this.#outputSchema = outputSchema;
585
+ }
586
+ };
587
+ //#endregion
588
+ //#region ../fragno/dist/api/route.js
589
+ /**
590
+ * Helper to resolve route factories into routes
591
+ * @internal
592
+ */
593
+ function resolveRouteFactories(context, routesOrFactories) {
594
+ const routes = [];
595
+ for (const item of routesOrFactories) if (typeof item === "function") {
596
+ const factoryRoutes = item(context);
597
+ routes.push(...factoryRoutes);
598
+ } else routes.push(item);
599
+ return routes;
600
+ }
601
+ //#endregion
602
+ //#region ../fragno/dist/util/content-type.js
603
+ /**
604
+ * Parses a content-type header string into its components
605
+ *
606
+ * @param contentType - The content-type header value to parse
607
+ * @returns A ParsedContentType object or null if the input is invalid
608
+ *
609
+ * @example
610
+ * ```ts
611
+ * const { type, subtype, mediaType, parameters }
612
+ * = parseContentType("application/json; charset=utf-8");
613
+ * console.assert(type === "application");
614
+ * console.assert(subtype === "json");
615
+ * console.assert(mediaType === "application/json");
616
+ * console.assert(parameters["charset"] === "utf-8");
617
+ */
618
+ function parseContentType(contentType) {
619
+ if (!contentType || typeof contentType !== "string") return null;
620
+ const trimmed = contentType.trim();
621
+ if (!trimmed) return null;
622
+ const parts = trimmed.split(";").map((part) => part.trim());
623
+ const mediaType = parts[0];
624
+ if (!mediaType) return null;
625
+ const typeParts = mediaType.split("/");
626
+ if (typeParts.length !== 2) return null;
627
+ const [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());
628
+ if (!type || !subtype) return null;
629
+ const parameters = {};
630
+ for (let i = 1; i < parts.length; i++) {
631
+ const param = parts[i];
632
+ const equalIndex = param.indexOf("=");
633
+ if (equalIndex > 0) {
634
+ const key = param.slice(0, equalIndex).trim().toLowerCase();
635
+ let value = param.slice(equalIndex + 1).trim();
636
+ if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
637
+ if (key) parameters[key] = value;
638
+ }
639
+ }
640
+ return {
641
+ type,
642
+ subtype,
643
+ mediaType: `${type}/${subtype}`,
644
+ parameters
645
+ };
646
+ }
647
+ //#endregion
648
+ //#region ../fragno/dist/util/nanostores.js
649
+ /**
650
+ * Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.
651
+ */
652
+ function unwrapAtom(value) {
653
+ if (value && typeof value === "object" && "get" in value && typeof value.get === "function") return value.get();
654
+ return value;
655
+ }
656
+ /**
657
+ * Normalizes an object where values can be plain values, Atoms, or Vue Refs.
658
+ * Returns a new object with all values normalized to plain values.
659
+ */
660
+ function unwrapObject(params) {
661
+ if (!params) return;
662
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));
663
+ }
664
+ function isReadableAtom(value) {
665
+ if (!value) return false;
666
+ if (typeof value !== "object" || value === null) return false;
667
+ if (!("get" in value) || typeof value.get !== "function") return false;
668
+ if (!("lc" in value) || typeof value.lc !== "number") return false;
669
+ if (!("notify" in value) || typeof value.notify !== "function") return false;
670
+ if (!("off" in value) || typeof value.off !== "function") return false;
671
+ if (!("subscribe" in value) || typeof value.subscribe !== "function") return false;
672
+ if (!("value" in value)) return false;
673
+ return true;
674
+ }
675
+ //#endregion
676
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/task/index.js
677
+ let tasks = 0;
678
+ let resolves = [];
679
+ function startTask() {
680
+ tasks += 1;
681
+ return () => {
682
+ tasks -= 1;
683
+ if (tasks === 0) {
684
+ let prevResolves = resolves;
685
+ resolves = [];
686
+ for (let i of prevResolves) i();
687
+ }
688
+ };
689
+ }
690
+ function task(cb) {
691
+ let endTask = startTask();
692
+ let promise = cb().finally(endTask);
693
+ promise.t = true;
694
+ return promise;
695
+ }
696
+ //#endregion
697
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js
698
+ const clean = Symbol("clean");
699
+ //#endregion
700
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js
701
+ let listenerQueue = [];
702
+ let lqIndex = 0;
703
+ const QUEUE_ITEMS_PER_LISTENER = 4;
704
+ const nanostoresGlobal = globalThis.nanostoresGlobal ||= { epoch: 0 };
705
+ const atom = /* @__NO_SIDE_EFFECTS__ */ (initialValue) => {
706
+ let listeners = [];
707
+ let $atom = {
708
+ get() {
709
+ if (!$atom.lc) $atom.listen(() => {})();
710
+ return $atom.value;
711
+ },
712
+ init: initialValue,
713
+ lc: 0,
714
+ listen(listener) {
715
+ $atom.lc = listeners.push(listener);
716
+ return () => {
717
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) if (listenerQueue[i] === listener) listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
718
+ else i += QUEUE_ITEMS_PER_LISTENER;
719
+ let index = listeners.indexOf(listener);
720
+ if (~index) {
721
+ listeners.splice(index, 1);
722
+ if (!--$atom.lc) $atom.off();
723
+ }
724
+ };
725
+ },
726
+ notify(oldValue, changedKey) {
727
+ nanostoresGlobal.epoch++;
728
+ let runListenerQueue = !listenerQueue.length;
729
+ for (let listener of listeners) listenerQueue.push(listener, $atom.value, oldValue, changedKey);
730
+ if (runListenerQueue) {
731
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
732
+ listenerQueue.length = 0;
733
+ }
734
+ },
735
+ off() {},
736
+ set(newValue) {
737
+ let oldValue = $atom.value;
738
+ if (oldValue !== newValue) {
739
+ $atom.value = newValue;
740
+ $atom.notify(oldValue);
741
+ }
742
+ },
743
+ subscribe(listener) {
744
+ let unbind = $atom.listen(listener);
745
+ listener($atom.value);
746
+ return unbind;
747
+ },
748
+ value: initialValue
749
+ };
750
+ $atom[clean] = () => {
751
+ listeners = [];
752
+ $atom.lc = 0;
753
+ $atom.off();
754
+ };
755
+ return $atom;
756
+ };
757
+ //#endregion
758
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js
759
+ const START = 0;
760
+ const STOP = 1;
761
+ const MOUNT = 5;
762
+ const UNMOUNT = 6;
763
+ const REVERT_MUTATION = 10;
764
+ let on = (object, listener, eventKey, mutateStore) => {
765
+ object.events = object.events || {};
766
+ if (!object.events[eventKey + REVERT_MUTATION]) object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
767
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
768
+ shared: {},
769
+ ...eventProps
770
+ });
771
+ });
772
+ object.events[eventKey] = object.events[eventKey] || [];
773
+ object.events[eventKey].push(listener);
774
+ return () => {
775
+ let currentListeners = object.events[eventKey];
776
+ let index = currentListeners.indexOf(listener);
777
+ currentListeners.splice(index, 1);
778
+ if (!currentListeners.length) {
779
+ delete object.events[eventKey];
780
+ object.events[eventKey + REVERT_MUTATION]();
781
+ delete object.events[eventKey + REVERT_MUTATION];
782
+ }
783
+ };
784
+ };
785
+ let onStart = ($store, listener) => on($store, listener, START, (runListeners) => {
786
+ let originListen = $store.listen;
787
+ $store.listen = (arg) => {
788
+ if (!$store.lc && !$store.starting) {
789
+ $store.starting = true;
790
+ runListeners();
791
+ delete $store.starting;
792
+ }
793
+ return originListen(arg);
794
+ };
795
+ return () => {
796
+ $store.listen = originListen;
797
+ };
798
+ });
799
+ let onStop = ($store, listener) => on($store, listener, STOP, (runListeners) => {
800
+ let originOff = $store.off;
801
+ $store.off = () => {
802
+ runListeners();
803
+ originOff();
804
+ };
805
+ return () => {
806
+ $store.off = originOff;
807
+ };
808
+ });
809
+ const STORE_UNMOUNT_DELAY = 1e3;
810
+ let onMount = ($store, initialize) => {
811
+ let listener = (payload) => {
812
+ let destroy = initialize(payload);
813
+ if (destroy) $store.events[UNMOUNT].push(destroy);
814
+ };
815
+ return on($store, listener, MOUNT, (runListeners) => {
816
+ let originListen = $store.listen;
817
+ $store.listen = (...args) => {
818
+ if (!$store.lc && !$store.active) {
819
+ $store.active = true;
820
+ runListeners();
821
+ }
822
+ return originListen(...args);
823
+ };
824
+ let originOff = $store.off;
825
+ $store.events[UNMOUNT] = [];
826
+ $store.off = () => {
827
+ originOff();
828
+ setTimeout(() => {
829
+ if ($store.active && !$store.lc) {
830
+ $store.active = false;
831
+ for (let destroy of $store.events[UNMOUNT]) destroy();
832
+ $store.events[UNMOUNT] = [];
833
+ }
834
+ }, STORE_UNMOUNT_DELAY);
835
+ };
836
+ {
837
+ let originClean = $store[clean];
838
+ $store[clean] = () => {
839
+ for (let destroy of $store.events[UNMOUNT]) destroy();
840
+ $store.events[UNMOUNT] = [];
841
+ $store.active = false;
842
+ originClean();
843
+ };
844
+ }
845
+ return () => {
846
+ $store.listen = originListen;
847
+ $store.off = originOff;
848
+ };
849
+ });
850
+ };
851
+ //#endregion
852
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/warn/index.js
853
+ let warned = {};
854
+ function warn(text) {
855
+ if (!warned[text]) {
856
+ warned[text] = true;
857
+ if (typeof console !== "undefined" && console.warn) {
858
+ console.groupCollapsed("Nano Stores: " + text);
859
+ console.trace("Source of deprecated call");
860
+ console.groupEnd();
861
+ }
862
+ }
863
+ }
864
+ //#endregion
865
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/computed/index.js
866
+ let computedStore = (stores, cb, batched) => {
867
+ if (!Array.isArray(stores)) stores = [stores];
868
+ let previousArgs;
869
+ let currentEpoch;
870
+ let set = () => {
871
+ if (currentEpoch === nanostoresGlobal.epoch) return;
872
+ currentEpoch = nanostoresGlobal.epoch;
873
+ let args = stores.map(($store) => $store.get());
874
+ if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {
875
+ previousArgs = args;
876
+ let value = cb(...args);
877
+ if (value && value.then && value.t) {
878
+ warn("Use @nanostores/async for async computed. We will remove Promise support in computed() in Nano Stores 2.0");
879
+ value.then((asyncValue) => {
880
+ if (previousArgs === args) $computed.set(asyncValue);
881
+ });
882
+ } else {
883
+ $computed.set(value);
884
+ currentEpoch = nanostoresGlobal.epoch;
885
+ }
886
+ }
887
+ };
888
+ let $computed = /* @__PURE__ */ atom(void 0);
889
+ let get = $computed.get;
890
+ $computed.get = () => {
891
+ set();
892
+ return get();
893
+ };
894
+ let timer;
895
+ let run = batched ? () => {
896
+ clearTimeout(timer);
897
+ timer = setTimeout(set);
898
+ } : set;
899
+ onMount($computed, () => {
900
+ let unbinds = stores.map(($store) => $store.listen(run));
901
+ set();
902
+ return () => {
903
+ for (let unbind of unbinds) unbind();
904
+ };
905
+ });
906
+ return $computed;
907
+ };
908
+ const computed = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn);
909
+ const batched = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn, true);
910
+ //#endregion
911
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/map/index.js
912
+ const map = /* @__NO_SIDE_EFFECTS__ */ (initial = {}) => {
913
+ let $map = /* @__PURE__ */ atom(initial);
914
+ $map.setKey = function(key, value) {
915
+ let oldMap = $map.value;
916
+ if (typeof value === "undefined" && key in $map.value) {
917
+ $map.value = { ...$map.value };
918
+ delete $map.value[key];
919
+ $map.notify(oldMap, key);
920
+ } else if ($map.value[key] !== value) {
921
+ $map.value = {
922
+ ...$map.value,
923
+ [key]: value
924
+ };
925
+ $map.notify(oldMap, key);
926
+ }
927
+ };
928
+ return $map;
929
+ };
930
+ //#endregion
931
+ //#region ../fragno/dist/util/ssr.js
932
+ let stores = [];
933
+ function addStore(store) {
934
+ stores.push(store);
935
+ }
936
+ //#endregion
937
+ //#region ../fragno/dist/client/client-error.js
938
+ /**
939
+ * Base error class for all Fragno client errors.
940
+ */
941
+ var FragnoClientError = class extends Error {
942
+ #code;
943
+ constructor(message, code, options = {}) {
944
+ super(message, { cause: options.cause });
945
+ this.name = "FragnoClientError";
946
+ this.#code = code;
947
+ }
948
+ get code() {
949
+ return this.#code;
950
+ }
951
+ };
952
+ var FragnoClientFetchError = class extends FragnoClientError {
953
+ constructor(message, code, options = {}) {
954
+ super(message, code, options);
955
+ this.name = "FragnoClientFetchError";
956
+ }
957
+ static fromUnknownFetchError(error) {
958
+ if (!(error instanceof Error)) return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
959
+ if (error.name === "AbortError") return new FragnoClientFetchAbortError("Request was aborted", { cause: error });
960
+ return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
961
+ }
962
+ };
963
+ /**
964
+ * Error thrown when a network request fails (e.g., no internet connection, DNS failure).
965
+ */
966
+ var FragnoClientFetchNetworkError = class extends FragnoClientFetchError {
967
+ constructor(message = "Network request failed", options = {}) {
968
+ super(message, "NETWORK_ERROR", options);
969
+ this.name = "FragnoClientFetchNetworkError";
970
+ }
971
+ };
972
+ /**
973
+ * Error thrown when a request is aborted (e.g., user cancels request, timeout).
974
+ */
975
+ var FragnoClientFetchAbortError = class extends FragnoClientFetchError {
976
+ constructor(message = "Request was aborted", options = {}) {
977
+ super(message, "ABORT_ERROR", options);
978
+ this.name = "FragnoClientFetchAbortError";
979
+ }
980
+ };
981
+ /**
982
+ * Error thrown when the API result is unexpected, e.g. no json is returned.
983
+ */
984
+ var FragnoClientUnknownApiError = class extends FragnoClientError {
985
+ #status;
986
+ constructor(message = "Unknown API error", status, options = {}) {
987
+ super(message, "UNKNOWN_API_ERROR", options);
988
+ this.name = "FragnoClientUnknownApiError";
989
+ this.#status = status;
990
+ }
991
+ get status() {
992
+ return this.#status;
993
+ }
994
+ };
995
+ var FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {
996
+ #status;
997
+ constructor({ message, code }, status, options = {}) {
998
+ super(message, code, options);
999
+ this.name = "FragnoClientApiError";
1000
+ this.#status = status;
1001
+ }
1002
+ get status() {
1003
+ return this.#status;
1004
+ }
1005
+ /**
1006
+ * The error code returned by the API.
1007
+ *
1008
+ * The type is `TErrorCode` (the set of known error codes for this route), but may also be a string
1009
+ * for forward compatibility with future error codes.
1010
+ */
1011
+ get code() {
1012
+ return super.code;
1013
+ }
1014
+ static async fromResponse(response) {
1015
+ const unknown = await response.json();
1016
+ const status = response.status;
1017
+ if (!("message" in unknown || "code" in unknown)) return new FragnoClientUnknownApiError("Unknown API error", status);
1018
+ if (!(typeof unknown.message === "string" && typeof unknown.code === "string")) return new FragnoClientUnknownApiError("Unknown API error", status);
1019
+ return new FragnoClientApiError({
1020
+ message: unknown.message,
1021
+ code: unknown.code
1022
+ }, status);
1023
+ }
1024
+ };
1025
+ //#endregion
1026
+ //#region ../fragno/dist/client/internal/fetcher-merge.js
1027
+ /**
1028
+ * Merge two fetcher configurations, with user config taking precedence.
1029
+ * If user provides a custom function, it takes full precedence.
1030
+ * Otherwise, deep merge RequestInit options.
1031
+ */
1032
+ function mergeFetcherConfigs(authorConfig, userConfig) {
1033
+ if (userConfig?.type === "function") return userConfig;
1034
+ if (!userConfig && authorConfig?.type === "function") return authorConfig;
1035
+ const authorOpts = authorConfig?.type === "options" ? authorConfig.options : {};
1036
+ const userOpts = userConfig?.type === "options" ? userConfig.options : {};
1037
+ if (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;
1038
+ return {
1039
+ type: "options",
1040
+ options: {
1041
+ ...authorOpts,
1042
+ ...userOpts,
1043
+ headers: mergeHeaders(authorOpts.headers, userOpts.headers)
1044
+ }
1045
+ };
1046
+ }
1047
+ /**
1048
+ * Merge headers from author and user configs.
1049
+ * User headers override author headers.
1050
+ */
1051
+ function mergeHeaders(author, user) {
1052
+ if (!author && !user) return;
1053
+ const merged = new Headers(author);
1054
+ new Headers(user).forEach((value, key) => {
1055
+ merged.set(key, value);
1056
+ });
1057
+ if (merged.keys().next().done) return;
1058
+ return merged;
1059
+ }
1060
+ //#endregion
1061
+ //#region ../fragno/dist/client/internal/ndjson-streaming.js
1062
+ /**
1063
+ * Creates a promise that rejects when the abort signal is triggered
1064
+ */
1065
+ function createAbortPromise(abortSignal) {
1066
+ return new Promise((_, reject) => {
1067
+ const abortHandler = () => {
1068
+ reject(new FragnoClientFetchAbortError("Operation was aborted"));
1069
+ };
1070
+ if (abortSignal.aborted) abortHandler();
1071
+ else abortSignal.addEventListener("abort", abortHandler, { once: true });
1072
+ });
1073
+ }
1074
+ const parseNdjsonBuffer = (buffer, options) => {
1075
+ const lines = buffer.split("\n");
1076
+ const trailingBuffer = options.flush ? "" : lines.pop() ?? "";
1077
+ for (let index = 0; index < lines.length; index += 1) {
1078
+ const line = lines[index];
1079
+ if (!line.trim()) continue;
1080
+ let jsonObject;
1081
+ try {
1082
+ jsonObject = JSON.parse(line);
1083
+ } catch (parseError) {
1084
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", options.parseErrorStatus, { cause: parseError });
1085
+ }
1086
+ if (options.onItem(jsonObject) === false) {
1087
+ const remainingLines = lines.slice(index + 1);
1088
+ return {
1089
+ stopped: true,
1090
+ buffer: remainingLines.length > 0 ? `${remainingLines.join("\n")}\n${trailingBuffer}` : trailingBuffer
1091
+ };
1092
+ }
1093
+ }
1094
+ return {
1095
+ stopped: false,
1096
+ buffer: trailingBuffer
1097
+ };
1098
+ };
1099
+ /**
1100
+ * Handles NDJSON streaming responses by returning the first item from the fetcher
1101
+ * and then continuing to stream updates via the store's mutate method.
1102
+ *
1103
+ * This makes it so that we can wait until the first chunk before updating the store, if we did
1104
+ * not do this, `loading` would briefly be false before the first item would be populated in the
1105
+ * result.
1106
+ *
1107
+ * @param response - The fetch Response object containing the NDJSON stream
1108
+ * @param store - The fetcher store to update with streaming data
1109
+ * @param abortSignal - Optional AbortSignal to cancel the streaming operation
1110
+ * @returns A promise that resolves to an object containing the first item and a streaming promise
1111
+ */
1112
+ async function handleNdjsonStreamingFirstItem(response, store, options = {}) {
1113
+ if (!response.body) throw new FragnoClientFetchError("Streaming response has no body", "NO_BODY");
1114
+ const { abortSignal } = options;
1115
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1116
+ const decoder = new TextDecoder();
1117
+ const reader = response.body.getReader();
1118
+ let buffer = "";
1119
+ let firstItem = null;
1120
+ const items = [];
1121
+ try {
1122
+ while (firstItem === null) {
1123
+ if (abortSignal?.aborted) {
1124
+ reader.releaseLock();
1125
+ throw new FragnoClientFetchAbortError("Operation was aborted");
1126
+ }
1127
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1128
+ if (done) break;
1129
+ buffer += decoder.decode(value, { stream: true });
1130
+ buffer = parseNdjsonBuffer(buffer, {
1131
+ parseErrorStatus: 500,
1132
+ onItem: (jsonObject) => {
1133
+ items.push(jsonObject);
1134
+ firstItem = jsonObject;
1135
+ return false;
1136
+ }
1137
+ }).buffer;
1138
+ if (firstItem !== null) {
1139
+ const streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);
1140
+ return {
1141
+ firstItem,
1142
+ items,
1143
+ streamingPromise
1144
+ };
1145
+ }
1146
+ }
1147
+ if (firstItem === null) {
1148
+ reader.releaseLock();
1149
+ throw new FragnoClientUnknownApiError("NDJSON stream contained no valid items", 500);
1150
+ }
1151
+ reader.releaseLock();
1152
+ throw new FragnoClientFetchError("Unexpected end of stream processing", "NO_BODY");
1153
+ } catch (error) {
1154
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1155
+ store?.setError(error);
1156
+ throw error;
1157
+ }
1158
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 500, { cause: error });
1159
+ store?.setError(clientError);
1160
+ throw clientError;
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Continues streaming the remaining items in the background
1165
+ */
1166
+ async function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {
1167
+ let buffer = initialBuffer;
1168
+ const appendItem = (jsonObject) => {
1169
+ items.push(jsonObject);
1170
+ store?.setData([...items]);
1171
+ };
1172
+ try {
1173
+ while (true) {
1174
+ buffer = parseNdjsonBuffer(buffer, {
1175
+ parseErrorStatus: 400,
1176
+ onItem: appendItem
1177
+ }).buffer;
1178
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1179
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1180
+ if (done) {
1181
+ parseNdjsonBuffer(buffer, {
1182
+ flush: true,
1183
+ parseErrorStatus: 400,
1184
+ onItem: appendItem
1185
+ });
1186
+ break;
1187
+ }
1188
+ buffer += decoder.decode(value, { stream: true });
1189
+ }
1190
+ } catch (error) {
1191
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1192
+ store?.setError(error);
1193
+ throw error;
1194
+ }
1195
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 400, { cause: error });
1196
+ store?.setError(clientError);
1197
+ throw clientError;
1198
+ } finally {
1199
+ reader.releaseLock();
1200
+ }
1201
+ return items;
1202
+ }
1203
+ //#endregion
1204
+ //#region ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
1205
+ let createNanoEvents = () => ({
1206
+ emit(event, ...args) {
1207
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) callbacks[i](...args);
1208
+ },
1209
+ events: {},
1210
+ on(event, cb) {
1211
+ (this.events[event] ||= []).push(cb);
1212
+ return () => {
1213
+ this.events[event] = this.events[event]?.filter((i) => cb !== i);
1214
+ };
1215
+ }
1216
+ });
1217
+ //#endregion
1218
+ //#region ../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.3.0/node_modules/@nanostores/query/dist/nanoquery.js
1219
+ function defaultOnErrorRetry({ retryCount }) {
1220
+ return ~~((Math.random() + .5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;
1221
+ }
1222
+ const nanoqueryFactory = ([isAppVisible, visibilityChangeSubscribe, reconnectChangeSubscribe]) => {
1223
+ const nanoquery = ({ cache = /* @__PURE__ */ new Map(), fetcher: globalFetcher, ...globalSettings } = {}) => {
1224
+ const events = createNanoEvents();
1225
+ let focus = true;
1226
+ visibilityChangeSubscribe(() => {
1227
+ focus = isAppVisible();
1228
+ focus && events.emit(FOCUS);
1229
+ });
1230
+ reconnectChangeSubscribe(() => events.emit(RECONNECT));
1231
+ const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();
1232
+ let rewrittenSettings = {};
1233
+ const getCachedValueByKey = (key) => {
1234
+ const fromCache = cache.get(key);
1235
+ if (!fromCache) return [];
1236
+ return (fromCache.expires || 0) > getNow() ? [fromCache.data, fromCache.error] : [];
1237
+ };
1238
+ const runFetcher = async ([key, keyParts], store, settings) => {
1239
+ if (!focus) return;
1240
+ const set = (v) => {
1241
+ if (store.key === key) {
1242
+ store.set(v);
1243
+ events.emit(SET_CACHE, key, v, true);
1244
+ }
1245
+ };
1246
+ const setAsLoading = (prev) => {
1247
+ set({
1248
+ ...prev === void 0 ? {} : { data: prev },
1249
+ ...loading,
1250
+ promise: _runningFetches.get(key)
1251
+ });
1252
+ };
1253
+ let { dedupeTime = 4e3, cacheLifetime = Infinity, fetcher, onErrorRetry = defaultOnErrorRetry } = {
1254
+ ...settings,
1255
+ ...rewrittenSettings
1256
+ };
1257
+ if (cacheLifetime < dedupeTime) cacheLifetime = dedupeTime;
1258
+ const now = getNow();
1259
+ if (_runningFetches.has(key)) {
1260
+ if (!store.value.loading) setAsLoading(getCachedValueByKey(key)[0]);
1261
+ return;
1262
+ }
1263
+ let cachedValue, cachedError;
1264
+ const fromCache = cache.get(key);
1265
+ if (fromCache?.data !== void 0 || fromCache?.error) {
1266
+ [cachedValue, cachedError] = getCachedValueByKey(key);
1267
+ if ((fromCache.created || 0) + dedupeTime > now) {
1268
+ if (store.value.data != cachedValue || store.value.error != cachedError) set({
1269
+ ...notLoading,
1270
+ data: cachedValue,
1271
+ error: cachedError
1272
+ });
1273
+ return;
1274
+ }
1275
+ }
1276
+ const finishTask = startTask();
1277
+ try {
1278
+ clearTimeout(_errorInvalidateTimeouts.get(key));
1279
+ const promise = fetcher(...keyParts);
1280
+ _runningFetches.set(key, promise);
1281
+ setAsLoading(cachedValue);
1282
+ const res = await promise;
1283
+ cache.set(key, {
1284
+ data: res,
1285
+ created: getNow(),
1286
+ expires: getNow() + cacheLifetime
1287
+ });
1288
+ set({
1289
+ data: res,
1290
+ ...notLoading
1291
+ });
1292
+ } catch (error) {
1293
+ settings.onError?.(error);
1294
+ const retryCount = (cache.get(key)?.retryCount || 0) + 1;
1295
+ cache.set(key, {
1296
+ error,
1297
+ created: getNow(),
1298
+ expires: getNow() + cacheLifetime,
1299
+ retryCount
1300
+ });
1301
+ if (onErrorRetry) {
1302
+ const timer = onErrorRetry({
1303
+ error,
1304
+ key,
1305
+ retryCount
1306
+ });
1307
+ if (timer) _errorInvalidateTimeouts.set(key, setTimeout(() => {
1308
+ invalidateKeys(key);
1309
+ cache.set(key, { retryCount });
1310
+ }, timer));
1311
+ }
1312
+ set({
1313
+ data: store.value.data,
1314
+ error,
1315
+ ...notLoading
1316
+ });
1317
+ } finally {
1318
+ finishTask();
1319
+ _runningFetches.delete(key);
1320
+ }
1321
+ };
1322
+ const createFetcherStore = (keyInput, { fetcher = globalFetcher, ...fetcherSettings } = {}) => {
1323
+ if (!fetcher) throw new Error("You need to set up either global fetcher of fetcher in createFetcherStore");
1324
+ const fetcherStore = /* @__PURE__ */ map({ ...notLoading }), settings = {
1325
+ ...globalSettings,
1326
+ ...fetcherSettings,
1327
+ fetcher
1328
+ };
1329
+ fetcherStore._ = fetcherSymbol;
1330
+ fetcherStore.invalidate = () => {
1331
+ const { key } = fetcherStore;
1332
+ if (key) invalidateKeys(key);
1333
+ };
1334
+ fetcherStore.revalidate = () => {
1335
+ const { key } = fetcherStore;
1336
+ if (key) revalidateKeys(key);
1337
+ };
1338
+ fetcherStore.mutate = (data) => {
1339
+ const { key } = fetcherStore;
1340
+ if (key) mutateCache(key, data);
1341
+ };
1342
+ fetcherStore.fetch = async () => {
1343
+ let resolve;
1344
+ const promise = new Promise((r) => resolve = r);
1345
+ const unsub = fetcherStore.listen(({ error, data }) => {
1346
+ if (error !== void 0) resolve({ error });
1347
+ if (data !== void 0) resolve({ data });
1348
+ });
1349
+ return promise.finally(unsub);
1350
+ };
1351
+ let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;
1352
+ let evtUnsubs = [];
1353
+ onStart(fetcherStore, () => {
1354
+ const firstRun = !keysInternalUnsub;
1355
+ [keyStore, keysInternalUnsub] = getKeyStore(keyInput);
1356
+ keyUnsub = keyStore.subscribe((currentKeys) => {
1357
+ if (currentKeys) {
1358
+ const [newKey, keyParts] = currentKeys;
1359
+ fetcherStore.key = newKey;
1360
+ runFetcher([newKey, keyParts], fetcherStore, settings);
1361
+ prevKey = newKey;
1362
+ prevKeyParts = keyParts;
1363
+ } else {
1364
+ fetcherStore.key = prevKey = prevKeyParts = void 0;
1365
+ fetcherStore.set({ ...notLoading });
1366
+ }
1367
+ });
1368
+ const currentKeyValue = keyStore.get();
1369
+ if (currentKeyValue) {
1370
+ [prevKey, prevKeyParts] = currentKeyValue;
1371
+ if (firstRun) handleNewListener();
1372
+ }
1373
+ const { revalidateInterval = 0, revalidateOnFocus, revalidateOnReconnect } = settings;
1374
+ const runRefetcher = () => {
1375
+ if (prevKey) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1376
+ };
1377
+ if (revalidateInterval > 0) _revalidateOnInterval.set(keyInput, setInterval(runRefetcher, revalidateInterval));
1378
+ if (revalidateOnFocus) evtUnsubs.push(events.on(FOCUS, runRefetcher));
1379
+ if (revalidateOnReconnect) evtUnsubs.push(events.on(RECONNECT, runRefetcher));
1380
+ const cacheKeyChangeHandler = (keySelector) => {
1381
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1382
+ };
1383
+ evtUnsubs.push(events.on(INVALIDATE_KEYS, cacheKeyChangeHandler), events.on(REVALIDATE_KEYS, cacheKeyChangeHandler), events.on(SET_CACHE, (keySelector, data, full) => {
1384
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) fetcherStore.set(full ? data : {
1385
+ data,
1386
+ ...notLoading
1387
+ });
1388
+ }));
1389
+ });
1390
+ const handleNewListener = () => {
1391
+ if (prevKey && prevKeyParts) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1392
+ };
1393
+ const originListen = fetcherStore.listen;
1394
+ fetcherStore.listen = (listener) => {
1395
+ const unsub = originListen(listener);
1396
+ listener(fetcherStore.value);
1397
+ handleNewListener();
1398
+ return unsub;
1399
+ };
1400
+ onStop(fetcherStore, () => {
1401
+ fetcherStore.value = { ...notLoading };
1402
+ keysInternalUnsub?.();
1403
+ evtUnsubs.forEach((fn) => fn());
1404
+ evtUnsubs = [];
1405
+ keyUnsub?.();
1406
+ clearInterval(_revalidateOnInterval.get(keyInput));
1407
+ });
1408
+ return fetcherStore;
1409
+ };
1410
+ const iterOverCache = (keySelector, cb) => {
1411
+ for (const key of cache.keys()) if (testKeyAgainstSelector(key, keySelector)) cb(key);
1412
+ };
1413
+ const invalidateKeys = (keySelector) => {
1414
+ iterOverCache(keySelector, (key) => {
1415
+ cache.delete(key);
1416
+ });
1417
+ events.emit(INVALIDATE_KEYS, keySelector);
1418
+ };
1419
+ const revalidateKeys = (keySelector) => {
1420
+ iterOverCache(keySelector, (key) => {
1421
+ const cached = cache.get(key);
1422
+ if (cached) cache.set(key, {
1423
+ ...cached,
1424
+ created: -Infinity
1425
+ });
1426
+ });
1427
+ events.emit(REVALIDATE_KEYS, keySelector);
1428
+ };
1429
+ const mutateCache = (keySelector, data) => {
1430
+ iterOverCache(keySelector, (key) => {
1431
+ if (data === void 0) cache.delete(key);
1432
+ else cache.set(key, {
1433
+ data,
1434
+ created: getNow(),
1435
+ expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)
1436
+ });
1437
+ });
1438
+ events.emit(SET_CACHE, keySelector, data);
1439
+ };
1440
+ function createMutatorStore(mutator, opts) {
1441
+ const { throttleCalls, onError } = opts ?? {
1442
+ throttleCalls: true,
1443
+ onError: globalSettings?.onError
1444
+ };
1445
+ const mutate = async (data) => {
1446
+ if (throttleCalls && store.value?.loading) return;
1447
+ const newMutator = rewrittenSettings.fetcher ?? mutator;
1448
+ const keysToInvalidate = [], keysToRevalidate = [];
1449
+ const safeKeySet = (k, v) => {
1450
+ if (store.lc) store.setKey(k, v);
1451
+ };
1452
+ try {
1453
+ store.set({
1454
+ error: void 0,
1455
+ data: void 0,
1456
+ mutate,
1457
+ ...loading
1458
+ });
1459
+ const result = await newMutator({
1460
+ data,
1461
+ invalidate: (key) => {
1462
+ keysToInvalidate.push(key);
1463
+ },
1464
+ revalidate: (key) => {
1465
+ keysToRevalidate.push(key);
1466
+ },
1467
+ getCacheUpdater: (key, shouldRevalidate = true) => [(newVal) => {
1468
+ mutateCache(key, newVal);
1469
+ if (shouldRevalidate) keysToRevalidate.push(key);
1470
+ }, cache.get(key)?.data]
1471
+ });
1472
+ safeKeySet("data", result);
1473
+ return result;
1474
+ } catch (error) {
1475
+ onError?.(error);
1476
+ safeKeySet("error", error);
1477
+ store.setKey("error", error);
1478
+ } finally {
1479
+ safeKeySet("loading", false);
1480
+ keysToInvalidate.forEach(invalidateKeys);
1481
+ keysToRevalidate.forEach(revalidateKeys);
1482
+ }
1483
+ };
1484
+ const store = /* @__PURE__ */ map({
1485
+ mutate,
1486
+ ...notLoading
1487
+ });
1488
+ onStop(store, () => store.set({
1489
+ mutate,
1490
+ ...notLoading
1491
+ }));
1492
+ store.mutate = mutate;
1493
+ return store;
1494
+ }
1495
+ const __unsafeOverruleSettings = (data) => {
1496
+ console.warn(`You should only use __unsafeOverruleSettings in test environment`);
1497
+ rewrittenSettings = data;
1498
+ };
1499
+ return [
1500
+ createFetcherStore,
1501
+ createMutatorStore,
1502
+ {
1503
+ __unsafeOverruleSettings,
1504
+ invalidateKeys,
1505
+ revalidateKeys,
1506
+ mutateCache
1507
+ }
1508
+ ];
1509
+ };
1510
+ function isSomeKey(key) {
1511
+ return typeof key === "string" || typeof key === "number" || key === true;
1512
+ }
1513
+ const getKeyStore = (keys) => {
1514
+ if (isSomeKey(keys)) return [/* @__PURE__ */ atom(["" + keys, [keys]]), () => {}];
1515
+ const keyParts = [];
1516
+ const $key = /* @__PURE__ */ atom(null);
1517
+ const keysAsStoresToIndexes = /* @__PURE__ */ new Map();
1518
+ const setKeyStoreValue = () => {
1519
+ if (keyParts.some((v) => v === null || v === void 0 || v === false)) $key.set(null);
1520
+ else $key.set([keyParts.join(""), keyParts]);
1521
+ };
1522
+ for (let i = 0; i < keys.length; i++) {
1523
+ const keyOrStore = keys[i];
1524
+ if (isSomeKey(keyOrStore)) keyParts.push(keyOrStore);
1525
+ else {
1526
+ keyParts.push(null);
1527
+ keysAsStoresToIndexes.set(keyOrStore, i);
1528
+ }
1529
+ }
1530
+ const storesAsArray = [...keysAsStoresToIndexes.keys()];
1531
+ const $storeKeys = /* @__PURE__ */ batched(storesAsArray, (...storeValues) => {
1532
+ for (let i = 0; i < storeValues.length; i++) {
1533
+ const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);
1534
+ keyParts[partIndex] = store._ === fetcherSymbol ? store.value && "data" in store.value ? store.key : null : storeValues[i];
1535
+ }
1536
+ setKeyStoreValue();
1537
+ });
1538
+ setKeyStoreValue();
1539
+ return [$key, $storeKeys.subscribe(noop)];
1540
+ };
1541
+ function noop() {}
1542
+ const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;
1543
+ const testKeyAgainstSelector = (key, selector) => {
1544
+ if (Array.isArray(selector)) return selector.includes(key);
1545
+ else if (typeof selector === "function") return selector(key);
1546
+ else return key === selector;
1547
+ };
1548
+ const getNow = () => (/* @__PURE__ */ new Date()).getTime();
1549
+ const fetcherSymbol = Symbol();
1550
+ const loading = { loading: true }, notLoading = { loading: false };
1551
+ return nanoquery;
1552
+ };
1553
+ const subscribe = (name, fn) => {
1554
+ if (!(typeof window === "undefined")) addEventListener(name, fn);
1555
+ };
1556
+ const nanoquery = nanoqueryFactory([
1557
+ () => !document.hidden,
1558
+ (cb) => subscribe("visibilitychange", cb),
1559
+ (cb) => subscribe("online", cb)
1560
+ ]);
1561
+ //#endregion
1562
+ //#region ../fragno/dist/client/client.js
1563
+ /**
1564
+ * Symbols used to identify hook types
1565
+ */
1566
+ const GET_HOOK_SYMBOL = Symbol("fragno-get-hook");
1567
+ const MUTATOR_HOOK_SYMBOL = Symbol("fragno-mutator-hook");
1568
+ const STORE_SYMBOL = Symbol("fragno-store");
1569
+ async function schemaAllowsUndefined(schema) {
1570
+ try {
1571
+ return !(await schema["~standard"].validate(void 0)).issues;
1572
+ } catch {
1573
+ return false;
1574
+ }
1575
+ }
1576
+ async function assertBodyProvided(body, inputSchema, errorMessage) {
1577
+ if (typeof body !== "undefined" || inputSchema === void 0) return;
1578
+ if (await schemaAllowsUndefined(inputSchema)) return;
1579
+ throw new Error(errorMessage);
1580
+ }
1581
+ /**
1582
+ * Merge request headers from multiple sources.
1583
+ * Returns undefined if there are no headers to merge.
1584
+ * @internal
1585
+ */
1586
+ function mergeRequestHeaders(...headerSources) {
1587
+ const result = {};
1588
+ let hasHeaders = false;
1589
+ for (const source of headerSources) {
1590
+ if (!source) continue;
1591
+ if (source instanceof Headers) for (const [key, value] of source.entries()) {
1592
+ result[key] = value;
1593
+ hasHeaders = true;
1594
+ }
1595
+ else if (Array.isArray(source)) for (const [key, value] of source) {
1596
+ result[key] = value;
1597
+ hasHeaders = true;
1598
+ }
1599
+ else for (const [key, value] of Object.entries(source)) {
1600
+ result[key] = value;
1601
+ hasHeaders = true;
1602
+ }
1603
+ }
1604
+ return hasHeaders ? result : void 0;
1605
+ }
1606
+ /**
1607
+ * @internal
1608
+ */
1609
+ function buildUrl(config, params) {
1610
+ const { baseUrl = "", mountRoute, path } = config;
1611
+ const { pathParams, queryParams } = params ?? {};
1612
+ const normalizedPathParams = unwrapObject(pathParams);
1613
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1614
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1615
+ const searchParams = new URLSearchParams(filteredQueryParams);
1616
+ return `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
1617
+ }
1618
+ /**
1619
+ * This method returns an array, which can be passed directly to nanostores.
1620
+ *
1621
+ * The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)
1622
+ * Missing pathParams are replaced with "<missing>".
1623
+ * Atoms with undefined values are wrapped in computed atoms that map undefined to "" to avoid nanoquery treating the key as incomplete.
1624
+ * @param path
1625
+ * @param params
1626
+ * @returns
1627
+ * @internal
1628
+ */
1629
+ function getCacheKey(method, path, params) {
1630
+ if (!params) return [method, path];
1631
+ const { pathParams, queryParams } = params;
1632
+ const pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? "<missing>");
1633
+ const queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {
1634
+ const value = queryParams[key];
1635
+ if (value && typeof value === "object" && "get" in value) return /* @__PURE__ */ computed(value, (v) => v ?? "");
1636
+ return value ?? "";
1637
+ }) : [];
1638
+ return [
1639
+ method,
1640
+ path,
1641
+ ...pathParamValues,
1642
+ ...queryParamValues
1643
+ ];
1644
+ }
1645
+ function isStreamingResponse(response) {
1646
+ const contentType = parseContentType(response.headers.get("content-type"));
1647
+ if (!contentType) return false;
1648
+ if (!(response.headers.get("transfer-encoding") === "chunked")) return false;
1649
+ if (contentType.subtype === "octet-stream") return "octet-stream";
1650
+ if (contentType.subtype === "x-ndjson") return "ndjson";
1651
+ return false;
1652
+ }
1653
+ /**
1654
+ * @internal
1655
+ */
1656
+ function isGetHook(hook) {
1657
+ return typeof hook === "object" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;
1658
+ }
1659
+ /**
1660
+ * @internal
1661
+ */
1662
+ function isMutatorHook(hook) {
1663
+ return typeof hook === "object" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;
1664
+ }
1665
+ /**
1666
+ * @internal
1667
+ */
1668
+ function isStore(obj) {
1669
+ return typeof obj === "object" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;
1670
+ }
1671
+ var ClientBuilder = class {
1672
+ #publicConfig;
1673
+ #fragmentConfig;
1674
+ #fetcherConfig;
1675
+ #cache = /* @__PURE__ */ new Map();
1676
+ #createFetcherStore;
1677
+ #createMutatorStore;
1678
+ #invalidateKeys;
1679
+ constructor(publicConfig, fragmentConfig) {
1680
+ this.#publicConfig = publicConfig;
1681
+ this.#fragmentConfig = fragmentConfig;
1682
+ this.#fetcherConfig = publicConfig.fetcherConfig;
1683
+ const [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({
1684
+ cache: this.#cache,
1685
+ cacheLifetime: Infinity
1686
+ });
1687
+ this.#createFetcherStore = createFetcherStore;
1688
+ this.#createMutatorStore = createMutatorStore;
1689
+ this.#invalidateKeys = invalidateKeys;
1690
+ }
1691
+ get cacheEntries() {
1692
+ return Object.fromEntries(this.#cache.entries());
1693
+ }
1694
+ createStore(input) {
1695
+ if (typeof input === "function") return {
1696
+ factory: input,
1697
+ [STORE_SYMBOL]: true
1698
+ };
1699
+ return {
1700
+ obj: input,
1701
+ [STORE_SYMBOL]: true
1702
+ };
1703
+ }
1704
+ /**
1705
+ * Build a URL for a custom backend call using the configured baseUrl and mountRoute.
1706
+ * Useful for fragment authors who need to make custom fetch calls.
1707
+ */
1708
+ buildUrl(path, params) {
1709
+ return buildUrl({
1710
+ baseUrl: this.#publicConfig.baseUrl ?? "",
1711
+ mountRoute: getMountRoute({
1712
+ name: this.#fragmentConfig.name,
1713
+ mountRoute: this.#publicConfig.mountRoute
1714
+ }),
1715
+ path
1716
+ }, {
1717
+ pathParams: params?.path,
1718
+ queryParams: params?.query
1719
+ });
1720
+ }
1721
+ /**
1722
+ * Get the configured fetcher function for custom backend calls.
1723
+ * Returns fetch with merged options applied.
1724
+ */
1725
+ getFetcher() {
1726
+ return {
1727
+ fetcher: this.#getFetcher(),
1728
+ defaultOptions: this.#getFetcherOptions()
1729
+ };
1730
+ }
1731
+ #getFetcher() {
1732
+ if (this.#fetcherConfig?.type === "function") return this.#fetcherConfig.fetcher;
1733
+ return globalThis.fetch.bind(globalThis);
1734
+ }
1735
+ #getFetcherOptions() {
1736
+ if (this.#fetcherConfig?.type === "options") return this.#fetcherConfig.options;
1737
+ }
1738
+ createHook(path, options) {
1739
+ const route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === "GET" && r.outputSchema !== void 0);
1740
+ if (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);
1741
+ return this.#createRouteQueryHook(route, options);
1742
+ }
1743
+ createMutator(method, path, onInvalidate) {
1744
+ const route = this.#fragmentConfig.routes.find((r) => r.method !== "GET" && r.path === path && r.method === method);
1745
+ if (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);
1746
+ return this.#createRouteQueryMutator(route, onInvalidate);
1747
+ }
1748
+ #createRouteQueryHook(route, options = {}) {
1749
+ if (route.method !== "GET") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${String(route.method)} route.`);
1750
+ if (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);
1751
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1752
+ const mountRoute = getMountRoute({
1753
+ name: this.#fragmentConfig.name,
1754
+ mountRoute: this.#publicConfig.mountRoute
1755
+ });
1756
+ const fetcher = this.#getFetcher();
1757
+ const fetcherOptions = this.#getFetcherOptions();
1758
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1759
+ async function callServerSideHandler(params) {
1760
+ const { pathParams, queryParams } = params ?? {};
1761
+ const normalizedPathParams = unwrapObject(pathParams);
1762
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1763
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1764
+ const searchParams = new URLSearchParams(filteredQueryParams);
1765
+ return await route.handler(RequestInputContext.fromSSRContext({
1766
+ method: route.method,
1767
+ path: route.path,
1768
+ pathParams: normalizedPathParams,
1769
+ searchParams
1770
+ }), new RequestOutputContext(route.outputSchema));
1771
+ }
1772
+ async function executeQuery(params) {
1773
+ const { pathParams, queryParams } = params ?? {};
1774
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => callServerSideHandler({
1775
+ pathParams,
1776
+ queryParams
1777
+ }));
1778
+ const url = buildUrl({
1779
+ baseUrl,
1780
+ mountRoute,
1781
+ path: route.path
1782
+ }, {
1783
+ pathParams,
1784
+ queryParams
1785
+ });
1786
+ let response;
1787
+ try {
1788
+ response = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);
1789
+ } catch (error) {
1790
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1791
+ }
1792
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1793
+ return response;
1794
+ }
1795
+ return {
1796
+ route,
1797
+ store: (args) => {
1798
+ const { path, query } = args ?? {};
1799
+ const key = getCacheKey(route.method, route.path, {
1800
+ pathParams: path,
1801
+ queryParams: query
1802
+ });
1803
+ const store = this.#createFetcherStore(key, {
1804
+ fetcher: async () => {
1805
+ const response = await executeQuery({
1806
+ pathParams: path,
1807
+ queryParams: query
1808
+ });
1809
+ const isStreaming = isStreamingResponse(response);
1810
+ if (!isStreaming) return response.json();
1811
+ if (typeof window === "undefined" && !useFetcherOnServer) {
1812
+ if (response.body) await response.body.getReader().cancel();
1813
+ return [];
1814
+ }
1815
+ if (isStreaming === "ndjson") {
1816
+ const { items } = await handleNdjsonStreamingFirstItem(response, {
1817
+ setData: (value) => {
1818
+ store.mutate(value);
1819
+ },
1820
+ setError: (value) => {
1821
+ store.set({
1822
+ ...store.get(),
1823
+ error: value
1824
+ });
1825
+ }
1826
+ });
1827
+ return items;
1828
+ }
1829
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1830
+ throw new Error("Unreachable");
1831
+ },
1832
+ onErrorRetry: options?.onErrorRetry,
1833
+ dedupeTime: Infinity
1834
+ });
1835
+ if (typeof window === "undefined") addStore(store);
1836
+ return store;
1837
+ },
1838
+ query: async (args) => {
1839
+ const { path, query } = args ?? {};
1840
+ const response = await executeQuery({
1841
+ pathParams: path,
1842
+ queryParams: query
1843
+ });
1844
+ const isStreaming = isStreamingResponse(response);
1845
+ if (!isStreaming) return await response.json();
1846
+ if (isStreaming === "ndjson") {
1847
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1848
+ return await streamingPromise;
1849
+ }
1850
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1851
+ throw new Error("Unreachable");
1852
+ },
1853
+ [GET_HOOK_SYMBOL]: true
1854
+ };
1855
+ }
1856
+ #createRouteQueryMutator(route, onInvalidate = (invalidate, params) => {
1857
+ invalidate("GET", route.path, params);
1858
+ }) {
1859
+ const method = route.method;
1860
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1861
+ const mountRoute = getMountRoute({
1862
+ name: this.#fragmentConfig.name,
1863
+ mountRoute: this.#publicConfig.mountRoute
1864
+ });
1865
+ const fetcher = this.#getFetcher();
1866
+ const fetcherOptions = this.#getFetcherOptions();
1867
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1868
+ async function executeMutateQuery({ body, path, query }) {
1869
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => route.handler(RequestInputContext.fromSSRContext({
1870
+ inputSchema: route.inputSchema,
1871
+ method,
1872
+ path: route.path,
1873
+ pathParams: path ?? {},
1874
+ searchParams: new URLSearchParams(query),
1875
+ body
1876
+ }), new RequestOutputContext(route.outputSchema)));
1877
+ const url = buildUrl({
1878
+ baseUrl,
1879
+ mountRoute,
1880
+ path: route.path
1881
+ }, {
1882
+ pathParams: path,
1883
+ queryParams: query
1884
+ });
1885
+ let response;
1886
+ try {
1887
+ const preparedBody = prepareClientRequestBody(body, route.contentType);
1888
+ const bodyHeaders = preparedBody.contentType === void 0 || preparedBody.contentType === null ? void 0 : { "Content-Type": preparedBody.contentType };
1889
+ const headers = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);
1890
+ const requestOptions = createRequestInitWithBody(method, headers ?? {}, preparedBody.body, fetcherOptions);
1891
+ response = await fetcher(url, requestOptions);
1892
+ } catch (error) {
1893
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1894
+ }
1895
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1896
+ return response;
1897
+ }
1898
+ const mutatorStore = this.#createMutatorStore(async ({ data }) => {
1899
+ if (typeof window === "undefined") {}
1900
+ const { body, path, query } = data;
1901
+ await assertBodyProvided(body, route.inputSchema, "Body is required.");
1902
+ const response = await executeMutateQuery({
1903
+ body,
1904
+ path,
1905
+ query
1906
+ });
1907
+ onInvalidate(this.#invalidate.bind(this), {
1908
+ pathParams: path ?? {},
1909
+ queryParams: query
1910
+ });
1911
+ if (response.status === 201 || response.status === 204) return;
1912
+ const isStreaming = isStreamingResponse(response);
1913
+ if (!isStreaming) return await response.json();
1914
+ if (typeof window === "undefined") return [];
1915
+ if (isStreaming === "ndjson") {
1916
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1917
+ setData: (value) => {
1918
+ mutatorStore.set({
1919
+ ...mutatorStore.get(),
1920
+ loading: !(Array.isArray(value) && value.length > 0),
1921
+ data: value
1922
+ });
1923
+ },
1924
+ setError: (value) => {
1925
+ mutatorStore.set({
1926
+ ...mutatorStore.get(),
1927
+ error: value
1928
+ });
1929
+ }
1930
+ });
1931
+ return [firstItem];
1932
+ }
1933
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1934
+ throw new Error("Unreachable");
1935
+ }, { onError: (error) => {
1936
+ console.error("Error in mutatorStore", error);
1937
+ } });
1938
+ const mutateQuery = async (data) => {
1939
+ const { body, path, query } = data;
1940
+ await assertBodyProvided(body, route.inputSchema, "Body is required for mutateQuery");
1941
+ const response = await executeMutateQuery({
1942
+ body,
1943
+ path,
1944
+ query
1945
+ });
1946
+ if (response.status === 201 || response.status === 204) return;
1947
+ const isStreaming = isStreamingResponse(response);
1948
+ if (!isStreaming) return await response.json();
1949
+ if (isStreaming === "ndjson") {
1950
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1951
+ return await streamingPromise;
1952
+ }
1953
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported for mutations");
1954
+ throw new Error("Unreachable");
1955
+ };
1956
+ return {
1957
+ route,
1958
+ mutateQuery,
1959
+ mutatorStore,
1960
+ [MUTATOR_HOOK_SYMBOL]: true
1961
+ };
1962
+ }
1963
+ #invalidate(method, path, params) {
1964
+ const prefix = getCacheKey(method, path, {
1965
+ pathParams: params?.pathParams,
1966
+ queryParams: params?.queryParams
1967
+ }).map((k) => typeof k === "string" ? k : k.get()).join("");
1968
+ this.#invalidateKeys((key) => key.startsWith(prefix));
1969
+ }
1970
+ };
1971
+ /**
1972
+ * Create a client builder for fragments using the new fragment definition API.
1973
+ * This is the same as createClientBuilder but works with FragmentDefinition.
1974
+ */
1975
+ function createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {
1976
+ const routes = resolveRouteFactories({
1977
+ config: {},
1978
+ deps: {},
1979
+ services: {},
1980
+ serviceDeps: {}
1981
+ }, routesOrFactories);
1982
+ const fragmentConfig = {
1983
+ name: definition.name,
1984
+ routes
1985
+ };
1986
+ const mountRoute = getMountRoute({
1987
+ name: definition.name,
1988
+ mountRoute: publicConfig.mountRoute
1989
+ });
1990
+ const mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);
1991
+ return new ClientBuilder({
1992
+ ...publicConfig,
1993
+ mountRoute,
1994
+ fetcherConfig: mergedFetcherConfig
1995
+ }, fragmentConfig);
1996
+ }
1997
+ //#endregion
1998
+ //#region src/definition.ts
1999
+ const apiFragmentDefinition = defineFragment("api-fragment").extend((x) => x).providesBaseService(() => {}).build();
2000
+ new TextEncoder();
2001
+ new TextDecoder();
2002
+ //#endregion
2003
+ //#region src/webhooks/auth.ts
2004
+ const secretRefSchema = z.string().trim().min(1);
2005
+ const requestValueNameSchema = z.string().trim().min(1);
2006
+ const webhookAuthConfigSchema = z.discriminatedUnion("type", [
2007
+ z.object({ type: z.literal("none") }),
2008
+ z.object({
2009
+ type: z.literal("bearer"),
2010
+ tokenRef: secretRefSchema
2011
+ }),
2012
+ z.object({
2013
+ type: z.literal("apiKey"),
2014
+ location: z.enum(["header", "query"]),
2015
+ name: requestValueNameSchema,
2016
+ secretRef: secretRefSchema
2017
+ }),
2018
+ z.object({
2019
+ type: z.literal("basic"),
2020
+ usernameRef: secretRefSchema,
2021
+ passwordRef: secretRefSchema
2022
+ }),
2023
+ z.object({
2024
+ type: z.literal("hmac"),
2025
+ secretRef: secretRefSchema,
2026
+ algorithm: z.enum([
2027
+ "sha1",
2028
+ "sha256",
2029
+ "sha512"
2030
+ ]),
2031
+ signature: z.object({
2032
+ location: z.enum(["header", "query"]),
2033
+ name: requestValueNameSchema,
2034
+ encoding: z.enum([
2035
+ "hex",
2036
+ "base64",
2037
+ "base64url"
2038
+ ]),
2039
+ prefix: z.string().optional()
2040
+ }),
2041
+ signedPayload: z.discriminatedUnion("type", [z.object({ type: z.literal("rawBody") }), z.object({
2042
+ type: z.literal("timestampBody"),
2043
+ timestampHeader: requestValueNameSchema,
2044
+ delimiter: z.string(),
2045
+ toleranceSeconds: z.number().int().positive()
2046
+ })])
2047
+ })
2048
+ ]);
2049
+ //#endregion
2050
+ //#region src/api-types.ts
2051
+ const tokenEndpointAuthMethodSchema = z.enum([
2052
+ "client_secret_basic",
2053
+ "client_secret_post",
2054
+ "none"
2055
+ ]);
2056
+ const authConfigSchema = z.discriminatedUnion("type", [
2057
+ z.object({ type: z.literal("none") }),
2058
+ z.object({
2059
+ type: z.literal("bearer"),
2060
+ token: z.string().min(1)
2061
+ }),
2062
+ z.object({
2063
+ type: z.literal("client_credentials"),
2064
+ tokenEndpoint: z.url(),
2065
+ clientId: z.string().min(1),
2066
+ clientSecret: z.string().min(1),
2067
+ scopes: z.array(z.string()).optional(),
2068
+ audience: z.string().min(1).optional(),
2069
+ tokenEndpointAuthMethod: z.enum(["client_secret_basic", "client_secret_post"]).default("client_secret_basic")
2070
+ }),
2071
+ z.object({
2072
+ type: z.literal("oauth"),
2073
+ authorizationEndpoint: z.url(),
2074
+ tokenEndpoint: z.url(),
2075
+ clientId: z.string().min(1),
2076
+ clientSecret: z.string().min(1).optional(),
2077
+ scopes: z.array(z.string()).optional(),
2078
+ tokenEndpointAuthMethod: tokenEndpointAuthMethodSchema.default("client_secret_basic"),
2079
+ extraAuthorizationParams: z.record(z.string(), z.string()).optional(),
2080
+ extraTokenParams: z.record(z.string(), z.string()).optional()
2081
+ })
2082
+ ]);
2083
+ const createApiConnectionInputSchema = z.object({
2084
+ name: z.string().min(1).optional(),
2085
+ baseUrl: z.url(),
2086
+ auth: authConfigSchema.default({ type: "none" })
2087
+ });
2088
+ const apiConnectionOutputSchema = z.object({
2089
+ slug: z.string(),
2090
+ name: z.string().nullable().optional(),
2091
+ baseUrl: z.string(),
2092
+ authMode: z.string(),
2093
+ status: z.string(),
2094
+ createdAt: z.union([z.string(), z.date()]).optional(),
2095
+ updatedAt: z.union([z.string(), z.date()]).optional()
2096
+ });
2097
+ const tokenAuthInputSchema = z.object({ token: z.string().min(1) });
2098
+ const oauthStartInputSchema = z.object({
2099
+ scopes: z.array(z.string()).optional(),
2100
+ extraAuthorizationParams: z.record(z.string(), z.string()).optional()
2101
+ });
2102
+ const apiRequestInputSchema = z.object({
2103
+ method: z.enum([
2104
+ "GET",
2105
+ "POST",
2106
+ "PUT",
2107
+ "PATCH",
2108
+ "DELETE"
2109
+ ]),
2110
+ path: z.string().min(1),
2111
+ query: z.record(z.string(), z.string()).optional(),
2112
+ headers: z.record(z.string(), z.string()).optional(),
2113
+ json: z.unknown().optional(),
2114
+ body: z.string().optional(),
2115
+ timeoutMs: z.number().int().positive().max(12e4).optional()
2116
+ }).refine((value) => value.json === void 0 || value.body === void 0, {
2117
+ message: "Use either json or body, not both",
2118
+ path: ["body"]
2119
+ });
2120
+ const webhookSecretRefSchema = z.string().trim().min(1);
2121
+ const webhookRequestValueNameSchema = z.string().trim().min(1);
2122
+ const webhookDeliveryIdentitySchema = z.discriminatedUnion("type", [
2123
+ z.object({
2124
+ type: z.literal("header"),
2125
+ name: webhookRequestValueNameSchema
2126
+ }),
2127
+ z.object({
2128
+ type: z.literal("query"),
2129
+ name: webhookRequestValueNameSchema
2130
+ }),
2131
+ z.object({
2132
+ type: z.literal("jsonBodyPath"),
2133
+ path: z.array(z.string().trim().min(1)).min(1)
2134
+ })
2135
+ ]);
2136
+ const webhookEndpointAuthInputSchema = z.discriminatedUnion("type", [
2137
+ z.object({ type: z.literal("none") }),
2138
+ z.object({
2139
+ type: z.literal("bearer"),
2140
+ token: webhookSecretRefSchema
2141
+ }),
2142
+ z.object({
2143
+ type: z.literal("apiKey"),
2144
+ location: z.enum(["header", "query"]),
2145
+ name: webhookRequestValueNameSchema,
2146
+ secret: webhookSecretRefSchema
2147
+ }),
2148
+ z.object({
2149
+ type: z.literal("basic"),
2150
+ username: webhookSecretRefSchema,
2151
+ password: webhookSecretRefSchema
2152
+ }),
2153
+ z.object({
2154
+ type: z.literal("hmac"),
2155
+ secret: webhookSecretRefSchema,
2156
+ algorithm: z.enum([
2157
+ "sha1",
2158
+ "sha256",
2159
+ "sha512"
2160
+ ]),
2161
+ signature: z.object({
2162
+ location: z.enum(["header", "query"]),
2163
+ name: webhookRequestValueNameSchema,
2164
+ encoding: z.enum([
2165
+ "hex",
2166
+ "base64",
2167
+ "base64url"
2168
+ ]),
2169
+ prefix: z.string().optional()
2170
+ }),
2171
+ signedPayload: z.discriminatedUnion("type", [z.object({ type: z.literal("rawBody") }), z.object({
2172
+ type: z.literal("timestampBody"),
2173
+ timestampHeader: webhookRequestValueNameSchema,
2174
+ delimiter: z.string(),
2175
+ toleranceSeconds: z.number().int().positive()
2176
+ })])
2177
+ })
2178
+ ]);
2179
+ const webhookEndpointStatusSchema = z.enum([
2180
+ "draft",
2181
+ "active",
2182
+ "disabled"
2183
+ ]);
2184
+ const webhookEndpointOutputSchema = z.object({
2185
+ id: z.string(),
2186
+ name: z.string(),
2187
+ status: webhookEndpointStatusSchema,
2188
+ authConfig: webhookAuthConfigSchema,
2189
+ deliveryIdentity: webhookDeliveryIdentitySchema,
2190
+ secretRefs: z.array(z.string()),
2191
+ createdAt: z.union([z.string(), z.date()]).optional(),
2192
+ updatedAt: z.union([z.string(), z.date()]).optional()
2193
+ });
2194
+ const createWebhookEndpointInputSchema = z.object({
2195
+ name: z.string().min(1),
2196
+ status: webhookEndpointStatusSchema.default("active"),
2197
+ deliveryIdentity: webhookDeliveryIdentitySchema,
2198
+ auth: webhookEndpointAuthInputSchema
2199
+ });
2200
+ const updateWebhookEndpointInputSchema = z.object({
2201
+ name: z.string().min(1).optional(),
2202
+ status: webhookEndpointStatusSchema.optional(),
2203
+ deliveryIdentity: webhookDeliveryIdentitySchema.optional(),
2204
+ auth: webhookEndpointAuthInputSchema.optional()
2205
+ });
2206
+ //#endregion
2207
+ //#region src/routes.ts
2208
+ const connectionsOutputSchema = z.object({ connections: z.array(apiConnectionOutputSchema) });
2209
+ const webhookEndpointsOutputSchema = z.object({ endpoints: z.array(webhookEndpointOutputSchema) });
2210
+ const webhookReceivedOutputSchema = z.object({ accepted: z.boolean() });
2211
+ const authStatusSchema = z.object({
2212
+ authenticated: z.boolean(),
2213
+ mode: z.string(),
2214
+ tokenPresent: z.boolean().optional(),
2215
+ expiresAt: z.union([z.string(), z.date()]).nullable().optional()
2216
+ });
2217
+ const oauthStartOutputSchema = z.object({
2218
+ authorizationUrl: z.string(),
2219
+ state: z.string()
2220
+ });
2221
+ const oauthCallbackOutputSchema = z.object({
2222
+ authenticated: z.boolean(),
2223
+ mode: z.string()
2224
+ });
2225
+ const requestOutputSchema = z.object({
2226
+ status: z.number(),
2227
+ statusText: z.string(),
2228
+ headers: z.record(z.string(), z.string()),
2229
+ body: z.unknown()
2230
+ });
2231
+ const apiRoutesFactory = defineRoutes(apiFragmentDefinition).create(({ services, defineRoute, config }) => [
2232
+ defineRoute({
2233
+ method: "PUT",
2234
+ path: "/webhooks/endpoints/:endpointId",
2235
+ inputSchema: createWebhookEndpointInputSchema,
2236
+ outputSchema: webhookEndpointOutputSchema,
2237
+ handler: () => {}
2238
+ }),
2239
+ defineRoute({
2240
+ method: "GET",
2241
+ path: "/webhooks/endpoints",
2242
+ outputSchema: webhookEndpointsOutputSchema,
2243
+ handler: () => {}
2244
+ }),
2245
+ defineRoute({
2246
+ method: "GET",
2247
+ path: "/webhooks/endpoints/:endpointId",
2248
+ outputSchema: webhookEndpointOutputSchema,
2249
+ errorCodes: ["WEBHOOK_ENDPOINT_NOT_FOUND"],
2250
+ handler: () => {}
2251
+ }),
2252
+ defineRoute({
2253
+ method: "POST",
2254
+ path: "/webhooks/endpoints/:endpointId/events",
2255
+ errorCodes: [
2256
+ "WEBHOOK_ENDPOINT_NOT_FOUND",
2257
+ "WEBHOOK_ENDPOINT_DISABLED",
2258
+ "WEBHOOK_ENDPOINT_DRAFT",
2259
+ "WEBHOOK_AUTH_FAILED",
2260
+ "WEBHOOK_BODY_INVALID",
2261
+ "WEBHOOK_DELIVERY_ID_MISSING",
2262
+ "WEBHOOK_DELIVERY_ID_INVALID"
2263
+ ],
2264
+ outputSchema: webhookReceivedOutputSchema,
2265
+ handler: () => {}
2266
+ }),
2267
+ defineRoute({
2268
+ method: "PATCH",
2269
+ path: "/webhooks/endpoints/:endpointId",
2270
+ inputSchema: updateWebhookEndpointInputSchema,
2271
+ outputSchema: webhookEndpointOutputSchema,
2272
+ errorCodes: ["WEBHOOK_ENDPOINT_NOT_FOUND"],
2273
+ handler: () => {}
2274
+ }),
2275
+ defineRoute({
2276
+ method: "DELETE",
2277
+ path: "/webhooks/endpoints/:endpointId",
2278
+ handler: () => {}
2279
+ }),
2280
+ defineRoute({
2281
+ method: "PUT",
2282
+ path: "/connections/:slug",
2283
+ inputSchema: createApiConnectionInputSchema,
2284
+ outputSchema: apiConnectionOutputSchema,
2285
+ errorCodes: ["CONNECTION_EXISTS", "BASE_URL_NOT_ALLOWED"],
2286
+ handler: () => {}
2287
+ }),
2288
+ defineRoute({
2289
+ method: "GET",
2290
+ path: "/connections",
2291
+ outputSchema: connectionsOutputSchema,
2292
+ handler: () => {}
2293
+ }),
2294
+ defineRoute({
2295
+ method: "GET",
2296
+ path: "/connections/:slug",
2297
+ outputSchema: apiConnectionOutputSchema,
2298
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2299
+ handler: () => {}
2300
+ }),
2301
+ defineRoute({
2302
+ method: "DELETE",
2303
+ path: "/connections/:slug",
2304
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2305
+ handler: () => {}
2306
+ }),
2307
+ defineRoute({
2308
+ method: "GET",
2309
+ path: "/connections/:slug/auth/status",
2310
+ outputSchema: authStatusSchema,
2311
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2312
+ handler: () => {}
2313
+ }),
2314
+ defineRoute({
2315
+ method: "POST",
2316
+ path: "/connections/:slug/auth/token",
2317
+ inputSchema: tokenAuthInputSchema,
2318
+ outputSchema: authStatusSchema,
2319
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2320
+ handler: () => {}
2321
+ }),
2322
+ defineRoute({
2323
+ method: "POST",
2324
+ path: "/connections/:slug/auth/oauth/start",
2325
+ inputSchema: oauthStartInputSchema,
2326
+ outputSchema: oauthStartOutputSchema,
2327
+ errorCodes: [
2328
+ "CONNECTION_NOT_FOUND",
2329
+ "AUTH_NOT_CONFIGURED",
2330
+ "AUTH_NOT_OAUTH",
2331
+ "OAUTH_ERROR"
2332
+ ],
2333
+ handler: () => {}
2334
+ }),
2335
+ defineRoute({
2336
+ method: "GET",
2337
+ path: "/oauth/callback",
2338
+ outputSchema: oauthCallbackOutputSchema,
2339
+ errorCodes: [
2340
+ "CONNECTION_NOT_FOUND",
2341
+ "AUTH_NOT_CONFIGURED",
2342
+ "AUTH_NOT_OAUTH",
2343
+ "OAUTH_ERROR",
2344
+ "INVALID_OAUTH_STATE"
2345
+ ],
2346
+ handler: () => {}
2347
+ }),
2348
+ defineRoute({
2349
+ method: "DELETE",
2350
+ path: "/connections/:slug/auth",
2351
+ outputSchema: authStatusSchema,
2352
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2353
+ handler: () => {}
2354
+ }),
2355
+ defineRoute({
2356
+ method: "POST",
2357
+ path: "/connections/:slug/request",
2358
+ inputSchema: apiRequestInputSchema,
2359
+ outputSchema: requestOutputSchema,
2360
+ errorCodes: [
2361
+ "CONNECTION_NOT_FOUND",
2362
+ "CONNECTION_DISABLED",
2363
+ "API_REQUEST_ERROR"
2364
+ ],
2365
+ handler: () => {}
2366
+ })
2367
+ ]);
2368
+ //#endregion
2369
+ //#region src/schema.ts
2370
+ function jsonColumn() {
2371
+ return column("json");
2372
+ }
2373
+ const apiSchema = schema("api-fragment", (s) => {
2374
+ return s.addTable("api_connection", (t) => t.addColumn("id", idColumn()).addColumn("name", column("string").nullable()).addColumn("baseUrl", column("string")).addColumn("authMode", column("string")).addColumn("status", column("string")).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now()))).addTable("secret", (t) => t.addColumn("id", idColumn()).addColumn("connectionId", referenceColumn({ table: "api_connection" })).addColumn("kind", column("string")).addColumn("payload", column("text")).addColumn("expiresAt", column("timestamp").nullable()).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_secret_connection_kind", ["connectionId", "kind"], { unique: true })).addTable("oauthState", (t) => t.addColumn("id", idColumn()).addColumn("connectionId", referenceColumn({ table: "api_connection" })).addColumn("codeVerifier", column("text")).addColumn("redirectUri", column("string")).addColumn("scope", column("string").nullable()).addColumn("expiresAt", column("timestamp")).addColumn("consumedAt", column("timestamp").nullable()).createIndex("idx_oauth_state_connection", ["connectionId"])).addTable("webhookEndpoint", (t) => t.addColumn("id", idColumn()).addColumn("name", column("string")).addColumn("status", column("string")).addColumn("authConfig", jsonColumn()).addColumn("deliveryIdentity", jsonColumn()).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now()))).addTable("webhookSecret", (t) => t.addColumn("id", idColumn()).addColumn("endpointId", referenceColumn({ table: "webhookEndpoint" })).addColumn("ref", column("string")).addColumn("payload", column("text")).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_webhook_secret_endpoint_ref", ["endpointId", "ref"], { unique: true }));
2375
+ });
2376
+ //#endregion
2377
+ //#region src/index.ts
2378
+ const routes = [apiRoutesFactory];
2379
+ function createApiFragment(config, fragnoConfig) {
2380
+ return {};
2381
+ }
2382
+ function createApiFragmentClients(fragnoConfig = {}) {
2383
+ const builder = createClientBuilder(apiFragmentDefinition, fragnoConfig, routes);
2384
+ return {
2385
+ useConnections: builder.createHook("/connections"),
2386
+ useConnection: builder.createHook("/connections/:slug"),
2387
+ useAuthStatus: builder.createHook("/connections/:slug/auth/status"),
2388
+ createConnection: builder.createMutator("PUT", "/connections/:slug"),
2389
+ deleteConnection: builder.createMutator("DELETE", "/connections/:slug"),
2390
+ setBearerToken: builder.createMutator("POST", "/connections/:slug/auth/token"),
2391
+ startOAuth: builder.createMutator("POST", "/connections/:slug/auth/oauth/start"),
2392
+ deleteAuth: builder.createMutator("DELETE", "/connections/:slug/auth"),
2393
+ request: builder.createMutator("POST", "/connections/:slug/request"),
2394
+ useWebhookEndpoints: builder.createHook("/webhooks/endpoints"),
2395
+ useWebhookEndpoint: builder.createHook("/webhooks/endpoints/:endpointId"),
2396
+ createWebhookEndpoint: builder.createMutator("PUT", "/webhooks/endpoints/:endpointId"),
2397
+ updateWebhookEndpoint: builder.createMutator("PATCH", "/webhooks/endpoints/:endpointId"),
2398
+ deleteWebhookEndpoint: builder.createMutator("DELETE", "/webhooks/endpoints/:endpointId")
2399
+ };
2400
+ }
2401
+ //#endregion
2402
+ export { apiFragmentDefinition as a, isStore as c, apiRoutesFactory as i, atom as l, createApiFragmentClients as n, isGetHook as o, apiSchema as r, isMutatorHook as s, createApiFragment as t, isReadableAtom as u };
2403
+
2404
+ //# sourceMappingURL=src-BrYPVbAN.js.map