@fragno-dev/pi-harness 0.0.0-stage → 0.0.3

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 (140) hide show
  1. package/LICENSE.md +16 -0
  2. package/README.md +181 -2
  3. package/dist/browser/agent-harness-event-protocol-CuKubox1.js +666 -0
  4. package/dist/browser/agent-harness-event-protocol-CuKubox1.js.map +1 -0
  5. package/dist/browser/agent-harness-event-protocol-d6mH_9n3.d.ts +261 -0
  6. package/dist/browser/agent-harness-event-protocol-d6mH_9n3.d.ts.map +1 -0
  7. package/dist/browser/client/clients.d.ts +2 -0
  8. package/dist/browser/client/clients.js +2 -0
  9. package/dist/browser/client/pi-workflow-emission-stream.d.ts +13 -0
  10. package/dist/browser/client/pi-workflow-emission-stream.d.ts.map +1 -0
  11. package/dist/browser/client/pi-workflow-emission-stream.js +29 -0
  12. package/dist/browser/client/pi-workflow-emission-stream.js.map +1 -0
  13. package/dist/browser/client/react.d.ts +147 -0
  14. package/dist/browser/client/react.d.ts.map +1 -0
  15. package/dist/browser/client/react.js +187 -0
  16. package/dist/browser/client/react.js.map +1 -0
  17. package/dist/browser/client/solid.d.ts +150 -0
  18. package/dist/browser/client/solid.d.ts.map +1 -0
  19. package/dist/browser/client/solid.js +130 -0
  20. package/dist/browser/client/solid.js.map +1 -0
  21. package/dist/browser/client/svelte.d.ts +150 -0
  22. package/dist/browser/client/svelte.d.ts.map +1 -0
  23. package/dist/browser/client/svelte.js +132 -0
  24. package/dist/browser/client/svelte.js.map +1 -0
  25. package/dist/browser/client/vanilla.d.ts +177 -0
  26. package/dist/browser/client/vanilla.d.ts.map +1 -0
  27. package/dist/browser/client/vanilla.js +159 -0
  28. package/dist/browser/client/vanilla.js.map +1 -0
  29. package/dist/browser/client/vue.d.ts +150 -0
  30. package/dist/browser/client/vue.d.ts.map +1 -0
  31. package/dist/browser/client/vue.js +128 -0
  32. package/dist/browser/client/vue.js.map +1 -0
  33. package/dist/browser/client/workflow-lofi-session-projection.d.ts +17 -0
  34. package/dist/browser/client/workflow-lofi-session-projection.d.ts.map +1 -0
  35. package/dist/browser/client/workflow-lofi-session-projection.js +107 -0
  36. package/dist/browser/client/workflow-lofi-session-projection.js.map +1 -0
  37. package/dist/browser/clients-DYXj19je.d.ts +247 -0
  38. package/dist/browser/clients-DYXj19je.d.ts.map +1 -0
  39. package/dist/browser/clients-pIAk6ClP.js +1853 -0
  40. package/dist/browser/clients-pIAk6ClP.js.map +1 -0
  41. package/dist/browser/pi/context-usage.d.ts +20 -0
  42. package/dist/browser/pi/context-usage.d.ts.map +1 -0
  43. package/dist/browser/pi/context-usage.js +84 -0
  44. package/dist/browser/pi/context-usage.js.map +1 -0
  45. package/dist/browser/pi/harness/agent-harness-event-protocol.d.ts +2 -0
  46. package/dist/browser/pi/harness/agent-harness-event-protocol.js +2 -0
  47. package/dist/browser/pi/route-schemas.d.ts +2 -0
  48. package/dist/browser/pi/route-schemas.js +130 -0
  49. package/dist/browser/pi/route-schemas.js.map +1 -0
  50. package/dist/browser/pi/workflow-session-projection.d.ts +2 -0
  51. package/dist/browser/pi/workflow-session-projection.js +2 -0
  52. package/dist/browser/route-schemas-DQB5ZR1E.d.ts +109 -0
  53. package/dist/browser/route-schemas-DQB5ZR1E.d.ts.map +1 -0
  54. package/dist/browser/types-8q4RWFXT.js +23 -0
  55. package/dist/browser/types-8q4RWFXT.js.map +1 -0
  56. package/dist/browser/types-Dk856kV1.d.ts +527 -0
  57. package/dist/browser/types-Dk856kV1.d.ts.map +1 -0
  58. package/dist/browser/workflow-session-projection-CJ4MUkpJ.js +443 -0
  59. package/dist/browser/workflow-session-projection-CJ4MUkpJ.js.map +1 -0
  60. package/dist/browser/workflow-session-projection-Dj_a79GF.d.ts +93 -0
  61. package/dist/browser/workflow-session-projection-Dj_a79GF.d.ts.map +1 -0
  62. package/dist/node/pi/compact-command-outcome-projection.js +41 -0
  63. package/dist/node/pi/compact-command-outcome-projection.js.map +1 -0
  64. package/dist/node/pi/context-usage.d.ts +20 -0
  65. package/dist/node/pi/context-usage.d.ts.map +1 -0
  66. package/dist/node/pi/context-usage.js +84 -0
  67. package/dist/node/pi/context-usage.js.map +1 -0
  68. package/dist/node/pi/definition.d.ts +535 -0
  69. package/dist/node/pi/definition.d.ts.map +1 -0
  70. package/dist/node/pi/definition.js +71 -0
  71. package/dist/node/pi/definition.js.map +1 -0
  72. package/dist/node/pi/factory.d.ts +142 -0
  73. package/dist/node/pi/factory.d.ts.map +1 -0
  74. package/dist/node/pi/factory.js +22 -0
  75. package/dist/node/pi/factory.js.map +1 -0
  76. package/dist/node/pi/harness/agent-harness-event-protocol.d.ts +261 -0
  77. package/dist/node/pi/harness/agent-harness-event-protocol.d.ts.map +1 -0
  78. package/dist/node/pi/harness/agent-harness-event-protocol.js +588 -0
  79. package/dist/node/pi/harness/agent-harness-event-protocol.js.map +1 -0
  80. package/dist/node/pi/harness/json-value.js +82 -0
  81. package/dist/node/pi/harness/json-value.js.map +1 -0
  82. package/dist/node/pi/harness/pi-operation-completed.d.ts +16 -0
  83. package/dist/node/pi/harness/pi-operation-completed.d.ts.map +1 -0
  84. package/dist/node/pi/harness/pi-operation-completed.js +71 -0
  85. package/dist/node/pi/harness/pi-operation-completed.js.map +1 -0
  86. package/dist/node/pi/harness/session-storage.d.ts +62 -0
  87. package/dist/node/pi/harness/session-storage.d.ts.map +1 -0
  88. package/dist/node/pi/harness/session-storage.js +174 -0
  89. package/dist/node/pi/harness/session-storage.js.map +1 -0
  90. package/dist/node/pi/pi-jsonl-export.d.ts +11 -0
  91. package/dist/node/pi/pi-jsonl-export.d.ts.map +1 -0
  92. package/dist/node/pi/pi-jsonl-export.js +31 -0
  93. package/dist/node/pi/pi-jsonl-export.js.map +1 -0
  94. package/dist/node/pi/route-schemas.d.ts +109 -0
  95. package/dist/node/pi/route-schemas.d.ts.map +1 -0
  96. package/dist/node/pi/route-schemas.js +130 -0
  97. package/dist/node/pi/route-schemas.js.map +1 -0
  98. package/dist/node/pi/session-command-protocol.d.ts +14 -0
  99. package/dist/node/pi/session-command-protocol.d.ts.map +1 -0
  100. package/dist/node/pi/session-command-protocol.js +25 -0
  101. package/dist/node/pi/session-command-protocol.js.map +1 -0
  102. package/dist/node/pi/session-entry-projection.js +79 -0
  103. package/dist/node/pi/session-entry-projection.js.map +1 -0
  104. package/dist/node/pi/skills.d.ts +70 -0
  105. package/dist/node/pi/skills.d.ts.map +1 -0
  106. package/dist/node/pi/skills.js +150 -0
  107. package/dist/node/pi/skills.js.map +1 -0
  108. package/dist/node/pi/tools.d.ts +12 -0
  109. package/dist/node/pi/tools.d.ts.map +1 -0
  110. package/dist/node/pi/tools.js +8 -0
  111. package/dist/node/pi/tools.js.map +1 -0
  112. package/dist/node/pi/types.d.ts +165 -0
  113. package/dist/node/pi/types.d.ts.map +1 -0
  114. package/dist/node/pi/types.js +49 -0
  115. package/dist/node/pi/types.js.map +1 -0
  116. package/dist/node/pi/wait-for-command-step.js +46 -0
  117. package/dist/node/pi/wait-for-command-step.js.map +1 -0
  118. package/dist/node/pi/workflow-session-live-projection.js +220 -0
  119. package/dist/node/pi/workflow-session-live-projection.js.map +1 -0
  120. package/dist/node/pi/workflow-session-projection.d.ts +84 -0
  121. package/dist/node/pi/workflow-session-projection.d.ts.map +1 -0
  122. package/dist/node/pi/workflow-session-projection.js +100 -0
  123. package/dist/node/pi/workflow-session-projection.js.map +1 -0
  124. package/dist/node/pi/workflows/interactive-chat-workflow.d.ts +37 -0
  125. package/dist/node/pi/workflows/interactive-chat-workflow.d.ts.map +1 -0
  126. package/dist/node/pi/workflows/interactive-chat-workflow.js +219 -0
  127. package/dist/node/pi/workflows/interactive-chat-workflow.js.map +1 -0
  128. package/dist/node/pi/workflows/workflow-agent-harness.d.ts +142 -0
  129. package/dist/node/pi/workflows/workflow-agent-harness.d.ts.map +1 -0
  130. package/dist/node/pi/workflows/workflow-agent-harness.js +450 -0
  131. package/dist/node/pi/workflows/workflow-agent-harness.js.map +1 -0
  132. package/dist/node/routes.d.ts +631 -0
  133. package/dist/node/routes.d.ts.map +1 -0
  134. package/dist/node/routes.js +355 -0
  135. package/dist/node/routes.js.map +1 -0
  136. package/dist/node/schema.d.ts +5 -0
  137. package/dist/node/schema.d.ts.map +1 -0
  138. package/dist/node/schema.js +7 -0
  139. package/dist/node/schema.js.map +1 -0
  140. package/package.json +175 -3
@@ -0,0 +1,1853 @@
1
+ import "./types-8q4RWFXT.js";
2
+ import "./workflow-session-projection-CJ4MUkpJ.js";
3
+ import { commandAckSchema, commandInputSchema, sessionBaseSchema, sessionDetailSchema } from "./pi/route-schemas.js";
4
+ import { atom, batched, computed, map, onStart, onStop, startTask, task } from "nanostores";
5
+ import { defineFragment, defineRoutes } from "@fragno-dev/core";
6
+ import "@fragno-dev/db";
7
+ import { z } from "zod";
8
+ import { WorkflowsLogger } from "@fragno-dev/workflows/debug-log";
9
+ //#region ../fragno/dist/api/internal/path.js
10
+ /**
11
+ * Extract parameter names from a path pattern at runtime.
12
+ * Examples:
13
+ * - "/users/:id" => ["id"]
14
+ * - "/files/**" => ["**"]
15
+ * - "/files/**:rest" => ["rest"]
16
+ */
17
+ function extractPathParams(pathPattern) {
18
+ const segments = pathPattern.split("/").filter((s) => s.length > 0);
19
+ const names = [];
20
+ for (const segment of segments) {
21
+ if (segment.startsWith(":")) {
22
+ names.push(segment.slice(1));
23
+ continue;
24
+ }
25
+ if (segment === "**") {
26
+ names.push("**");
27
+ continue;
28
+ }
29
+ if (segment.startsWith("**:")) {
30
+ names.push(segment.slice(3));
31
+ continue;
32
+ }
33
+ }
34
+ return names;
35
+ }
36
+ /**
37
+ * Build a concrete path by replacing placeholders in a path pattern with values.
38
+ *
39
+ * Supports the same placeholder syntax as the matcher:
40
+ * - Named parameter ":name" is URL-encoded as a single segment
41
+ * - Anonymous wildcard "**" inserts the remainder as-is (slashes preserved)
42
+ * - Named wildcard "**:name" inserts the remainder from the named key
43
+ *
44
+ * Examples:
45
+ * - buildPath("/users/:id", { id: "123" }) => "/users/123"
46
+ * - buildPath("/files/**", { "**": "a/b" }) => "/files/a/b"
47
+ * - buildPath("/files/**:rest", { rest: "a/b" }) => "/files/a/b"
48
+ */
49
+ function buildPath(pathPattern, params) {
50
+ const patternSegments = pathPattern.split("/");
51
+ const builtSegments = [];
52
+ for (const segment of patternSegments) {
53
+ if (segment.length === 0) {
54
+ builtSegments.push("");
55
+ continue;
56
+ }
57
+ if (segment.startsWith(":")) {
58
+ const name = segment.slice(1);
59
+ const value = params[name];
60
+ if (value === void 0) throw new Error(`Missing value for path parameter :${name}`);
61
+ builtSegments.push(encodeURIComponent(value));
62
+ continue;
63
+ }
64
+ if (segment === "**") {
65
+ const value = params["**"];
66
+ if (value === void 0) throw new Error("Missing value for path wildcard **");
67
+ builtSegments.push(value);
68
+ continue;
69
+ }
70
+ if (segment.startsWith("**:")) {
71
+ const name = segment.slice(3);
72
+ const value = params[name];
73
+ if (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);
74
+ builtSegments.push(value);
75
+ continue;
76
+ }
77
+ builtSegments.push(segment);
78
+ }
79
+ return builtSegments.join("/");
80
+ }
81
+ //#endregion
82
+ //#region ../fragno/dist/api/request-body.js
83
+ const isBinaryRequestBody = (body) => body instanceof ReadableStream || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body);
84
+ const containsFileBody = (value) => {
85
+ if (value instanceof File || value instanceof Blob || value instanceof FormData) return true;
86
+ return typeof value === "object" && value !== null && Object.values(value).some((entry) => entry instanceof File || entry instanceof Blob || entry instanceof FormData);
87
+ };
88
+ const appendFormDataValue = (formData, key, value) => {
89
+ if (value instanceof File) formData.append(key, value, value.name);
90
+ else if (value instanceof Blob) formData.append(key, value);
91
+ else if (value !== void 0 && value !== null) formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
92
+ };
93
+ const prepareMultipartBody = (body) => {
94
+ if (body instanceof FormData) return body;
95
+ const formData = new FormData();
96
+ if (body instanceof File) {
97
+ formData.append("file", body, body.name);
98
+ return formData;
99
+ }
100
+ if (body instanceof Blob) {
101
+ formData.append("file", body);
102
+ return formData;
103
+ }
104
+ if (typeof body === "object" && body !== null) {
105
+ for (const [key, value] of Object.entries(body)) appendFormDataValue(formData, key, value);
106
+ return formData;
107
+ }
108
+ throw new TypeError("Multipart routes require FormData, File, Blob, or an object body.");
109
+ };
110
+ const prepareClientRequestBody = (body, contentType) => {
111
+ if (body === void 0) return {
112
+ body: void 0,
113
+ contentType: void 0
114
+ };
115
+ if (contentType === "application/octet-stream") {
116
+ if (!isBinaryRequestBody(body)) throw new TypeError("Octet-stream routes require Blob, ArrayBuffer, ArrayBufferView, or ReadableStream bodies.");
117
+ return {
118
+ body,
119
+ contentType
120
+ };
121
+ }
122
+ if (body instanceof FormData || body instanceof File || body instanceof Blob) return {
123
+ body: prepareMultipartBody(body),
124
+ contentType: null
125
+ };
126
+ if (containsFileBody(body)) return {
127
+ body: prepareMultipartBody(body),
128
+ contentType: null
129
+ };
130
+ return {
131
+ body: JSON.stringify(body),
132
+ contentType: "application/json"
133
+ };
134
+ };
135
+ const createRequestInitWithBody = (method, headers, body, options = {}) => {
136
+ const requestInit = {
137
+ ...options,
138
+ method,
139
+ headers,
140
+ body
141
+ };
142
+ if (body instanceof ReadableStream) requestInit.duplex = "half";
143
+ return requestInit;
144
+ };
145
+ //#endregion
146
+ //#region ../fragno/dist/api/internal/route.js
147
+ function getMountRoute(opts) {
148
+ const mountRoute = opts.mountRoute ?? `/api/${opts.name}`;
149
+ if (mountRoute.endsWith("/")) return mountRoute.slice(0, -1);
150
+ return mountRoute;
151
+ }
152
+ //#endregion
153
+ //#region ../fragno/dist/api/error.js
154
+ var FragnoApiError = class extends Error {
155
+ #status;
156
+ #code;
157
+ constructor({ message, code }, status) {
158
+ super(message);
159
+ this.name = "FragnoApiError";
160
+ this.#status = status;
161
+ this.#code = code;
162
+ }
163
+ get status() {
164
+ return this.#status;
165
+ }
166
+ get code() {
167
+ return this.#code;
168
+ }
169
+ toResponse() {
170
+ return Response.json({
171
+ message: this.message,
172
+ code: this.code
173
+ }, { status: this.status });
174
+ }
175
+ };
176
+ var FragnoApiValidationError = class extends FragnoApiError {
177
+ issues;
178
+ constructor(message, issues) {
179
+ super({
180
+ message,
181
+ code: "FRAGNO_VALIDATION_ERROR"
182
+ }, 400);
183
+ this.name = "FragnoApiValidationError";
184
+ this.issues = issues;
185
+ }
186
+ toResponse() {
187
+ return Response.json({
188
+ message: this.message,
189
+ issues: this.issues,
190
+ code: this.code
191
+ }, { status: this.status });
192
+ }
193
+ };
194
+ //#endregion
195
+ //#region ../fragno/dist/api/request-input-context.js
196
+ var RequestInputContext = class RequestInputContext {
197
+ #path;
198
+ #method;
199
+ #pathParams;
200
+ #searchParams;
201
+ #headers;
202
+ #body;
203
+ #request;
204
+ #parsedBody;
205
+ #inputSchema;
206
+ #shouldValidateInput;
207
+ constructor(config) {
208
+ this.#path = config.path;
209
+ this.#method = config.method;
210
+ this.#pathParams = config.pathParams;
211
+ this.#searchParams = config.searchParams;
212
+ this.#headers = config.headers;
213
+ this.#body = config.rawBody;
214
+ this.#request = config.request;
215
+ this.#parsedBody = config.parsedBody;
216
+ this.#inputSchema = config.inputSchema;
217
+ this.#shouldValidateInput = config.shouldValidateInput ?? true;
218
+ }
219
+ /**
220
+ * Create a RequestContext from a Request object for server-side handling
221
+ */
222
+ static async fromRequest(config) {
223
+ return new RequestInputContext({
224
+ method: config.method,
225
+ path: config.path,
226
+ pathParams: config.state.pathParams,
227
+ searchParams: config.state.searchParams,
228
+ headers: config.state.headers,
229
+ request: config.request,
230
+ parsedBody: config.state.body,
231
+ rawBody: config.rawBody,
232
+ inputSchema: config.inputSchema,
233
+ shouldValidateInput: config.shouldValidateInput
234
+ });
235
+ }
236
+ /**
237
+ * Create a RequestContext for server-side rendering contexts (no Request object)
238
+ */
239
+ static fromSSRContext(config) {
240
+ return new RequestInputContext({
241
+ method: config.method,
242
+ path: config.path,
243
+ pathParams: config.pathParams,
244
+ searchParams: config.searchParams ?? new URLSearchParams(),
245
+ headers: config.headers ?? new Headers(),
246
+ parsedBody: "body" in config ? config.body : void 0,
247
+ inputSchema: "inputSchema" in config ? config.inputSchema : void 0,
248
+ shouldValidateInput: false
249
+ });
250
+ }
251
+ /**
252
+ * The HTTP method as string (e.g., `GET`, `POST`)
253
+ */
254
+ get method() {
255
+ return this.#method;
256
+ }
257
+ /**
258
+ * The matched route path (e.g., `/users/:id`)
259
+ * @remarks `string`
260
+ */
261
+ get path() {
262
+ return this.#path;
263
+ }
264
+ /**
265
+ * Extracted path parameters as object (e.g., `{ id: '123' }`)
266
+ * @remarks `Record<string, string>`
267
+ */
268
+ get pathParams() {
269
+ return this.#pathParams;
270
+ }
271
+ /**
272
+ * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters
273
+ * @remarks `URLSearchParams`
274
+ */
275
+ get query() {
276
+ return this.#searchParams;
277
+ }
278
+ /**
279
+ * [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers
280
+ * @remarks `Headers`
281
+ */
282
+ get headers() {
283
+ return this.#headers;
284
+ }
285
+ get rawBody() {
286
+ return this.#body;
287
+ }
288
+ get request() {
289
+ return this.#request;
290
+ }
291
+ /**
292
+ * Access the request body as FormData.
293
+ *
294
+ * Use this method when handling file uploads or multipart form submissions.
295
+ * The request must have been sent with Content-Type: multipart/form-data.
296
+ *
297
+ * @throws Error if the request body is not FormData
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * defineRoute({
302
+ * method: "POST",
303
+ * path: "/upload",
304
+ * async handler(ctx, res) {
305
+ * const formData = ctx.formData();
306
+ * const file = formData.get("file") as File;
307
+ * const description = formData.get("description") as string;
308
+ * // ... process file
309
+ * }
310
+ * });
311
+ * ```
312
+ */
313
+ formData() {
314
+ if (!(this.#parsedBody instanceof FormData)) throw new Error("Request body is not FormData. Ensure the request was sent with Content-Type: multipart/form-data.");
315
+ return this.#parsedBody;
316
+ }
317
+ /**
318
+ * Check if the request body is FormData.
319
+ *
320
+ * Useful for routes that accept both JSON and FormData payloads.
321
+ *
322
+ * @example
323
+ * ```typescript
324
+ * defineRoute({
325
+ * method: "POST",
326
+ * path: "/upload",
327
+ * async handler(ctx, res) {
328
+ * if (ctx.isFormData()) {
329
+ * const formData = ctx.formData();
330
+ * // handle file upload
331
+ * } else {
332
+ * const json = await ctx.input.valid();
333
+ * // handle JSON payload
334
+ * }
335
+ * }
336
+ * });
337
+ * ```
338
+ */
339
+ isFormData() {
340
+ return this.#parsedBody instanceof FormData;
341
+ }
342
+ /**
343
+ * Access the request body as a ReadableStream (application/octet-stream).
344
+ *
345
+ * @throws Error if the request body is not a ReadableStream
346
+ */
347
+ bodyStream() {
348
+ 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.");
349
+ return this.#parsedBody;
350
+ }
351
+ /**
352
+ * Check if the request body is a ReadableStream.
353
+ */
354
+ isBodyStream() {
355
+ return this.#parsedBody instanceof ReadableStream;
356
+ }
357
+ /**
358
+ * Input validation context (only if inputSchema is defined)
359
+ * @remarks `InputContext`
360
+ */
361
+ get input() {
362
+ if (!this.#inputSchema) return;
363
+ return {
364
+ schema: this.#inputSchema,
365
+ valid: async () => {
366
+ if (!this.#shouldValidateInput) return this.#parsedBody;
367
+ return this.#validateInput();
368
+ }
369
+ };
370
+ }
371
+ async #validateInput() {
372
+ if (!this.#inputSchema) throw new Error("No input schema defined for this route");
373
+ if (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error("Schema validation is only supported for JSON data, not FormData or Blob");
374
+ if (this.#parsedBody instanceof ReadableStream) throw new Error("Schema validation is only supported for JSON data, not FormData, Blob, or ReadableStream");
375
+ const result = await this.#inputSchema["~standard"].validate(this.#parsedBody);
376
+ if (result.issues) throw new FragnoApiValidationError("Validation failed", result.issues);
377
+ return result.value;
378
+ }
379
+ };
380
+ //#endregion
381
+ //#region ../fragno/dist/api/internal/response-stream.js
382
+ var ResponseStream = class {
383
+ #writer;
384
+ #encoder;
385
+ #abortSubscribers = [];
386
+ #responseReadable;
387
+ #aborted = false;
388
+ #abortPromise;
389
+ #closed = false;
390
+ /**
391
+ * Whether the stream has been aborted.
392
+ */
393
+ get aborted() {
394
+ return this.#aborted;
395
+ }
396
+ /**
397
+ * Whether the stream has been closed normally.
398
+ */
399
+ get closed() {
400
+ return this.#closed;
401
+ }
402
+ /**
403
+ * The readable stream that the response is piped to.
404
+ */
405
+ get responseReadable() {
406
+ return this.#responseReadable;
407
+ }
408
+ constructor(writable, readable) {
409
+ this.#writer = writable.getWriter();
410
+ this.#encoder = new TextEncoder();
411
+ const reader = readable.getReader();
412
+ this.#abortSubscribers.push(async () => {
413
+ await reader.cancel();
414
+ });
415
+ this.#responseReadable = new ReadableStream({
416
+ async pull(controller) {
417
+ const { done, value } = await reader.read();
418
+ if (done) controller.close();
419
+ else controller.enqueue(value);
420
+ },
421
+ cancel: () => this.abort()
422
+ });
423
+ }
424
+ async writeRaw(input) {
425
+ try {
426
+ if (typeof input === "string") input = this.#encoder.encode(input);
427
+ await this.#writer.write(input);
428
+ return true;
429
+ } catch {
430
+ return false;
431
+ }
432
+ }
433
+ async write(input) {
434
+ await this.writeRaw(JSON.stringify(input) + "\n");
435
+ }
436
+ sleep(ms) {
437
+ return new Promise((resolve) => {
438
+ setTimeout(resolve, ms);
439
+ });
440
+ }
441
+ async close() {
442
+ try {
443
+ await this.#writer.close();
444
+ } catch {} finally {
445
+ this.#closed = true;
446
+ }
447
+ }
448
+ onAbort(listener) {
449
+ this.#abortSubscribers.push(listener);
450
+ }
451
+ /**
452
+ * Abort the stream.
453
+ * You can call this method when stream is aborted by external event.
454
+ */
455
+ abort() {
456
+ if (!this.#abortPromise) {
457
+ this.#aborted = true;
458
+ this.#abortPromise = Promise.allSettled(this.#abortSubscribers.map(async (subscriber) => subscriber())).then((results) => {
459
+ const errors = [];
460
+ for (const result of results) if (result.status === "rejected") errors.push(result.reason);
461
+ if (errors.length > 0) throw new AggregateError(errors, "Failed to abort response stream.");
462
+ });
463
+ }
464
+ return this.#abortPromise;
465
+ }
466
+ };
467
+ //#endregion
468
+ //#region ../fragno/dist/api/request-output-context.js
469
+ /**
470
+ * Utility function to merge headers from multiple sources.
471
+ * Later headers override earlier ones.
472
+ */
473
+ function mergeHeaders$1(...headerSources) {
474
+ const mergedHeaders = new Headers();
475
+ for (const headerSource of headerSources) {
476
+ if (!headerSource) continue;
477
+ if (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);
478
+ else if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);
479
+ else for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);
480
+ }
481
+ return mergedHeaders;
482
+ }
483
+ var OutputContext = class {
484
+ #runJsonStreamCallback;
485
+ constructor(options = {}) {
486
+ this.#runJsonStreamCallback = options.runJsonStreamCallback;
487
+ }
488
+ /**
489
+ * Creates an error response.
490
+ *
491
+ * Shortcut for `throw new FragnoApiError(...)`
492
+ */
493
+ error = ({ message, code }, initOrStatus, headers) => {
494
+ if (typeof initOrStatus === "undefined") return Response.json({
495
+ message,
496
+ code
497
+ }, {
498
+ status: 500,
499
+ headers
500
+ });
501
+ if (typeof initOrStatus === "number") return Response.json({
502
+ message,
503
+ code
504
+ }, {
505
+ status: initOrStatus,
506
+ headers
507
+ });
508
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
509
+ return Response.json({
510
+ message,
511
+ code
512
+ }, {
513
+ status: initOrStatus.status,
514
+ headers: mergedHeaders
515
+ });
516
+ };
517
+ empty = (initOrStatus, headers) => {
518
+ const defaultHeaders = {};
519
+ if (typeof initOrStatus === "undefined") {
520
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
521
+ return new Response(null, {
522
+ status: 201,
523
+ headers: mergedHeaders
524
+ });
525
+ }
526
+ if (typeof initOrStatus === "number") {
527
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
528
+ return new Response(null, {
529
+ status: initOrStatus,
530
+ headers: mergedHeaders
531
+ });
532
+ }
533
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, initOrStatus.headers, headers);
534
+ return new Response(null, {
535
+ status: initOrStatus.status,
536
+ headers: mergedHeaders
537
+ });
538
+ };
539
+ json = (object, initOrStatus, headers) => {
540
+ if (typeof initOrStatus === "undefined") return Response.json(object, {
541
+ status: 200,
542
+ headers
543
+ });
544
+ if (typeof initOrStatus === "number") return Response.json(object, {
545
+ status: initOrStatus,
546
+ headers
547
+ });
548
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
549
+ return Response.json(object, {
550
+ status: initOrStatus.status,
551
+ headers: mergedHeaders
552
+ });
553
+ };
554
+ jsonStream = (cb, { onError, headers } = {}) => {
555
+ const defaultHeaders = {
556
+ "content-type": "application/x-ndjson; charset=utf-8",
557
+ "transfer-encoding": "chunked",
558
+ "cache-control": "no-cache"
559
+ };
560
+ const { readable, writable } = new TransformStream();
561
+ const stream = new ResponseStream(writable, readable);
562
+ const runStreamCallback = async () => {
563
+ try {
564
+ await cb(stream);
565
+ } catch (e) {
566
+ if (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);
567
+ else console.error(e);
568
+ } finally {
569
+ await stream.close();
570
+ }
571
+ };
572
+ try {
573
+ Promise.resolve(this.#runJsonStreamCallback ? this.#runJsonStreamCallback(runStreamCallback) : runStreamCallback()).catch(async (error) => {
574
+ console.error(error);
575
+ await stream.close();
576
+ });
577
+ } catch (error) {
578
+ console.error(error);
579
+ stream.close();
580
+ }
581
+ return new Response(stream.responseReadable, {
582
+ status: 200,
583
+ headers: mergeHeaders$1(defaultHeaders, headers)
584
+ });
585
+ };
586
+ };
587
+ var RequestOutputContext = class extends OutputContext {
588
+ #outputSchema;
589
+ constructor(outputSchema, options) {
590
+ super(options);
591
+ this.#outputSchema = outputSchema;
592
+ }
593
+ };
594
+ //#endregion
595
+ //#region ../fragno/dist/api/route.js
596
+ /**
597
+ * Helper to resolve route factories into routes
598
+ * @internal
599
+ */
600
+ function resolveRouteFactories(context, routesOrFactories) {
601
+ const routes = [];
602
+ for (const item of routesOrFactories) if (typeof item === "function") {
603
+ const factoryRoutes = item(context);
604
+ routes.push(...factoryRoutes);
605
+ } else routes.push(item);
606
+ return routes;
607
+ }
608
+ //#endregion
609
+ //#region ../fragno/dist/util/content-type.js
610
+ /**
611
+ * Parses a content-type header string into its components
612
+ *
613
+ * @param contentType - The content-type header value to parse
614
+ * @returns A ParsedContentType object or null if the input is invalid
615
+ *
616
+ * @example
617
+ * ```ts
618
+ * const { type, subtype, mediaType, parameters }
619
+ * = parseContentType("application/json; charset=utf-8");
620
+ * console.assert(type === "application");
621
+ * console.assert(subtype === "json");
622
+ * console.assert(mediaType === "application/json");
623
+ * console.assert(parameters["charset"] === "utf-8");
624
+ */
625
+ function parseContentType(contentType) {
626
+ if (!contentType || typeof contentType !== "string") return null;
627
+ const trimmed = contentType.trim();
628
+ if (!trimmed) return null;
629
+ const parts = trimmed.split(";").map((part) => part.trim());
630
+ const mediaType = parts[0];
631
+ if (!mediaType) return null;
632
+ const typeParts = mediaType.split("/");
633
+ if (typeParts.length !== 2) return null;
634
+ const [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());
635
+ if (!type || !subtype) return null;
636
+ const parameters = {};
637
+ for (let i = 1; i < parts.length; i++) {
638
+ const param = parts[i];
639
+ const equalIndex = param.indexOf("=");
640
+ if (equalIndex > 0) {
641
+ const key = param.slice(0, equalIndex).trim().toLowerCase();
642
+ let value = param.slice(equalIndex + 1).trim();
643
+ if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
644
+ if (key) parameters[key] = value;
645
+ }
646
+ }
647
+ return {
648
+ type,
649
+ subtype,
650
+ mediaType: `${type}/${subtype}`,
651
+ parameters
652
+ };
653
+ }
654
+ //#endregion
655
+ //#region ../fragno/dist/util/nanostores.js
656
+ /**
657
+ * Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.
658
+ */
659
+ function unwrapAtom(value) {
660
+ if (value && typeof value === "object" && "get" in value && typeof value.get === "function") return value.get();
661
+ return value;
662
+ }
663
+ /**
664
+ * Normalizes an object where values can be plain values, Atoms, or Vue Refs.
665
+ * Returns a new object with all values normalized to plain values.
666
+ */
667
+ function unwrapObject(params) {
668
+ if (!params) return;
669
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));
670
+ }
671
+ function isReadableAtom(value) {
672
+ if (!value) return false;
673
+ if (typeof value !== "object" || value === null) return false;
674
+ if (!("get" in value) || typeof value.get !== "function") return false;
675
+ if (!("lc" in value) || typeof value.lc !== "number") return false;
676
+ if (!("notify" in value) || typeof value.notify !== "function") return false;
677
+ if (!("off" in value) || typeof value.off !== "function") return false;
678
+ if (!("subscribe" in value) || typeof value.subscribe !== "function") return false;
679
+ if (!("value" in value)) return false;
680
+ return true;
681
+ }
682
+ //#endregion
683
+ //#region ../fragno/dist/util/ssr.js
684
+ let stores = [];
685
+ function addStore(store) {
686
+ stores.push(store);
687
+ }
688
+ //#endregion
689
+ //#region ../fragno/dist/client/client-error.js
690
+ /**
691
+ * Base error class for all Fragno client errors.
692
+ */
693
+ var FragnoClientError = class extends Error {
694
+ #code;
695
+ constructor(message, code, options = {}) {
696
+ super(message, { cause: options.cause });
697
+ this.name = "FragnoClientError";
698
+ this.#code = code;
699
+ }
700
+ get code() {
701
+ return this.#code;
702
+ }
703
+ };
704
+ var FragnoClientFetchError = class extends FragnoClientError {
705
+ constructor(message, code, options = {}) {
706
+ super(message, code, options);
707
+ this.name = "FragnoClientFetchError";
708
+ }
709
+ static fromUnknownFetchError(error) {
710
+ if (!(error instanceof Error)) return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
711
+ if (error.name === "AbortError") return new FragnoClientFetchAbortError("Request was aborted", { cause: error });
712
+ return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
713
+ }
714
+ };
715
+ /**
716
+ * Error thrown when a network request fails (e.g., no internet connection, DNS failure).
717
+ */
718
+ var FragnoClientFetchNetworkError = class extends FragnoClientFetchError {
719
+ constructor(message = "Network request failed", options = {}) {
720
+ super(message, "NETWORK_ERROR", options);
721
+ this.name = "FragnoClientFetchNetworkError";
722
+ }
723
+ };
724
+ /**
725
+ * Error thrown when a request is aborted (e.g., user cancels request, timeout).
726
+ */
727
+ var FragnoClientFetchAbortError = class extends FragnoClientFetchError {
728
+ constructor(message = "Request was aborted", options = {}) {
729
+ super(message, "ABORT_ERROR", options);
730
+ this.name = "FragnoClientFetchAbortError";
731
+ }
732
+ };
733
+ /**
734
+ * Error thrown when the API result is unexpected, e.g. no json is returned.
735
+ */
736
+ var FragnoClientUnknownApiError = class extends FragnoClientError {
737
+ #status;
738
+ constructor(message = "Unknown API error", status, options = {}) {
739
+ super(message, "UNKNOWN_API_ERROR", options);
740
+ this.name = "FragnoClientUnknownApiError";
741
+ this.#status = status;
742
+ }
743
+ get status() {
744
+ return this.#status;
745
+ }
746
+ };
747
+ var FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {
748
+ #status;
749
+ constructor({ message, code }, status, options = {}) {
750
+ super(message, code, options);
751
+ this.name = "FragnoClientApiError";
752
+ this.#status = status;
753
+ }
754
+ get status() {
755
+ return this.#status;
756
+ }
757
+ /**
758
+ * The error code returned by the API.
759
+ *
760
+ * The type is `TErrorCode` (the set of known error codes for this route), but may also be a string
761
+ * for forward compatibility with future error codes.
762
+ */
763
+ get code() {
764
+ return super.code;
765
+ }
766
+ static async fromResponse(response) {
767
+ const unknown = await response.json();
768
+ const status = response.status;
769
+ if (!("message" in unknown || "code" in unknown)) return new FragnoClientUnknownApiError("Unknown API error", status);
770
+ if (!(typeof unknown.message === "string" && typeof unknown.code === "string")) return new FragnoClientUnknownApiError("Unknown API error", status);
771
+ return new FragnoClientApiError({
772
+ message: unknown.message,
773
+ code: unknown.code
774
+ }, status);
775
+ }
776
+ };
777
+ //#endregion
778
+ //#region ../fragno/dist/client/internal/fetcher-merge.js
779
+ /**
780
+ * Merge two fetcher configurations, with user config taking precedence.
781
+ * If user provides a custom function, it takes full precedence.
782
+ * Otherwise, deep merge RequestInit options.
783
+ */
784
+ function mergeFetcherConfigs(authorConfig, userConfig) {
785
+ if (userConfig?.type === "function") return userConfig;
786
+ if (!userConfig && authorConfig?.type === "function") return authorConfig;
787
+ const authorOpts = authorConfig?.type === "options" ? authorConfig.options : {};
788
+ const userOpts = userConfig?.type === "options" ? userConfig.options : {};
789
+ if (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;
790
+ return {
791
+ type: "options",
792
+ options: {
793
+ ...authorOpts,
794
+ ...userOpts,
795
+ headers: mergeHeaders(authorOpts.headers, userOpts.headers)
796
+ }
797
+ };
798
+ }
799
+ /**
800
+ * Merge headers from author and user configs.
801
+ * User headers override author headers.
802
+ */
803
+ function mergeHeaders(author, user) {
804
+ if (!author && !user) return;
805
+ const merged = new Headers(author);
806
+ new Headers(user).forEach((value, key) => {
807
+ merged.set(key, value);
808
+ });
809
+ if (merged.keys().next().done) return;
810
+ return merged;
811
+ }
812
+ //#endregion
813
+ //#region ../fragno/dist/client/internal/ndjson-streaming.js
814
+ /**
815
+ * Creates a promise that rejects when the abort signal is triggered
816
+ */
817
+ function createAbortPromise(abortSignal) {
818
+ return new Promise((_, reject) => {
819
+ const abortHandler = () => {
820
+ reject(new FragnoClientFetchAbortError("Operation was aborted"));
821
+ };
822
+ if (abortSignal.aborted) abortHandler();
823
+ else abortSignal.addEventListener("abort", abortHandler, { once: true });
824
+ });
825
+ }
826
+ const parseNdjsonBuffer = (buffer, options) => {
827
+ const lines = buffer.split("\n");
828
+ const trailingBuffer = options.flush ? "" : lines.pop() ?? "";
829
+ for (let index = 0; index < lines.length; index += 1) {
830
+ const line = lines[index];
831
+ if (!line.trim()) continue;
832
+ let jsonObject;
833
+ try {
834
+ jsonObject = JSON.parse(line);
835
+ } catch (parseError) {
836
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", options.parseErrorStatus, { cause: parseError });
837
+ }
838
+ if (options.onItem(jsonObject) === false) {
839
+ const remainingLines = lines.slice(index + 1);
840
+ return {
841
+ stopped: true,
842
+ buffer: remainingLines.length > 0 ? `${remainingLines.join("\n")}\n${trailingBuffer}` : trailingBuffer
843
+ };
844
+ }
845
+ }
846
+ return {
847
+ stopped: false,
848
+ buffer: trailingBuffer
849
+ };
850
+ };
851
+ /**
852
+ * Handles NDJSON streaming responses by returning the first item from the fetcher
853
+ * and then continuing to stream updates via the store's mutate method.
854
+ *
855
+ * This makes it so that we can wait until the first chunk before updating the store, if we did
856
+ * not do this, `loading` would briefly be false before the first item would be populated in the
857
+ * result.
858
+ *
859
+ * @param response - The fetch Response object containing the NDJSON stream
860
+ * @param store - The fetcher store to update with streaming data
861
+ * @param abortSignal - Optional AbortSignal to cancel the streaming operation
862
+ * @returns A promise that resolves to an object containing the first item and a streaming promise
863
+ */
864
+ async function handleNdjsonStreamingFirstItem(response, store, options = {}) {
865
+ if (!response.body) throw new FragnoClientFetchError("Streaming response has no body", "NO_BODY");
866
+ const { abortSignal } = options;
867
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
868
+ const decoder = new TextDecoder();
869
+ const reader = response.body.getReader();
870
+ let buffer = "";
871
+ let firstItem = null;
872
+ const items = [];
873
+ try {
874
+ while (firstItem === null) {
875
+ if (abortSignal?.aborted) {
876
+ reader.releaseLock();
877
+ throw new FragnoClientFetchAbortError("Operation was aborted");
878
+ }
879
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
880
+ if (done) break;
881
+ buffer += decoder.decode(value, { stream: true });
882
+ buffer = parseNdjsonBuffer(buffer, {
883
+ parseErrorStatus: 500,
884
+ onItem: (jsonObject) => {
885
+ items.push(jsonObject);
886
+ firstItem = jsonObject;
887
+ return false;
888
+ }
889
+ }).buffer;
890
+ if (firstItem !== null) {
891
+ const streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);
892
+ return {
893
+ firstItem,
894
+ items,
895
+ streamingPromise
896
+ };
897
+ }
898
+ }
899
+ if (firstItem === null) {
900
+ reader.releaseLock();
901
+ throw new FragnoClientUnknownApiError("NDJSON stream contained no valid items", 500);
902
+ }
903
+ reader.releaseLock();
904
+ throw new FragnoClientFetchError("Unexpected end of stream processing", "NO_BODY");
905
+ } catch (error) {
906
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
907
+ store?.setError(error);
908
+ throw error;
909
+ }
910
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 500, { cause: error });
911
+ store?.setError(clientError);
912
+ throw clientError;
913
+ }
914
+ }
915
+ /**
916
+ * Continues streaming the remaining items in the background
917
+ */
918
+ async function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {
919
+ let buffer = initialBuffer;
920
+ const appendItem = (jsonObject) => {
921
+ items.push(jsonObject);
922
+ store?.setData([...items]);
923
+ };
924
+ try {
925
+ while (true) {
926
+ buffer = parseNdjsonBuffer(buffer, {
927
+ parseErrorStatus: 400,
928
+ onItem: appendItem
929
+ }).buffer;
930
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
931
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
932
+ if (done) {
933
+ parseNdjsonBuffer(buffer, {
934
+ flush: true,
935
+ parseErrorStatus: 400,
936
+ onItem: appendItem
937
+ });
938
+ break;
939
+ }
940
+ buffer += decoder.decode(value, { stream: true });
941
+ }
942
+ } catch (error) {
943
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
944
+ store?.setError(error);
945
+ throw error;
946
+ }
947
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 400, { cause: error });
948
+ store?.setError(clientError);
949
+ throw clientError;
950
+ } finally {
951
+ reader.releaseLock();
952
+ }
953
+ return items;
954
+ }
955
+ //#endregion
956
+ //#region ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
957
+ let createNanoEvents = () => ({
958
+ emit(event, ...args) {
959
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) callbacks[i](...args);
960
+ },
961
+ events: {},
962
+ on(event, cb) {
963
+ (this.events[event] ||= []).push(cb);
964
+ return () => {
965
+ this.events[event] = this.events[event]?.filter((i) => cb !== i);
966
+ };
967
+ }
968
+ });
969
+ //#endregion
970
+ //#region ../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.3.0/node_modules/@nanostores/query/dist/nanoquery.js
971
+ function defaultOnErrorRetry({ retryCount }) {
972
+ return ~~((Math.random() + .5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;
973
+ }
974
+ const nanoqueryFactory = ([isAppVisible, visibilityChangeSubscribe, reconnectChangeSubscribe]) => {
975
+ const nanoquery = ({ cache = /* @__PURE__ */ new Map(), fetcher: globalFetcher, ...globalSettings } = {}) => {
976
+ const events = createNanoEvents();
977
+ let focus = true;
978
+ visibilityChangeSubscribe(() => {
979
+ focus = isAppVisible();
980
+ focus && events.emit(FOCUS);
981
+ });
982
+ reconnectChangeSubscribe(() => events.emit(RECONNECT));
983
+ const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();
984
+ let rewrittenSettings = {};
985
+ const getCachedValueByKey = (key) => {
986
+ const fromCache = cache.get(key);
987
+ if (!fromCache) return [];
988
+ return (fromCache.expires || 0) > getNow() ? [fromCache.data, fromCache.error] : [];
989
+ };
990
+ const runFetcher = async ([key, keyParts], store, settings) => {
991
+ if (!focus) return;
992
+ const set = (v) => {
993
+ if (store.key === key) {
994
+ store.set(v);
995
+ events.emit(SET_CACHE, key, v, true);
996
+ }
997
+ };
998
+ const setAsLoading = (prev) => {
999
+ set({
1000
+ ...prev === void 0 ? {} : { data: prev },
1001
+ ...loading,
1002
+ promise: _runningFetches.get(key)
1003
+ });
1004
+ };
1005
+ let { dedupeTime = 4e3, cacheLifetime = Infinity, fetcher, onErrorRetry = defaultOnErrorRetry } = {
1006
+ ...settings,
1007
+ ...rewrittenSettings
1008
+ };
1009
+ if (cacheLifetime < dedupeTime) cacheLifetime = dedupeTime;
1010
+ const now = getNow();
1011
+ if (_runningFetches.has(key)) {
1012
+ if (!store.value.loading) setAsLoading(getCachedValueByKey(key)[0]);
1013
+ return;
1014
+ }
1015
+ let cachedValue, cachedError;
1016
+ const fromCache = cache.get(key);
1017
+ if (fromCache?.data !== void 0 || fromCache?.error) {
1018
+ [cachedValue, cachedError] = getCachedValueByKey(key);
1019
+ if ((fromCache.created || 0) + dedupeTime > now) {
1020
+ if (store.value.data != cachedValue || store.value.error != cachedError) set({
1021
+ ...notLoading,
1022
+ data: cachedValue,
1023
+ error: cachedError
1024
+ });
1025
+ return;
1026
+ }
1027
+ }
1028
+ const finishTask = startTask();
1029
+ try {
1030
+ clearTimeout(_errorInvalidateTimeouts.get(key));
1031
+ const promise = fetcher(...keyParts);
1032
+ _runningFetches.set(key, promise);
1033
+ setAsLoading(cachedValue);
1034
+ const res = await promise;
1035
+ cache.set(key, {
1036
+ data: res,
1037
+ created: getNow(),
1038
+ expires: getNow() + cacheLifetime
1039
+ });
1040
+ set({
1041
+ data: res,
1042
+ ...notLoading
1043
+ });
1044
+ } catch (error) {
1045
+ settings.onError?.(error);
1046
+ const retryCount = (cache.get(key)?.retryCount || 0) + 1;
1047
+ cache.set(key, {
1048
+ error,
1049
+ created: getNow(),
1050
+ expires: getNow() + cacheLifetime,
1051
+ retryCount
1052
+ });
1053
+ if (onErrorRetry) {
1054
+ const timer = onErrorRetry({
1055
+ error,
1056
+ key,
1057
+ retryCount
1058
+ });
1059
+ if (timer) _errorInvalidateTimeouts.set(key, setTimeout(() => {
1060
+ invalidateKeys(key);
1061
+ cache.set(key, { retryCount });
1062
+ }, timer));
1063
+ }
1064
+ set({
1065
+ data: store.value.data,
1066
+ error,
1067
+ ...notLoading
1068
+ });
1069
+ } finally {
1070
+ finishTask();
1071
+ _runningFetches.delete(key);
1072
+ }
1073
+ };
1074
+ const createFetcherStore = (keyInput, { fetcher = globalFetcher, ...fetcherSettings } = {}) => {
1075
+ if (!fetcher) throw new Error("You need to set up either global fetcher of fetcher in createFetcherStore");
1076
+ const fetcherStore = map({ ...notLoading }), settings = {
1077
+ ...globalSettings,
1078
+ ...fetcherSettings,
1079
+ fetcher
1080
+ };
1081
+ fetcherStore._ = fetcherSymbol;
1082
+ fetcherStore.invalidate = () => {
1083
+ const { key } = fetcherStore;
1084
+ if (key) invalidateKeys(key);
1085
+ };
1086
+ fetcherStore.revalidate = () => {
1087
+ const { key } = fetcherStore;
1088
+ if (key) revalidateKeys(key);
1089
+ };
1090
+ fetcherStore.mutate = (data) => {
1091
+ const { key } = fetcherStore;
1092
+ if (key) mutateCache(key, data);
1093
+ };
1094
+ fetcherStore.fetch = async () => {
1095
+ let resolve;
1096
+ const promise = new Promise((r) => resolve = r);
1097
+ const unsub = fetcherStore.listen(({ error, data }) => {
1098
+ if (error !== void 0) resolve({ error });
1099
+ if (data !== void 0) resolve({ data });
1100
+ });
1101
+ return promise.finally(unsub);
1102
+ };
1103
+ let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;
1104
+ let evtUnsubs = [];
1105
+ onStart(fetcherStore, () => {
1106
+ const firstRun = !keysInternalUnsub;
1107
+ [keyStore, keysInternalUnsub] = getKeyStore(keyInput);
1108
+ keyUnsub = keyStore.subscribe((currentKeys) => {
1109
+ if (currentKeys) {
1110
+ const [newKey, keyParts] = currentKeys;
1111
+ fetcherStore.key = newKey;
1112
+ runFetcher([newKey, keyParts], fetcherStore, settings);
1113
+ prevKey = newKey;
1114
+ prevKeyParts = keyParts;
1115
+ } else {
1116
+ fetcherStore.key = prevKey = prevKeyParts = void 0;
1117
+ fetcherStore.set({ ...notLoading });
1118
+ }
1119
+ });
1120
+ const currentKeyValue = keyStore.get();
1121
+ if (currentKeyValue) {
1122
+ [prevKey, prevKeyParts] = currentKeyValue;
1123
+ if (firstRun) handleNewListener();
1124
+ }
1125
+ const { revalidateInterval = 0, revalidateOnFocus, revalidateOnReconnect } = settings;
1126
+ const runRefetcher = () => {
1127
+ if (prevKey) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1128
+ };
1129
+ if (revalidateInterval > 0) _revalidateOnInterval.set(keyInput, setInterval(runRefetcher, revalidateInterval));
1130
+ if (revalidateOnFocus) evtUnsubs.push(events.on(FOCUS, runRefetcher));
1131
+ if (revalidateOnReconnect) evtUnsubs.push(events.on(RECONNECT, runRefetcher));
1132
+ const cacheKeyChangeHandler = (keySelector) => {
1133
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1134
+ };
1135
+ evtUnsubs.push(events.on(INVALIDATE_KEYS, cacheKeyChangeHandler), events.on(REVALIDATE_KEYS, cacheKeyChangeHandler), events.on(SET_CACHE, (keySelector, data, full) => {
1136
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) fetcherStore.set(full ? data : {
1137
+ data,
1138
+ ...notLoading
1139
+ });
1140
+ }));
1141
+ });
1142
+ const handleNewListener = () => {
1143
+ if (prevKey && prevKeyParts) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1144
+ };
1145
+ const originListen = fetcherStore.listen;
1146
+ fetcherStore.listen = (listener) => {
1147
+ const unsub = originListen(listener);
1148
+ listener(fetcherStore.value);
1149
+ handleNewListener();
1150
+ return unsub;
1151
+ };
1152
+ onStop(fetcherStore, () => {
1153
+ fetcherStore.value = { ...notLoading };
1154
+ keysInternalUnsub?.();
1155
+ evtUnsubs.forEach((fn) => fn());
1156
+ evtUnsubs = [];
1157
+ keyUnsub?.();
1158
+ clearInterval(_revalidateOnInterval.get(keyInput));
1159
+ });
1160
+ return fetcherStore;
1161
+ };
1162
+ const iterOverCache = (keySelector, cb) => {
1163
+ for (const key of cache.keys()) if (testKeyAgainstSelector(key, keySelector)) cb(key);
1164
+ };
1165
+ const invalidateKeys = (keySelector) => {
1166
+ iterOverCache(keySelector, (key) => {
1167
+ cache.delete(key);
1168
+ });
1169
+ events.emit(INVALIDATE_KEYS, keySelector);
1170
+ };
1171
+ const revalidateKeys = (keySelector) => {
1172
+ iterOverCache(keySelector, (key) => {
1173
+ const cached = cache.get(key);
1174
+ if (cached) cache.set(key, {
1175
+ ...cached,
1176
+ created: -Infinity
1177
+ });
1178
+ });
1179
+ events.emit(REVALIDATE_KEYS, keySelector);
1180
+ };
1181
+ const mutateCache = (keySelector, data) => {
1182
+ iterOverCache(keySelector, (key) => {
1183
+ if (data === void 0) cache.delete(key);
1184
+ else cache.set(key, {
1185
+ data,
1186
+ created: getNow(),
1187
+ expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)
1188
+ });
1189
+ });
1190
+ events.emit(SET_CACHE, keySelector, data);
1191
+ };
1192
+ function createMutatorStore(mutator, opts) {
1193
+ const { throttleCalls, onError } = opts ?? {
1194
+ throttleCalls: true,
1195
+ onError: globalSettings?.onError
1196
+ };
1197
+ const mutate = async (data) => {
1198
+ if (throttleCalls && store.value?.loading) return;
1199
+ const newMutator = rewrittenSettings.fetcher ?? mutator;
1200
+ const keysToInvalidate = [], keysToRevalidate = [];
1201
+ const safeKeySet = (k, v) => {
1202
+ if (store.lc) store.setKey(k, v);
1203
+ };
1204
+ try {
1205
+ store.set({
1206
+ error: void 0,
1207
+ data: void 0,
1208
+ mutate,
1209
+ ...loading
1210
+ });
1211
+ const result = await newMutator({
1212
+ data,
1213
+ invalidate: (key) => {
1214
+ keysToInvalidate.push(key);
1215
+ },
1216
+ revalidate: (key) => {
1217
+ keysToRevalidate.push(key);
1218
+ },
1219
+ getCacheUpdater: (key, shouldRevalidate = true) => [(newVal) => {
1220
+ mutateCache(key, newVal);
1221
+ if (shouldRevalidate) keysToRevalidate.push(key);
1222
+ }, cache.get(key)?.data]
1223
+ });
1224
+ safeKeySet("data", result);
1225
+ return result;
1226
+ } catch (error) {
1227
+ onError?.(error);
1228
+ safeKeySet("error", error);
1229
+ store.setKey("error", error);
1230
+ } finally {
1231
+ safeKeySet("loading", false);
1232
+ keysToInvalidate.forEach(invalidateKeys);
1233
+ keysToRevalidate.forEach(revalidateKeys);
1234
+ }
1235
+ };
1236
+ const store = map({
1237
+ mutate,
1238
+ ...notLoading
1239
+ });
1240
+ onStop(store, () => store.set({
1241
+ mutate,
1242
+ ...notLoading
1243
+ }));
1244
+ store.mutate = mutate;
1245
+ return store;
1246
+ }
1247
+ const __unsafeOverruleSettings = (data) => {
1248
+ console.warn(`You should only use __unsafeOverruleSettings in test environment`);
1249
+ rewrittenSettings = data;
1250
+ };
1251
+ return [
1252
+ createFetcherStore,
1253
+ createMutatorStore,
1254
+ {
1255
+ __unsafeOverruleSettings,
1256
+ invalidateKeys,
1257
+ revalidateKeys,
1258
+ mutateCache
1259
+ }
1260
+ ];
1261
+ };
1262
+ function isSomeKey(key) {
1263
+ return typeof key === "string" || typeof key === "number" || key === true;
1264
+ }
1265
+ const getKeyStore = (keys) => {
1266
+ if (isSomeKey(keys)) return [atom(["" + keys, [keys]]), () => {}];
1267
+ const keyParts = [];
1268
+ const $key = atom(null);
1269
+ const keysAsStoresToIndexes = /* @__PURE__ */ new Map();
1270
+ const setKeyStoreValue = () => {
1271
+ if (keyParts.some((v) => v === null || v === void 0 || v === false)) $key.set(null);
1272
+ else $key.set([keyParts.join(""), keyParts]);
1273
+ };
1274
+ for (let i = 0; i < keys.length; i++) {
1275
+ const keyOrStore = keys[i];
1276
+ if (isSomeKey(keyOrStore)) keyParts.push(keyOrStore);
1277
+ else {
1278
+ keyParts.push(null);
1279
+ keysAsStoresToIndexes.set(keyOrStore, i);
1280
+ }
1281
+ }
1282
+ const storesAsArray = [...keysAsStoresToIndexes.keys()];
1283
+ const $storeKeys = batched(storesAsArray, (...storeValues) => {
1284
+ for (let i = 0; i < storeValues.length; i++) {
1285
+ const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);
1286
+ keyParts[partIndex] = store._ === fetcherSymbol ? store.value && "data" in store.value ? store.key : null : storeValues[i];
1287
+ }
1288
+ setKeyStoreValue();
1289
+ });
1290
+ setKeyStoreValue();
1291
+ return [$key, $storeKeys.subscribe(noop)];
1292
+ };
1293
+ function noop() {}
1294
+ const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;
1295
+ const testKeyAgainstSelector = (key, selector) => {
1296
+ if (Array.isArray(selector)) return selector.includes(key);
1297
+ else if (typeof selector === "function") return selector(key);
1298
+ else return key === selector;
1299
+ };
1300
+ const getNow = () => (/* @__PURE__ */ new Date()).getTime();
1301
+ const fetcherSymbol = Symbol();
1302
+ const loading = { loading: true }, notLoading = { loading: false };
1303
+ return nanoquery;
1304
+ };
1305
+ const subscribe = (name, fn) => {
1306
+ if (!(typeof window === "undefined")) addEventListener(name, fn);
1307
+ };
1308
+ const nanoquery = nanoqueryFactory([
1309
+ () => !document.hidden,
1310
+ (cb) => subscribe("visibilitychange", cb),
1311
+ (cb) => subscribe("online", cb)
1312
+ ]);
1313
+ //#endregion
1314
+ //#region ../fragno/dist/client/client.js
1315
+ /**
1316
+ * Symbols used to identify hook types
1317
+ */
1318
+ const GET_HOOK_SYMBOL = Symbol("fragno-get-hook");
1319
+ const MUTATOR_HOOK_SYMBOL = Symbol("fragno-mutator-hook");
1320
+ const STORE_SYMBOL = Symbol("fragno-store");
1321
+ async function schemaAllowsUndefined(schema) {
1322
+ try {
1323
+ return !(await schema["~standard"].validate(void 0)).issues;
1324
+ } catch {
1325
+ return false;
1326
+ }
1327
+ }
1328
+ async function assertBodyProvided(body, inputSchema, errorMessage) {
1329
+ if (typeof body !== "undefined" || inputSchema === void 0) return;
1330
+ if (await schemaAllowsUndefined(inputSchema)) return;
1331
+ throw new Error(errorMessage);
1332
+ }
1333
+ /**
1334
+ * Merge request headers from multiple sources.
1335
+ * Returns undefined if there are no headers to merge.
1336
+ * @internal
1337
+ */
1338
+ function mergeRequestHeaders(...headerSources) {
1339
+ const result = {};
1340
+ let hasHeaders = false;
1341
+ for (const source of headerSources) {
1342
+ if (!source) continue;
1343
+ if (source instanceof Headers) for (const [key, value] of source.entries()) {
1344
+ result[key] = value;
1345
+ hasHeaders = true;
1346
+ }
1347
+ else if (Array.isArray(source)) for (const [key, value] of source) {
1348
+ result[key] = value;
1349
+ hasHeaders = true;
1350
+ }
1351
+ else for (const [key, value] of Object.entries(source)) {
1352
+ result[key] = value;
1353
+ hasHeaders = true;
1354
+ }
1355
+ }
1356
+ return hasHeaders ? result : void 0;
1357
+ }
1358
+ /**
1359
+ * @internal
1360
+ */
1361
+ function buildUrl(config, params) {
1362
+ const { baseUrl = "", mountRoute, path } = config;
1363
+ const { pathParams, queryParams } = params ?? {};
1364
+ const normalizedPathParams = unwrapObject(pathParams);
1365
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1366
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1367
+ const searchParams = new URLSearchParams(filteredQueryParams);
1368
+ return `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
1369
+ }
1370
+ /**
1371
+ * This method returns an array, which can be passed directly to nanostores.
1372
+ *
1373
+ * The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)
1374
+ * Missing pathParams are replaced with "<missing>".
1375
+ * Atoms with undefined values are wrapped in computed atoms that map undefined to "" to avoid nanoquery treating the key as incomplete.
1376
+ * @param path
1377
+ * @param params
1378
+ * @returns
1379
+ * @internal
1380
+ */
1381
+ function getCacheKey(method, path, params) {
1382
+ if (!params) return [method, path];
1383
+ const { pathParams, queryParams } = params;
1384
+ const pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? "<missing>");
1385
+ const queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {
1386
+ const value = queryParams[key];
1387
+ if (value && typeof value === "object" && "get" in value) return computed(value, (v) => v ?? "");
1388
+ return value ?? "";
1389
+ }) : [];
1390
+ return [
1391
+ method,
1392
+ path,
1393
+ ...pathParamValues,
1394
+ ...queryParamValues
1395
+ ];
1396
+ }
1397
+ function isStreamingResponse(response) {
1398
+ const contentType = parseContentType(response.headers.get("content-type"));
1399
+ if (!contentType) return false;
1400
+ if (!(response.headers.get("transfer-encoding") === "chunked")) return false;
1401
+ if (contentType.subtype === "octet-stream") return "octet-stream";
1402
+ if (contentType.subtype === "x-ndjson") return "ndjson";
1403
+ return false;
1404
+ }
1405
+ /**
1406
+ * @internal
1407
+ */
1408
+ function isGetHook(hook) {
1409
+ return typeof hook === "object" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;
1410
+ }
1411
+ /**
1412
+ * @internal
1413
+ */
1414
+ function isMutatorHook(hook) {
1415
+ return typeof hook === "object" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;
1416
+ }
1417
+ /**
1418
+ * @internal
1419
+ */
1420
+ function isStore(obj) {
1421
+ return typeof obj === "object" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;
1422
+ }
1423
+ var ClientBuilder = class {
1424
+ #publicConfig;
1425
+ #fragmentConfig;
1426
+ #fetcherConfig;
1427
+ #cache = /* @__PURE__ */ new Map();
1428
+ #createFetcherStore;
1429
+ #createMutatorStore;
1430
+ #invalidateKeys;
1431
+ constructor(publicConfig, fragmentConfig) {
1432
+ this.#publicConfig = publicConfig;
1433
+ this.#fragmentConfig = fragmentConfig;
1434
+ this.#fetcherConfig = publicConfig.fetcherConfig;
1435
+ const [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({
1436
+ cache: this.#cache,
1437
+ cacheLifetime: Infinity
1438
+ });
1439
+ this.#createFetcherStore = createFetcherStore;
1440
+ this.#createMutatorStore = createMutatorStore;
1441
+ this.#invalidateKeys = invalidateKeys;
1442
+ }
1443
+ get cacheEntries() {
1444
+ return Object.fromEntries(this.#cache.entries());
1445
+ }
1446
+ createStore(input) {
1447
+ if (typeof input === "function") return {
1448
+ factory: input,
1449
+ [STORE_SYMBOL]: true
1450
+ };
1451
+ return {
1452
+ obj: input,
1453
+ [STORE_SYMBOL]: true
1454
+ };
1455
+ }
1456
+ /**
1457
+ * Build a URL for a custom backend call using the configured baseUrl and mountRoute.
1458
+ * Useful for fragment authors who need to make custom fetch calls.
1459
+ */
1460
+ buildUrl(path, params) {
1461
+ return buildUrl({
1462
+ baseUrl: this.#publicConfig.baseUrl ?? "",
1463
+ mountRoute: getMountRoute({
1464
+ name: this.#fragmentConfig.name,
1465
+ mountRoute: this.#publicConfig.mountRoute
1466
+ }),
1467
+ path
1468
+ }, {
1469
+ pathParams: params?.path,
1470
+ queryParams: params?.query
1471
+ });
1472
+ }
1473
+ /**
1474
+ * Get the configured fetcher function for custom backend calls.
1475
+ * Returns fetch with merged options applied.
1476
+ */
1477
+ getFetcher() {
1478
+ return {
1479
+ fetcher: this.#getFetcher(),
1480
+ defaultOptions: this.#getFetcherOptions()
1481
+ };
1482
+ }
1483
+ #getFetcher() {
1484
+ if (this.#fetcherConfig?.type === "function") return this.#fetcherConfig.fetcher;
1485
+ return globalThis.fetch.bind(globalThis);
1486
+ }
1487
+ #getFetcherOptions() {
1488
+ if (this.#fetcherConfig?.type === "options") return this.#fetcherConfig.options;
1489
+ }
1490
+ createHook(path, options) {
1491
+ const route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === "GET" && r.outputSchema !== void 0);
1492
+ if (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);
1493
+ return this.#createRouteQueryHook(route, options);
1494
+ }
1495
+ createMutator(method, path, onInvalidate) {
1496
+ const route = this.#fragmentConfig.routes.find((r) => r.method !== "GET" && r.path === path && r.method === method);
1497
+ if (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);
1498
+ return this.#createRouteQueryMutator(route, onInvalidate);
1499
+ }
1500
+ #createRouteQueryHook(route, options = {}) {
1501
+ if (route.method !== "GET") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${String(route.method)} route.`);
1502
+ if (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);
1503
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1504
+ const mountRoute = getMountRoute({
1505
+ name: this.#fragmentConfig.name,
1506
+ mountRoute: this.#publicConfig.mountRoute
1507
+ });
1508
+ const fetcher = this.#getFetcher();
1509
+ const fetcherOptions = this.#getFetcherOptions();
1510
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1511
+ async function callServerSideHandler(params) {
1512
+ const { pathParams, queryParams } = params ?? {};
1513
+ const normalizedPathParams = unwrapObject(pathParams);
1514
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1515
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1516
+ const searchParams = new URLSearchParams(filteredQueryParams);
1517
+ return await route.handler(RequestInputContext.fromSSRContext({
1518
+ method: route.method,
1519
+ path: route.path,
1520
+ pathParams: normalizedPathParams,
1521
+ searchParams
1522
+ }), new RequestOutputContext(route.outputSchema));
1523
+ }
1524
+ async function executeQuery(params) {
1525
+ const { pathParams, queryParams } = params ?? {};
1526
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => callServerSideHandler({
1527
+ pathParams,
1528
+ queryParams
1529
+ }));
1530
+ const url = buildUrl({
1531
+ baseUrl,
1532
+ mountRoute,
1533
+ path: route.path
1534
+ }, {
1535
+ pathParams,
1536
+ queryParams
1537
+ });
1538
+ let response;
1539
+ try {
1540
+ response = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);
1541
+ } catch (error) {
1542
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1543
+ }
1544
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1545
+ return response;
1546
+ }
1547
+ return {
1548
+ route,
1549
+ store: (args) => {
1550
+ const { path, query } = args ?? {};
1551
+ const key = getCacheKey(route.method, route.path, {
1552
+ pathParams: path,
1553
+ queryParams: query
1554
+ });
1555
+ const store = this.#createFetcherStore(key, {
1556
+ fetcher: async () => {
1557
+ const response = await executeQuery({
1558
+ pathParams: path,
1559
+ queryParams: query
1560
+ });
1561
+ const isStreaming = isStreamingResponse(response);
1562
+ if (!isStreaming) return response.json();
1563
+ if (typeof window === "undefined" && !useFetcherOnServer) {
1564
+ if (response.body) await response.body.getReader().cancel();
1565
+ return [];
1566
+ }
1567
+ if (isStreaming === "ndjson") {
1568
+ const { items } = await handleNdjsonStreamingFirstItem(response, {
1569
+ setData: (value) => {
1570
+ store.mutate(value);
1571
+ },
1572
+ setError: (value) => {
1573
+ store.set({
1574
+ ...store.get(),
1575
+ error: value
1576
+ });
1577
+ }
1578
+ });
1579
+ return items;
1580
+ }
1581
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1582
+ throw new Error("Unreachable");
1583
+ },
1584
+ onErrorRetry: options?.onErrorRetry,
1585
+ dedupeTime: Infinity
1586
+ });
1587
+ if (typeof window === "undefined") addStore(store);
1588
+ return store;
1589
+ },
1590
+ query: async (args) => {
1591
+ const { path, query } = args ?? {};
1592
+ const response = await executeQuery({
1593
+ pathParams: path,
1594
+ queryParams: query
1595
+ });
1596
+ const isStreaming = isStreamingResponse(response);
1597
+ if (!isStreaming) return await response.json();
1598
+ if (isStreaming === "ndjson") {
1599
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1600
+ return await streamingPromise;
1601
+ }
1602
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1603
+ throw new Error("Unreachable");
1604
+ },
1605
+ [GET_HOOK_SYMBOL]: true
1606
+ };
1607
+ }
1608
+ #createRouteQueryMutator(route, onInvalidate = (invalidate, params) => {
1609
+ invalidate("GET", route.path, params);
1610
+ }) {
1611
+ const method = route.method;
1612
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1613
+ const mountRoute = getMountRoute({
1614
+ name: this.#fragmentConfig.name,
1615
+ mountRoute: this.#publicConfig.mountRoute
1616
+ });
1617
+ const fetcher = this.#getFetcher();
1618
+ const fetcherOptions = this.#getFetcherOptions();
1619
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1620
+ async function executeMutateQuery({ body, path, query }) {
1621
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => route.handler(RequestInputContext.fromSSRContext({
1622
+ inputSchema: route.inputSchema,
1623
+ method,
1624
+ path: route.path,
1625
+ pathParams: path ?? {},
1626
+ searchParams: new URLSearchParams(query),
1627
+ body
1628
+ }), new RequestOutputContext(route.outputSchema)));
1629
+ const url = buildUrl({
1630
+ baseUrl,
1631
+ mountRoute,
1632
+ path: route.path
1633
+ }, {
1634
+ pathParams: path,
1635
+ queryParams: query
1636
+ });
1637
+ let response;
1638
+ try {
1639
+ const preparedBody = prepareClientRequestBody(body, route.contentType);
1640
+ const bodyHeaders = preparedBody.contentType === void 0 || preparedBody.contentType === null ? void 0 : { "Content-Type": preparedBody.contentType };
1641
+ const headers = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);
1642
+ const requestOptions = createRequestInitWithBody(method, headers ?? {}, preparedBody.body, fetcherOptions);
1643
+ response = await fetcher(url, requestOptions);
1644
+ } catch (error) {
1645
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1646
+ }
1647
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1648
+ return response;
1649
+ }
1650
+ const mutatorStore = this.#createMutatorStore(async ({ data }) => {
1651
+ if (typeof window === "undefined") {}
1652
+ const { body, path, query } = data;
1653
+ await assertBodyProvided(body, route.inputSchema, "Body is required.");
1654
+ const response = await executeMutateQuery({
1655
+ body,
1656
+ path,
1657
+ query
1658
+ });
1659
+ onInvalidate(this.#invalidate.bind(this), {
1660
+ pathParams: path ?? {},
1661
+ queryParams: query
1662
+ });
1663
+ if (response.status === 201 || response.status === 204) return;
1664
+ const isStreaming = isStreamingResponse(response);
1665
+ if (!isStreaming) return await response.json();
1666
+ if (typeof window === "undefined") return [];
1667
+ if (isStreaming === "ndjson") {
1668
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1669
+ setData: (value) => {
1670
+ mutatorStore.set({
1671
+ ...mutatorStore.get(),
1672
+ loading: !(Array.isArray(value) && value.length > 0),
1673
+ data: value
1674
+ });
1675
+ },
1676
+ setError: (value) => {
1677
+ mutatorStore.set({
1678
+ ...mutatorStore.get(),
1679
+ error: value
1680
+ });
1681
+ }
1682
+ });
1683
+ return [firstItem];
1684
+ }
1685
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1686
+ throw new Error("Unreachable");
1687
+ }, { onError: (error) => {
1688
+ console.error("Error in mutatorStore", error);
1689
+ } });
1690
+ const mutateQuery = async (data) => {
1691
+ const { body, path, query } = data;
1692
+ await assertBodyProvided(body, route.inputSchema, "Body is required for mutateQuery");
1693
+ const response = await executeMutateQuery({
1694
+ body,
1695
+ path,
1696
+ query
1697
+ });
1698
+ if (response.status === 201 || response.status === 204) return;
1699
+ const isStreaming = isStreamingResponse(response);
1700
+ if (!isStreaming) return await response.json();
1701
+ if (isStreaming === "ndjson") {
1702
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1703
+ return await streamingPromise;
1704
+ }
1705
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported for mutations");
1706
+ throw new Error("Unreachable");
1707
+ };
1708
+ return {
1709
+ route,
1710
+ mutateQuery,
1711
+ mutatorStore,
1712
+ [MUTATOR_HOOK_SYMBOL]: true
1713
+ };
1714
+ }
1715
+ #invalidate(method, path, params) {
1716
+ const prefix = getCacheKey(method, path, {
1717
+ pathParams: params?.pathParams,
1718
+ queryParams: params?.queryParams
1719
+ }).map((k) => typeof k === "string" ? k : k.get()).join("");
1720
+ this.#invalidateKeys((key) => key.startsWith(prefix));
1721
+ }
1722
+ };
1723
+ /**
1724
+ * Create a client builder for fragments using the new fragment definition API.
1725
+ * This is the same as createClientBuilder but works with FragmentDefinition.
1726
+ */
1727
+ function createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {
1728
+ const routes = resolveRouteFactories({
1729
+ config: {},
1730
+ deps: {},
1731
+ services: {},
1732
+ serviceDeps: {}
1733
+ }, routesOrFactories);
1734
+ const fragmentConfig = {
1735
+ name: definition.name,
1736
+ routes
1737
+ };
1738
+ const mountRoute = getMountRoute({
1739
+ name: definition.name,
1740
+ mountRoute: publicConfig.mountRoute
1741
+ });
1742
+ const mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);
1743
+ return new ClientBuilder({
1744
+ ...publicConfig,
1745
+ mountRoute,
1746
+ fetcherConfig: mergedFetcherConfig
1747
+ }, fragmentConfig);
1748
+ }
1749
+ //#endregion
1750
+ //#region src/pi/definition.ts
1751
+ const piHarnessDefinition = defineFragment("pi-harness").extend((x) => x).usesService("workflows").providesBaseService(() => {}).build();
1752
+ //#endregion
1753
+ //#region src/routes.ts
1754
+ const piRoutesFactory = defineRoutes(piHarnessDefinition).create(({ config, defineRoute, serviceDeps, services }) => {
1755
+ if (config.logging) WorkflowsLogger.configure(config.logging);
1756
+ return [
1757
+ defineRoute({
1758
+ method: "POST",
1759
+ path: "/workflows/:workflowName/sessions",
1760
+ inputSchema: z.object({
1761
+ name: z.string().optional(),
1762
+ metadata: z.record(z.string(), z.unknown()).optional(),
1763
+ input: z.unknown().optional()
1764
+ }),
1765
+ outputSchema: sessionBaseSchema,
1766
+ errorCodes: [
1767
+ "WORKFLOW_NOT_FOUND",
1768
+ "WORKFLOW_PARAMS_INVALID",
1769
+ "WORKFLOW_CREATE_FAILED"
1770
+ ],
1771
+ handler: () => {}
1772
+ }),
1773
+ defineRoute({
1774
+ method: "GET",
1775
+ path: "/workflows/:workflowName/sessions",
1776
+ queryParameters: ["limit"],
1777
+ outputSchema: z.array(sessionBaseSchema),
1778
+ errorCodes: ["SESSION_DATA_INTEGRITY_ERROR"],
1779
+ handler: () => {}
1780
+ }),
1781
+ defineRoute({
1782
+ method: "GET",
1783
+ path: "/workflows/:workflowName/sessions/:sessionId",
1784
+ outputSchema: sessionDetailSchema,
1785
+ errorCodes: [
1786
+ "SESSION_NOT_FOUND",
1787
+ "SESSION_DATA_UNAVAILABLE",
1788
+ "SESSION_DATA_INTEGRITY_ERROR",
1789
+ "WORKFLOW_INSTANCE_MISSING"
1790
+ ],
1791
+ handler: () => {}
1792
+ }),
1793
+ defineRoute({
1794
+ method: "GET",
1795
+ path: "/workflows/:workflowName/sessions/:sessionId/export/pi-jsonl",
1796
+ errorCodes: [
1797
+ "SESSION_NOT_FOUND",
1798
+ "SESSION_DATA_UNAVAILABLE",
1799
+ "SESSION_DATA_INTEGRITY_ERROR",
1800
+ "WORKFLOW_INSTANCE_MISSING"
1801
+ ],
1802
+ handler: () => {}
1803
+ }),
1804
+ defineRoute({
1805
+ method: "GET",
1806
+ path: "/workflows/:workflowName/sessions/:sessionId/commands/:commandId/wait",
1807
+ queryParameters: ["timeoutMs"],
1808
+ errorCodes: [
1809
+ "SESSION_NOT_FOUND",
1810
+ "WORKFLOW_INSTANCE_MISSING",
1811
+ "INVALID_COMMAND_ID",
1812
+ "COMMAND_NOT_WAITABLE",
1813
+ "COMMAND_STEP_TIMEOUT",
1814
+ "COMMAND_STEP_FAILED",
1815
+ "COMMAND_WORKFLOW_TERMINAL"
1816
+ ],
1817
+ handler: () => {}
1818
+ }),
1819
+ defineRoute({
1820
+ method: "POST",
1821
+ path: "/workflows/:workflowName/sessions/:sessionId/command",
1822
+ inputSchema: commandInputSchema,
1823
+ outputSchema: commandAckSchema,
1824
+ errorCodes: ["SESSION_NOT_FOUND", "WORKFLOW_INSTANCE_MISSING"],
1825
+ handler: () => {}
1826
+ })
1827
+ ];
1828
+ });
1829
+ //#endregion
1830
+ //#region src/client/clients.ts
1831
+ function createPiFragmentClients(fragnoConfig = {}) {
1832
+ const builder = createClientBuilder(piHarnessDefinition, fragnoConfig, [piRoutesFactory]);
1833
+ const useCommandSession = builder.createMutator("POST", "/workflows/:workflowName/sessions/:sessionId/command", (invalidate, params) => {
1834
+ const workflowName = params.pathParams.workflowName;
1835
+ const sessionId = params.pathParams.sessionId;
1836
+ if (!workflowName || !sessionId) return;
1837
+ invalidate("GET", "/workflows/:workflowName/sessions/:sessionId", { pathParams: {
1838
+ workflowName,
1839
+ sessionId
1840
+ } });
1841
+ invalidate("GET", "/workflows/:workflowName/sessions", { pathParams: { workflowName } });
1842
+ });
1843
+ return {
1844
+ useSessions: builder.createHook("/workflows/:workflowName/sessions"),
1845
+ useSessionDetail: builder.createHook("/workflows/:workflowName/sessions/:sessionId"),
1846
+ useCreateSession: builder.createMutator("POST", "/workflows/:workflowName/sessions"),
1847
+ useCommandSession
1848
+ };
1849
+ }
1850
+ //#endregion
1851
+ export { isReadableAtom as a, isStore as i, isGetHook as n, isMutatorHook as r, createPiFragmentClients as t };
1852
+
1853
+ //# sourceMappingURL=clients-pIAk6ClP.js.map