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