@fragno-dev/forms 0.0.1 → 0.0.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"src-DElBPLyi.js","names":["resolveRouteFactories","context","routesOrFactories","routes","item","factoryRoutes","push","defineRoute","config","defineRoutes","_definition","create","fn","ctx","getMountRoute","opts","mountRoute","name","endsWith","slice","FragnoApiError","Error","status","code","constructor","message","name","toResponse","Response","json","FragnoApiValidationError","issues","FragnoApiValidationError","RequestInputContext","path","method","pathParams","searchParams","headers","body","parsedBody","inputSchema","shouldValidateInput","constructor","config","rawBody","fromRequest","state","fromSSRContext","URLSearchParams","Headers","query","input","schema","valid","validateInput","#validateInput","Error","FormData","Blob","result","validate","issues","value","ResponseStream","writer","encoder","abortSubscribers","responseReadable","aborted","closed","constructor","writable","readable","getWriter","TextEncoder","reader","getReader","push","cancel","ReadableStream","pull","controller","done","value","read","close","enqueue","abort","writeRaw","input","encode","write","JSON","stringify","sleep","ms","Promise","res","setTimeout","onAbort","listener","forEach","subscriber","ResponseStream","mergeHeaders","headerSources","mergedHeaders","Headers","headerSource","key","value","entries","set","Array","isArray","Object","OutputContext","error","message","code","initOrStatus","headers","Response","json","status","empty","defaultHeaders","mergedHeaders$1","object","jsonStream","cb","onError","readable","writable","TransformStream","stream","e","Error","console","close","responseReadable","RequestOutputContext","outputSchema","constructor","extractPathParams","pathPattern","segments","split","filter","s","length","names","segment","startsWith","push","slice","buildPath","params","patternSegments","builtSegments","name","value","Error","encodeURIComponent","join","FragnoClientError","Error","code","constructor","message","options","cause","name","FragnoClientFetchError","fromUnknownFetchError","error","FragnoClientFetchNetworkError","FragnoClientFetchAbortError","FragnoClientUnknownApiError","status","FragnoClientApiError","fromResponse","response","unknown","json","parseContentType","contentType","trimmed","trim","parts","split","map","part","mediaType","typeParts","length","type","subtype","toLowerCase","parameters","i","param","equalIndex","indexOf","key","slice","value","startsWith","endsWith","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientUnknownApiError","createAbortPromise","abortSignal","Promise","_","reject","abortHandler","aborted","addEventListener","once","handleNdjsonStreamingFirstItem","response","store","options","body","decoder","TextDecoder","reader","getReader","buffer","firstItem","items","releaseLock","done","value","race","read","decode","stream","lines","split","pop","line","trim","jsonObject","JSON","parse","push","streamingPromise","continueStreaming","parseError","cause","error","setError","clientError","initialBuffer","lines$1","setData","tasks","resolves","startTask","prevResolves","i","task","cb","endTask","promise","finally","t","allTasks","Promise","resolve","push","cleanTasks","cleanTasks","clean","Symbol","cleanStores","stores","process","env","NODE_ENV","Error","$store","mocked","clean","listenerQueue","lqIndex","QUEUE_ITEMS_PER_LISTENER","epoch","atom","initialValue","listeners","$atom","get","lc","listen","value","listener","push","i","length","splice","index","indexOf","off","notify","oldValue","changedKey","runListenerQueue","set","newValue","subscribe","unbind","process","env","NODE_ENV","readonlyType","store","clean","START","STOP","SET","NOTIFY","MOUNT","UNMOUNT","REVERT_MUTATION","on","object","listener","eventKey","mutateStore","events","eventProps","reduceRight","event","l","shared","push","currentListeners","index","indexOf","splice","length","onStart","$store","runListeners","originListen","listen","arg","lc","starting","onStop","originOff","off","onSet","originSet","set","originSetKey","setKey","changed","changedValue","isAborted","abort","newValue","value","onNotify","originNotify","notify","oldValue","STORE_UNMOUNT_DELAY","onMount","initialize","payload","destroy","args","active","setTimeout","process","env","NODE_ENV","originClean","atom","epoch","onMount","computedStore","stores","cb","batched","Array","isArray","previousArgs","currentEpoch","set","args","map","$store","get","some","arg","i","value","then","t","asyncValue","$computed","undefined","timer","run","clearTimeout","setTimeout","unbinds","listen","unbind","computed","fn","atom","map","initial","$map","setKey","key","value","oldMap","notify","allTasks","stores","SSR_ENABLED","getStores","addStore","store","push","cleanStores","clientInitialData","hydrateFromWindow","window","__FRAGNO_INITIAL_DATA__","Map","console","warn","Array","from","entries","getInitialData","key","has","data","get","delete","listenToStores","listen","getFinalStoreValues","stores$1","storesInitialValue","value","loading","set","unwrapAtom","value","get","unwrapObject","params","Object","fromEntries","entries","map","key","isReadableAtom","lc","notify","off","subscribe","mergeFetcherConfigs","authorConfig","userConfig","type","authorOpts","options","userOpts","Object","keys","length","headers","mergeHeaders","author","user","merged","Headers","forEach","value","key","set","next","done","createNanoEvents","emit","event","args","callbacks","events","i","length","on","cb","push","filter","map","onStart","onStop","atom","batched","startTask","createNanoEvents","defaultOnErrorRetry","retryCount","Math","random","nanoqueryFactory","isAppVisible","visibilityChangeSubscribe","reconnectChangeSubscribe","nanoquery","cache","Map","fetcher","globalFetcher","globalSettings","events","focus","emit","FOCUS","RECONNECT","_revalidateOnInterval","_errorInvalidateTimeouts","_runningFetches","rewrittenSettings","getCachedValueByKey","key","fromCache","get","cacheHit","expires","getNow","data","error","runFetcher","keyParts","store","settings","set","v","SET_CACHE","setAsLoading","prev","toSet","loading","promise","dedupeTime","cacheLifetime","Infinity","onErrorRetry","now","has","value","cachedValue","cachedError","created","notLoading","finishTask","clearTimeout","res","onError","timer","setTimeout","invalidateKeys","delete","createFetcherStore","keyInput","fetcherSettings","process","env","NODE_ENV","Error","fetcherStore","_","fetcherSymbol","invalidate","revalidate","revalidateKeys","mutate","mutateCache","fetch","resolve","Promise","r","unsub","listen","finally","keysInternalUnsub","prevKey","prevKeyParts","keyUnsub","keyStore","evtUnsubs","firstRun","getKeyStore","subscribe","currentKeys","newKey","currentKeyValue","handleNewListener","revalidateInterval","revalidateOnFocus","revalidateOnReconnect","runRefetcher","setInterval","push","on","cacheKeyChangeHandler","keySelector","testKeyAgainstSelector","INVALIDATE_KEYS","REVALIDATE_KEYS","full","originListen","listener","forEach","fn","clearInterval","iterOverCache","cb","keys","cached","createMutatorStore","mutator","opts","throttleCalls","newMutator","keysToInvalidate","keysToRevalidate","safeKeySet","k","lc","setKey","result","getCacheUpdater","shouldRevalidate","newVal","__unsafeOverruleSettings","console","warn","isSomeKey","$key","keysAsStoresToIndexes","setKeyStoreValue","some","join","i","length","keyOrStore","storesAsArray","$storeKeys","storeValues","partIndex","noop","selector","Array","isArray","includes","Date","getTime","Symbol","name","isServer","window","addEventListener","browserCompat","document","hidden","resolveRouteFactories","getMountRoute","RequestInputContext","RequestOutputContext","buildPath","extractPathParams","FragnoClientApiError","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientFetchNetworkError","FragnoClientUnknownApiError","parseContentType","handleNdjsonStreamingFirstItem","SSR_ENABLED","addStore","getInitialData","unwrapObject","mergeFetcherConfigs","computed","task","nanoquery","GET_HOOK_SYMBOL","Symbol","MUTATOR_HOOK_SYMBOL","STORE_SYMBOL","buildUrl","config","params","baseUrl","mountRoute","path","pathParams","queryParams","normalizedPathParams","normalizedQueryParams","filteredQueryParams","Object","fromEntries","entries","filter","_","value","searchParams","URLSearchParams","toString","getCacheKey","method","pathParamValues","map","name","queryParamValues","keys","sort","key","v","isStreamingResponse","response","contentType","headers","get","subtype","isGetHook","hook","isMutatorHook","isStore","obj","ClientBuilder","publicConfig","fragmentConfig","fetcherConfig","cache","Map","createFetcherStore","createMutatorStore","invalidateKeys","constructor","cacheEntries","createStore","query","getFetcher","fetcher","defaultOptions","getFetcherOptions","#getFetcher","type","fetch","#getFetcherOptions","options","createHook","route","routes","find","r","outputSchema","Error","createRouteQueryHook","createMutator","onInvalidate","createRouteQueryMutator","#createRouteQueryHook","fetcherOptions","callServerSideHandler","handler","fromSSRContext","executeQuery","window","url","error","fromUnknownFetchError","ok","fromResponse","store","args","initialData","d","join","isStreaming","json","firstItem","setData","set","loading","Array","isArray","length","data","setError","onErrorRetry","dedupeTime","Infinity","streamingPromise","#createRouteQueryMutator","invalidate","executeMutateQuery","body","inputSchema","JSON","stringify","mutatorStore","bind","status","onError","console","mutateQuery","#invalidate","prefix","k","startsWith","createClientBuilder","definition","routesOrFactories","authorFetcherConfig","deps","services","serviceDeps","mergedFetcherConfig","defineFragment","FormsConfig","NewForm","UpdateForm","Schema","ValidatedData","Record","T","ValidationResult","success","data","error","message","errors","Array","path","SubmissionSortOptions","field","order","formsFragmentDef","extend","x","withDependencies","providesBaseService","build","z","JSONSchemaSchema","record","string","unknown","UISchemaElementSchema","FormStatusSchema","enum","FormSchema","object","id","title","description","nullable","slug","status","dataSchema","uiSchema","version","number","createdAt","date","updatedAt","NewFormSchema","omit","UpdateFormSchema","partial","ResponseMetadataSchema","ip","union","ipv4","ipv6","userAgent","max","ResponseSchema","formId","describe","formVersion","data","submittedAt","NewResponseSchema","extend","securityToken","optional","NewForm","infer","UpdateForm","Form","NewResponse","Response","ResponseMetadata","FormStatus","JSONSchema","UIElementSchema","defineRoutes","z","formsFragmentDef","FormSchema","NewFormSchema","NewResponseSchema","ResponseSchema","UpdateFormSchema","StaticForm","publicRoutes","create","services","defineRoute","config","method","path","outputSchema","errorCodes","const","handler","inputSchema","string","adminRoutes","array","queryParameters","createClientBuilder","FragnoPublicClientConfig","FragnoPublicConfig","publicRoutes","adminRoutes","formsFragmentDef","Form","JSONSchema","Response","UISchemaElement","StaticForm","id","title","description","slug","dataSchema","uiSchema","version","FormsConfig","onFormCreated","form","Omit","Promise","onResponseSubmitted","response","staticForms","routes","const","createFormsFragment","config","options","FragnoPublicConfigWithDatabase","createFormsClients","fragnoConfig","b","useForm","createHook","useSubmitForm","createMutator","useForms","useCreateForm","useUpdateForm","useDeleteForm","useSubmissions","useSubmission","useDeleteSubmission","SubmissionSortOptions","FragnoRouteConfig"],"sources":["../../../fragno/dist/api/route.js","../../../fragno/dist/api/internal/route.js","../../../fragno/dist/api/error.js","../../../fragno/dist/api/request-input-context.js","../../../fragno/dist/api/internal/response-stream.js","../../../fragno/dist/api/request-output-context.js","../../../fragno/dist/api/internal/path.js","../../../fragno/dist/client/client-error.js","../../../fragno/dist/util/content-type.js","../../../fragno/dist/client/internal/ndjson-streaming.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/task/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/clean-stores/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/atom/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/lifecycle/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/computed/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/map/index.js","../../../fragno/dist/util/ssr.js","../../../fragno/dist/util/nanostores.js","../../../fragno/dist/client/internal/fetcher-merge.js","../../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../../../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.1.0/node_modules/@nanostores/query/dist/nanoquery.js","../../../fragno/dist/client/client.js","../../src/definition.ts","../../src/models.ts","../../src/routes.ts","../../src/index.ts"],"sourcesContent":["//#region src/api/route.ts\n/**\n* Helper to resolve route factories into routes\n* @internal\n*/\nfunction resolveRouteFactories(context, routesOrFactories) {\n\tconst routes = [];\n\tfor (const item of routesOrFactories) if (typeof item === \"function\") {\n\t\tconst factoryRoutes = item(context);\n\t\troutes.push(...factoryRoutes);\n\t} else routes.push(item);\n\treturn routes;\n}\nfunction defineRoute(config) {\n\treturn config;\n}\nfunction defineRoutes(_definition) {\n\treturn { create: (fn) => {\n\t\treturn (ctx) => {\n\t\t\treturn fn({\n\t\t\t\t...ctx,\n\t\t\t\tdefineRoute\n\t\t\t});\n\t\t};\n\t} };\n}\n\n//#endregion\nexport { defineRoute, defineRoutes, resolveRouteFactories };\n//# sourceMappingURL=route.js.map","//#region src/api/internal/route.ts\nfunction getMountRoute(opts) {\n\tconst mountRoute = opts.mountRoute ?? `/api/${opts.name}`;\n\tif (mountRoute.endsWith(\"/\")) return mountRoute.slice(0, -1);\n\treturn mountRoute;\n}\n\n//#endregion\nexport { getMountRoute };\n//# sourceMappingURL=route.js.map","//#region src/api/error.ts\nvar FragnoApiError = class extends Error {\n\t#status;\n\t#code;\n\tconstructor({ message, code }, status) {\n\t\tsuper(message);\n\t\tthis.name = \"FragnoApiError\";\n\t\tthis.#status = status;\n\t\tthis.#code = code;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\nvar FragnoApiValidationError = class extends FragnoApiError {\n\t#issues;\n\tconstructor(message, issues) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tcode: \"FRAGNO_VALIDATION_ERROR\"\n\t\t}, 400);\n\t\tthis.name = \"FragnoApiValidationError\";\n\t\tthis.#issues = issues;\n\t}\n\tget issues() {\n\t\treturn this.#issues;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tissues: this.#issues,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\n\n//#endregion\nexport { FragnoApiError, FragnoApiValidationError };\n//# sourceMappingURL=error.js.map","import { FragnoApiValidationError } from \"./error.js\";\n\n//#region src/api/request-input-context.ts\nvar RequestInputContext = class RequestInputContext {\n\t#path;\n\t#method;\n\t#pathParams;\n\t#searchParams;\n\t#headers;\n\t#body;\n\t#parsedBody;\n\t#inputSchema;\n\t#shouldValidateInput;\n\tconstructor(config) {\n\t\tthis.#path = config.path;\n\t\tthis.#method = config.method;\n\t\tthis.#pathParams = config.pathParams;\n\t\tthis.#searchParams = config.searchParams;\n\t\tthis.#headers = config.headers;\n\t\tthis.#body = config.rawBody;\n\t\tthis.#parsedBody = config.parsedBody;\n\t\tthis.#inputSchema = config.inputSchema;\n\t\tthis.#shouldValidateInput = config.shouldValidateInput ?? true;\n\t}\n\t/**\n\t* Create a RequestContext from a Request object for server-side handling\n\t*/\n\tstatic async fromRequest(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.state.pathParams,\n\t\t\tsearchParams: config.state.searchParams,\n\t\t\theaders: config.state.headers,\n\t\t\tparsedBody: config.state.body,\n\t\t\trawBody: config.rawBody,\n\t\t\tinputSchema: config.inputSchema,\n\t\t\tshouldValidateInput: config.shouldValidateInput\n\t\t});\n\t}\n\t/**\n\t* Create a RequestContext for server-side rendering contexts (no Request object)\n\t*/\n\tstatic fromSSRContext(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.pathParams,\n\t\t\tsearchParams: config.searchParams ?? new URLSearchParams(),\n\t\t\theaders: config.headers ?? new Headers(),\n\t\t\tparsedBody: \"body\" in config ? config.body : void 0,\n\t\t\tinputSchema: \"inputSchema\" in config ? config.inputSchema : void 0,\n\t\t\tshouldValidateInput: false\n\t\t});\n\t}\n\t/**\n\t* The HTTP method as string (e.g., `GET`, `POST`)\n\t*/\n\tget method() {\n\t\treturn this.#method;\n\t}\n\t/**\n\t* The matched route path (e.g., `/users/:id`)\n\t* @remarks `string`\n\t*/\n\tget path() {\n\t\treturn this.#path;\n\t}\n\t/**\n\t* Extracted path parameters as object (e.g., `{ id: '123' }`)\n\t* @remarks `Record<string, string>`\n\t*/\n\tget pathParams() {\n\t\treturn this.#pathParams;\n\t}\n\t/**\n\t* [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters\n\t* @remarks `URLSearchParams`\n\t*/\n\tget query() {\n\t\treturn this.#searchParams;\n\t}\n\t/**\n\t* [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers\n\t* @remarks `Headers`\n\t*/\n\tget headers() {\n\t\treturn this.#headers;\n\t}\n\tget rawBody() {\n\t\treturn this.#body;\n\t}\n\t/**\n\t* Input validation context (only if inputSchema is defined)\n\t* @remarks `InputContext`\n\t*/\n\tget input() {\n\t\tif (!this.#inputSchema) return;\n\t\treturn {\n\t\t\tschema: this.#inputSchema,\n\t\t\tvalid: async () => {\n\t\t\t\tif (!this.#shouldValidateInput) return this.#parsedBody;\n\t\t\t\treturn this.#validateInput();\n\t\t\t}\n\t\t};\n\t}\n\tasync #validateInput() {\n\t\tif (!this.#inputSchema) throw new Error(\"No input schema defined for this route\");\n\t\tif (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error(\"Schema validation is only supported for JSON data, not FormData or Blob\");\n\t\tconst result = await this.#inputSchema[\"~standard\"].validate(this.#parsedBody);\n\t\tif (result.issues) throw new FragnoApiValidationError(\"Validation failed\", result.issues);\n\t\treturn result.value;\n\t}\n};\n\n//#endregion\nexport { RequestInputContext };\n//# sourceMappingURL=request-input-context.js.map","//#region src/api/internal/response-stream.ts\nvar ResponseStream = class {\n\t#writer;\n\t#encoder;\n\t#abortSubscribers = [];\n\t#responseReadable;\n\t#aborted = false;\n\t#closed = false;\n\t/**\n\t* Whether the stream has been aborted.\n\t*/\n\tget aborted() {\n\t\treturn this.#aborted;\n\t}\n\t/**\n\t* Whether the stream has been closed normally.\n\t*/\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\t/**\n\t* The readable stream that the response is piped to.\n\t*/\n\tget responseReadable() {\n\t\treturn this.#responseReadable;\n\t}\n\tconstructor(writable, readable) {\n\t\tthis.#writer = writable.getWriter();\n\t\tthis.#encoder = new TextEncoder();\n\t\tconst reader = readable.getReader();\n\t\tthis.#abortSubscribers.push(async () => {\n\t\t\tawait reader.cancel();\n\t\t});\n\t\tthis.#responseReadable = new ReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tthis.abort();\n\t\t\t}\n\t\t});\n\t}\n\tasync writeRaw(input) {\n\t\ttry {\n\t\t\tif (typeof input === \"string\") input = this.#encoder.encode(input);\n\t\t\tawait this.#writer.write(input);\n\t\t} catch {}\n\t}\n\twrite(input) {\n\t\treturn this.writeRaw(JSON.stringify(input) + \"\\n\");\n\t}\n\tsleep(ms) {\n\t\treturn new Promise((res) => setTimeout(res, ms));\n\t}\n\tasync close() {\n\t\ttry {\n\t\t\tawait this.#writer.close();\n\t\t} catch {} finally {\n\t\t\tthis.#closed = true;\n\t\t}\n\t}\n\tonAbort(listener) {\n\t\tthis.#abortSubscribers.push(listener);\n\t}\n\t/**\n\t* Abort the stream.\n\t* You can call this method when stream is aborted by external event.\n\t*/\n\tabort() {\n\t\tif (!this.aborted) {\n\t\t\tthis.#aborted = true;\n\t\t\tthis.#abortSubscribers.forEach((subscriber) => subscriber());\n\t\t}\n\t}\n};\n\n//#endregion\nexport { ResponseStream };\n//# sourceMappingURL=response-stream.js.map","import { ResponseStream } from \"./internal/response-stream.js\";\n\n//#region src/api/request-output-context.ts\n/**\n* Utility function to merge headers from multiple sources.\n* Later headers override earlier ones.\n*/\nfunction mergeHeaders(...headerSources) {\n\tconst mergedHeaders = new Headers();\n\tfor (const headerSource of headerSources) {\n\t\tif (!headerSource) continue;\n\t\tif (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);\n\t\telse if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);\n\t\telse for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);\n\t}\n\treturn mergedHeaders;\n}\nvar OutputContext = class {\n\t/**\n\t* Creates an error response.\n\t*\n\t* Shortcut for `throw new FragnoApiError(...)`\n\t*/\n\terror = ({ message, code }, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: 500,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tempty = (initOrStatus, headers) => {\n\t\tconst defaultHeaders = {};\n\t\tif (typeof initOrStatus === \"undefined\") {\n\t\t\tconst mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 201,\n\t\t\t\theaders: mergedHeaders$1\n\t\t\t});\n\t\t}\n\t\tif (typeof initOrStatus === \"number\") {\n\t\t\tconst mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: initOrStatus,\n\t\t\t\theaders: mergedHeaders$1\n\t\t\t});\n\t\t}\n\t\tconst mergedHeaders = mergeHeaders(defaultHeaders, initOrStatus.headers, headers);\n\t\treturn new Response(null, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjson = (object, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json(object, {\n\t\t\tstatus: 200,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json(object, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json(object, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjsonStream = (cb, { onError, headers } = {}) => {\n\t\tconst defaultHeaders = {\n\t\t\t\"content-type\": \"application/x-ndjson; charset=utf-8\",\n\t\t\t\"transfer-encoding\": \"chunked\",\n\t\t\t\"cache-control\": \"no-cache\"\n\t\t};\n\t\tconst { readable, writable } = new TransformStream();\n\t\tconst stream = new ResponseStream(writable, readable);\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tawait cb(stream);\n\t\t\t} catch (e) {\n\t\t\t\tif (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);\n\t\t\t\telse console.error(e);\n\t\t\t} finally {\n\t\t\t\tstream.close();\n\t\t\t}\n\t\t})();\n\t\treturn new Response(stream.responseReadable, {\n\t\t\tstatus: 200,\n\t\t\theaders: mergeHeaders(defaultHeaders, headers)\n\t\t});\n\t};\n};\nvar RequestOutputContext = class extends OutputContext {\n\t#outputSchema;\n\tconstructor(outputSchema) {\n\t\tsuper();\n\t\tthis.#outputSchema = outputSchema;\n\t}\n};\n\n//#endregion\nexport { OutputContext, RequestOutputContext };\n//# sourceMappingURL=request-output-context.js.map","//#region src/api/internal/path.ts\n/**\n* Extract parameter names from a path pattern at runtime.\n* Examples:\n* - \"/users/:id\" => [\"id\"]\n* - \"/files/**\" => [\"**\"]\n* - \"/files/**:rest\" => [\"rest\"]\n*/\nfunction extractPathParams(pathPattern) {\n\tconst segments = pathPattern.split(\"/\").filter((s) => s.length > 0);\n\tconst names = [];\n\tfor (const segment of segments) {\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tnames.push(segment.slice(1));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tnames.push(\"**\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tnames.push(segment.slice(3));\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn names;\n}\n/**\n* Build a concrete path by replacing placeholders in a path pattern with values.\n*\n* Supports the same placeholder syntax as the matcher:\n* - Named parameter \":name\" is URL-encoded as a single segment\n* - Anonymous wildcard \"**\" inserts the remainder as-is (slashes preserved)\n* - Named wildcard \"**:name\" inserts the remainder from the named key\n*\n* Examples:\n* - buildPath(\"/users/:id\", { id: \"123\" }) => \"/users/123\"\n* - buildPath(\"/files/**\", { \"**\": \"a/b\" }) => \"/files/a/b\"\n* - buildPath(\"/files/**:rest\", { rest: \"a/b\" }) => \"/files/a/b\"\n*/\nfunction buildPath(pathPattern, params) {\n\tconst patternSegments = pathPattern.split(\"/\");\n\tconst builtSegments = [];\n\tfor (const segment of patternSegments) {\n\t\tif (segment.length === 0) {\n\t\t\tbuiltSegments.push(\"\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tconst name = segment.slice(1);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path parameter :${name}`);\n\t\t\tbuiltSegments.push(encodeURIComponent(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tconst value = params[\"**\"];\n\t\t\tif (value === void 0) throw new Error(\"Missing value for path wildcard **\");\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tconst name = segment.slice(3);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tbuiltSegments.push(segment);\n\t}\n\treturn builtSegments.join(\"/\");\n}\n\n//#endregion\nexport { buildPath, extractPathParams };\n//# sourceMappingURL=path.js.map","//#region src/client/client-error.ts\n/**\n* Base error class for all Fragno client errors.\n*/\nvar FragnoClientError = class extends Error {\n\t#code;\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, { cause: options.cause });\n\t\tthis.name = \"FragnoClientError\";\n\t\tthis.#code = code;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n};\nvar FragnoClientFetchError = class extends FragnoClientError {\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientFetchError\";\n\t}\n\tstatic fromUnknownFetchError(error) {\n\t\tif (!(error instanceof Error)) return new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t\tif (error.name === \"AbortError\") return new FragnoClientFetchAbortError(\"Request was aborted\", { cause: error });\n\t\treturn new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t}\n};\n/**\n* Error thrown when a network request fails (e.g., no internet connection, DNS failure).\n*/\nvar FragnoClientFetchNetworkError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Network request failed\", options = {}) {\n\t\tsuper(message, \"NETWORK_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchNetworkError\";\n\t}\n};\n/**\n* Error thrown when a request is aborted (e.g., user cancels request, timeout).\n*/\nvar FragnoClientFetchAbortError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Request was aborted\", options = {}) {\n\t\tsuper(message, \"ABORT_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchAbortError\";\n\t}\n};\n/**\n* Error thrown when the API result is unexpected, e.g. no json is returned.\n*/\nvar FragnoClientUnknownApiError = class extends FragnoClientError {\n\t#status;\n\tconstructor(message = \"Unknown API error\", status, options = {}) {\n\t\tsuper(message, \"UNKNOWN_API_ERROR\", options);\n\t\tthis.name = \"FragnoClientUnknownApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n};\nvar FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {\n\t#status;\n\tconstructor({ message, code }, status, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\t/**\n\t* The error code returned by the API.\n\t*\n\t* The type is `TErrorCode` (the set of known error codes for this route), but may also be a string\n\t* for forward compatibility with future error codes.\n\t*/\n\tget code() {\n\t\treturn super.code;\n\t}\n\tstatic async fromResponse(response) {\n\t\tconst unknown = await response.json();\n\t\tconst status = response.status;\n\t\tif (!(\"message\" in unknown || \"code\" in unknown)) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\tif (!(typeof unknown.message === \"string\" && typeof unknown.code === \"string\")) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\treturn new FragnoClientApiError({\n\t\t\tmessage: unknown.message,\n\t\t\tcode: unknown.code\n\t\t}, status);\n\t}\n};\n\n//#endregion\nexport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError };\n//# sourceMappingURL=client-error.js.map","//#region src/util/content-type.ts\n/**\n* Parses a content-type header string into its components\n*\n* @param contentType - The content-type header value to parse\n* @returns A ParsedContentType object or null if the input is invalid\n*\n* @example\n* ```ts\n* const { type, subtype, mediaType, parameters }\n* = parseContentType(\"application/json; charset=utf-8\");\n* console.assert(type === \"application\");\n* console.assert(subtype === \"json\");\n* console.assert(mediaType === \"application/json\");\n* console.assert(parameters[\"charset\"] === \"utf-8\");\n*/\nfunction parseContentType(contentType) {\n\tif (!contentType || typeof contentType !== \"string\") return null;\n\tconst trimmed = contentType.trim();\n\tif (!trimmed) return null;\n\tconst parts = trimmed.split(\";\").map((part) => part.trim());\n\tconst mediaType = parts[0];\n\tif (!mediaType) return null;\n\tconst typeParts = mediaType.split(\"/\");\n\tif (typeParts.length !== 2) return null;\n\tconst [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());\n\tif (!type || !subtype) return null;\n\tconst parameters = {};\n\tfor (let i = 1; i < parts.length; i++) {\n\t\tconst param = parts[i];\n\t\tconst equalIndex = param.indexOf(\"=\");\n\t\tif (equalIndex > 0) {\n\t\t\tconst key = param.slice(0, equalIndex).trim().toLowerCase();\n\t\t\tlet value = param.slice(equalIndex + 1).trim();\n\t\t\tif (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) value = value.slice(1, -1);\n\t\t\tif (key) parameters[key] = value;\n\t\t}\n\t}\n\treturn {\n\t\ttype,\n\t\tsubtype,\n\t\tmediaType: `${type}/${subtype}`,\n\t\tparameters\n\t};\n}\n\n//#endregion\nexport { parseContentType };\n//# sourceMappingURL=content-type.js.map","import { FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientUnknownApiError } from \"../client-error.js\";\n\n//#region src/client/internal/ndjson-streaming.ts\n/**\n* Creates a promise that rejects when the abort signal is triggered\n*/\nfunction createAbortPromise(abortSignal) {\n\treturn new Promise((_, reject) => {\n\t\tconst abortHandler = () => {\n\t\t\treject(new FragnoClientFetchAbortError(\"Operation was aborted\"));\n\t\t};\n\t\tif (abortSignal.aborted) abortHandler();\n\t\telse abortSignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t});\n}\n/**\n* Handles NDJSON streaming responses by returning the first item from the fetcher\n* and then continuing to stream updates via the store's mutate method.\n*\n* This makes it so that we can wait until the first chunk before updating the store, if we did\n* not do this, `loading` would briefly be false before the first item would be populated in the\n* result.\n*\n* @param response - The fetch Response object containing the NDJSON stream\n* @param store - The fetcher store to update with streaming data\n* @param abortSignal - Optional AbortSignal to cancel the streaming operation\n* @returns A promise that resolves to an object containing the first item and a streaming promise\n*/\nasync function handleNdjsonStreamingFirstItem(response, store, options = {}) {\n\tif (!response.body) throw new FragnoClientFetchError(\"Streaming response has no body\", \"NO_BODY\");\n\tconst { abortSignal } = options;\n\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\tconst decoder = new TextDecoder();\n\tconst reader = response.body.getReader();\n\tlet buffer = \"\";\n\tlet firstItem = null;\n\tconst items = [];\n\ttry {\n\t\twhile (firstItem === null) {\n\t\t\tif (abortSignal?.aborted) {\n\t\t\t\treader.releaseLock();\n\t\t\t\tthrow new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\t}\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tif (firstItem === null) {\n\t\t\t\t\t\tfirstItem = jsonObject;\n\t\t\t\t\t\tconst streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tfirstItem,\n\t\t\t\t\t\t\tstreamingPromise\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 500, { cause: parseError });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (firstItem === null) {\n\t\t\treader.releaseLock();\n\t\t\tthrow new FragnoClientUnknownApiError(\"NDJSON stream contained no valid items\", 500);\n\t\t}\n\t\treader.releaseLock();\n\t\tthrow new FragnoClientFetchError(\"Unexpected end of stream processing\", \"NO_BODY\");\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientError) {\n\t\t\tstore?.setError(error);\n\t\t\tthrow error;\n\t\t} else {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 500, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\n\t}\n}\n/**\n* Continues streaming the remaining items in the background\n*/\nasync function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {\n\tlet buffer = initialBuffer;\n\ttry {\n\t\twhile (true) {\n\t\t\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) {\n\t\t\t\tif (buffer.trim()) {\n\t\t\t\t\tconst lines$1 = buffer.split(\"\\n\");\n\t\t\t\t\tfor (const line of lines$1) {\n\t\t\t\t\t\tif (!line.trim()) continue;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t\t\t} catch (parseError) {\n\t\t\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientError) store?.setError(error);\n\t\telse {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 400, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn items;\n}\n\n//#endregion\nexport { handleNdjsonStreamingFirstItem };\n//# sourceMappingURL=ndjson-streaming.js.map","let tasks = 0\nlet resolves = []\n\nexport function startTask() {\n tasks += 1\n return () => {\n tasks -= 1\n if (tasks === 0) {\n let prevResolves = resolves\n resolves = []\n for (let i of prevResolves) i()\n }\n }\n}\n\nexport function task(cb) {\n let endTask = startTask()\n let promise = cb().finally(endTask)\n promise.t = true\n return promise\n}\n\nexport function allTasks() {\n if (tasks === 0) {\n return Promise.resolve()\n } else {\n return new Promise(resolve => {\n resolves.push(resolve)\n })\n }\n}\n\nexport function cleanTasks() {\n tasks = 0\n}\n","import { cleanTasks } from '../task/index.js'\n\nexport let clean = Symbol('clean')\n\nexport let cleanStores = (...stores) => {\n if (process.env.NODE_ENV === 'production') {\n throw new Error(\n 'cleanStores() can be used only during development or tests'\n )\n }\n cleanTasks()\n for (let $store of stores) {\n if ($store) {\n if ($store.mocked) delete $store.mocked\n if ($store[clean]) $store[clean]()\n }\n }\n}\n","import { clean } from '../clean-stores/index.js'\n\nlet listenerQueue = []\nlet lqIndex = 0\nconst QUEUE_ITEMS_PER_LISTENER = 4\nexport let epoch = 0\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const atom = initialValue => {\n let listeners = []\n let $atom = {\n get() {\n if (!$atom.lc) {\n $atom.listen(() => {})()\n }\n return $atom.value\n },\n lc: 0,\n listen(listener) {\n $atom.lc = listeners.push(listener)\n\n return () => {\n for (\n let i = lqIndex + QUEUE_ITEMS_PER_LISTENER;\n i < listenerQueue.length;\n\n ) {\n if (listenerQueue[i] === listener) {\n listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER)\n } else {\n i += QUEUE_ITEMS_PER_LISTENER\n }\n }\n\n let index = listeners.indexOf(listener)\n if (~index) {\n listeners.splice(index, 1)\n if (!--$atom.lc) $atom.off()\n }\n }\n },\n notify(oldValue, changedKey) {\n epoch++\n let runListenerQueue = !listenerQueue.length\n for (let listener of listeners) {\n listenerQueue.push(listener, $atom.value, oldValue, changedKey)\n }\n\n if (runListenerQueue) {\n for (\n lqIndex = 0;\n lqIndex < listenerQueue.length;\n lqIndex += QUEUE_ITEMS_PER_LISTENER\n ) {\n listenerQueue[lqIndex](\n listenerQueue[lqIndex + 1],\n listenerQueue[lqIndex + 2],\n listenerQueue[lqIndex + 3]\n )\n }\n listenerQueue.length = 0\n }\n },\n /* It will be called on last listener unsubscribing.\n We will redefine it in onMount and onStop. */\n off() {},\n set(newValue) {\n let oldValue = $atom.value\n if (oldValue !== newValue) {\n $atom.value = newValue\n $atom.notify(oldValue)\n }\n },\n subscribe(listener) {\n let unbind = $atom.listen(listener)\n listener($atom.value)\n return unbind\n },\n value: initialValue\n }\n\n if (process.env.NODE_ENV !== 'production') {\n $atom[clean] = () => {\n listeners = []\n $atom.lc = 0\n $atom.off()\n }\n }\n\n return $atom\n}\n\nexport const readonlyType = store => store\n","import { clean } from '../clean-stores/index.js'\n\nconst START = 0\nconst STOP = 1\nconst SET = 2\nconst NOTIFY = 3\nconst MOUNT = 5\nconst UNMOUNT = 6\nconst REVERT_MUTATION = 10\n\nexport let on = (object, listener, eventKey, mutateStore) => {\n object.events = object.events || {}\n if (!object.events[eventKey + REVERT_MUTATION]) {\n object.events[eventKey + REVERT_MUTATION] = mutateStore(eventProps => {\n // eslint-disable-next-line no-sequences\n object.events[eventKey].reduceRight((event, l) => (l(event), event), {\n shared: {},\n ...eventProps\n })\n })\n }\n object.events[eventKey] = object.events[eventKey] || []\n object.events[eventKey].push(listener)\n return () => {\n let currentListeners = object.events[eventKey]\n let index = currentListeners.indexOf(listener)\n currentListeners.splice(index, 1)\n if (!currentListeners.length) {\n delete object.events[eventKey]\n object.events[eventKey + REVERT_MUTATION]()\n delete object.events[eventKey + REVERT_MUTATION]\n }\n }\n}\n\nexport let onStart = ($store, listener) =>\n on($store, listener, START, runListeners => {\n let originListen = $store.listen\n $store.listen = arg => {\n if (!$store.lc && !$store.starting) {\n $store.starting = true\n runListeners()\n delete $store.starting\n }\n return originListen(arg)\n }\n return () => {\n $store.listen = originListen\n }\n })\n\nexport let onStop = ($store, listener) =>\n on($store, listener, STOP, runListeners => {\n let originOff = $store.off\n $store.off = () => {\n runListeners()\n originOff()\n }\n return () => {\n $store.off = originOff\n }\n })\n\nexport let onSet = ($store, listener) =>\n on($store, listener, SET, runListeners => {\n let originSet = $store.set\n let originSetKey = $store.setKey\n if ($store.setKey) {\n $store.setKey = (changed, changedValue) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({\n abort,\n changed,\n newValue: { ...$store.value, [changed]: changedValue }\n })\n if (!isAborted) return originSetKey(changed, changedValue)\n }\n }\n $store.set = newValue => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, newValue })\n if (!isAborted) return originSet(newValue)\n }\n return () => {\n $store.set = originSet\n $store.setKey = originSetKey\n }\n })\n\nexport let onNotify = ($store, listener) =>\n on($store, listener, NOTIFY, runListeners => {\n let originNotify = $store.notify\n $store.notify = (oldValue, changed) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, changed, oldValue })\n if (!isAborted) return originNotify(oldValue, changed)\n }\n return () => {\n $store.notify = originNotify\n }\n })\n\nexport let STORE_UNMOUNT_DELAY = 1000\n\nexport let onMount = ($store, initialize) => {\n let listener = payload => {\n let destroy = initialize(payload)\n if (destroy) $store.events[UNMOUNT].push(destroy)\n }\n return on($store, listener, MOUNT, runListeners => {\n let originListen = $store.listen\n $store.listen = (...args) => {\n if (!$store.lc && !$store.active) {\n $store.active = true\n runListeners()\n }\n return originListen(...args)\n }\n\n let originOff = $store.off\n $store.events[UNMOUNT] = []\n $store.off = () => {\n originOff()\n setTimeout(() => {\n if ($store.active && !$store.lc) {\n $store.active = false\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n }\n }, STORE_UNMOUNT_DELAY)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n let originClean = $store[clean]\n $store[clean] = () => {\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n $store.active = false\n originClean()\n }\n }\n\n return () => {\n $store.listen = originListen\n $store.off = originOff\n }\n })\n}\n","import { atom, epoch } from '../atom/index.js'\nimport { onMount } from '../lifecycle/index.js'\n\nlet computedStore = (stores, cb, batched) => {\n if (!Array.isArray(stores)) stores = [stores]\n\n let previousArgs\n let currentEpoch\n let set = () => {\n if (currentEpoch === epoch) return\n currentEpoch = epoch\n let args = stores.map($store => $store.get())\n if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {\n previousArgs = args\n let value = cb(...args)\n if (value && value.then && value.t) {\n value.then(asyncValue => {\n if (previousArgs === args) {\n // Prevent a stale set\n $computed.set(asyncValue)\n }\n })\n } else {\n $computed.set(value)\n currentEpoch = epoch\n }\n }\n }\n let $computed = atom(undefined)\n let get = $computed.get\n $computed.get = () => {\n set()\n return get()\n }\n\n let timer\n let run = batched\n ? () => {\n clearTimeout(timer)\n timer = setTimeout(set)\n }\n : set\n\n onMount($computed, () => {\n let unbinds = stores.map($store => $store.listen(run))\n set()\n return () => {\n for (let unbind of unbinds) unbind()\n }\n })\n\n return $computed\n}\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const computed = (stores, fn) => computedStore(stores, fn)\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const batched = (stores, fn) => computedStore(stores, fn, true)\n","import { atom } from '../atom/index.js'\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const map = (initial = {}) => {\n let $map = atom(initial)\n\n $map.setKey = function (key, value) {\n let oldMap = $map.value\n if (typeof value === 'undefined' && key in $map.value) {\n $map.value = { ...$map.value }\n delete $map.value[key]\n $map.notify(oldMap, key)\n } else if ($map.value[key] !== value) {\n $map.value = {\n ...$map.value,\n [key]: value\n }\n $map.notify(oldMap, key)\n }\n }\n\n return $map\n}\n","import { allTasks } from \"nanostores\";\n\n//#region src/util/ssr.ts\nlet stores = [];\nconst SSR_ENABLED = false;\nfunction getStores() {\n\treturn stores;\n}\nfunction addStore(store) {\n\tstores.push(store);\n}\nfunction cleanStores() {\n\tstores = [];\n}\nlet clientInitialData;\nfunction hydrateFromWindow() {\n\tif (typeof window !== \"undefined\" && window.__FRAGNO_INITIAL_DATA__) {\n\t\tclientInitialData = new Map(window.__FRAGNO_INITIAL_DATA__);\n\t\tdelete window.__FRAGNO_INITIAL_DATA__;\n\t\tconsole.warn(\"hydrateFromWindow\", { clientInitialData: Array.from(clientInitialData.entries()) });\n\t}\n}\nfunction getInitialData(key) {\n\tif (clientInitialData?.has(key)) {\n\t\tconst data = clientInitialData.get(key);\n\t\tclientInitialData.delete(key);\n\t\treturn data;\n\t}\n}\nfunction listenToStores() {\n\tfor (const store of getStores()) store.listen(() => {});\n}\nasync function getFinalStoreValues() {\n\tlistenToStores();\n\tawait allTasks();\n\tconst stores$1 = getStores();\n\tconst storesInitialValue = /* @__PURE__ */ new Map();\n\tfor (const store of stores$1) {\n\t\tconst value = store.get();\n\t\tif (!value || !store.key || value.loading) continue;\n\t\tstoresInitialValue.set(store.key, value.data);\n\t}\n\treturn storesInitialValue;\n}\n\n//#endregion\nexport { SSR_ENABLED, addStore, cleanStores, getFinalStoreValues, getInitialData, hydrateFromWindow };\n//# sourceMappingURL=ssr.js.map","//#region src/util/nanostores.ts\n/**\n* Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.\n*/\nfunction unwrapAtom(value) {\n\tif (value && typeof value === \"object\" && \"get\" in value && typeof value.get === \"function\") return value.get();\n\treturn value;\n}\n/**\n* Normalizes an object where values can be plain values, Atoms, or Vue Refs.\n* Returns a new object with all values normalized to plain values.\n*/\nfunction unwrapObject(params) {\n\tif (!params) return;\n\treturn Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));\n}\nfunction isReadableAtom(value) {\n\tif (!value) return false;\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"get\" in value) || typeof value.get !== \"function\") return false;\n\tif (!(\"lc\" in value) || typeof value.lc !== \"number\") return false;\n\tif (!(\"notify\" in value) || typeof value.notify !== \"function\") return false;\n\tif (!(\"off\" in value) || typeof value.off !== \"function\") return false;\n\tif (!(\"subscribe\" in value) || typeof value.subscribe !== \"function\") return false;\n\tif (!(\"value\" in value)) return false;\n\treturn true;\n}\n\n//#endregion\nexport { isReadableAtom, unwrapObject };\n//# sourceMappingURL=nanostores.js.map","//#region src/client/internal/fetcher-merge.ts\n/**\n* Merge two fetcher configurations, with user config taking precedence.\n* If user provides a custom function, it takes full precedence.\n* Otherwise, deep merge RequestInit options.\n*/\nfunction mergeFetcherConfigs(authorConfig, userConfig) {\n\tif (userConfig?.type === \"function\") return userConfig;\n\tif (!userConfig && authorConfig?.type === \"function\") return authorConfig;\n\tconst authorOpts = authorConfig?.type === \"options\" ? authorConfig.options : {};\n\tconst userOpts = userConfig?.type === \"options\" ? userConfig.options : {};\n\tif (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;\n\treturn {\n\t\ttype: \"options\",\n\t\toptions: {\n\t\t\t...authorOpts,\n\t\t\t...userOpts,\n\t\t\theaders: mergeHeaders(authorOpts.headers, userOpts.headers)\n\t\t}\n\t};\n}\n/**\n* Merge headers from author and user configs.\n* User headers override author headers.\n*/\nfunction mergeHeaders(author, user) {\n\tif (!author && !user) return;\n\tconst merged = new Headers(author);\n\tnew Headers(user).forEach((value, key) => merged.set(key, value));\n\tif (merged.keys().next().done) return;\n\treturn merged;\n}\n\n//#endregion\nexport { mergeFetcherConfigs };\n//# sourceMappingURL=fetcher-merge.js.map","export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n","import { map, onStart, onStop, atom, batched, startTask } from 'nanostores';\nimport { createNanoEvents } from 'nanoevents';\n\nfunction defaultOnErrorRetry({ retryCount }) {\n return ~~((Math.random() + 0.5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;\n}\nconst nanoqueryFactory = ([\n isAppVisible,\n visibilityChangeSubscribe,\n reconnectChangeSubscribe\n]) => {\n const nanoquery = ({\n cache = /* @__PURE__ */ new Map(),\n fetcher: globalFetcher,\n ...globalSettings\n } = {}) => {\n const events = createNanoEvents();\n let focus = true;\n visibilityChangeSubscribe(() => {\n focus = isAppVisible();\n focus && events.emit(FOCUS);\n });\n reconnectChangeSubscribe(() => events.emit(RECONNECT));\n const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();\n let rewrittenSettings = {};\n const getCachedValueByKey = (key) => {\n const fromCache = cache.get(key);\n if (!fromCache)\n return [];\n const cacheHit = (fromCache.expires || 0) > getNow();\n return cacheHit ? [fromCache.data, fromCache.error] : [];\n };\n const runFetcher = async ([key, keyParts], store, settings) => {\n if (!focus)\n return;\n const set = (v) => {\n if (store.key === key) {\n store.set(v);\n events.emit(SET_CACHE, key, v, true);\n }\n };\n const setAsLoading = (prev) => {\n const toSet = prev === void 0 ? {} : { data: prev };\n set({\n ...toSet,\n ...loading,\n promise: _runningFetches.get(key)\n });\n };\n let {\n dedupeTime = 4e3,\n cacheLifetime = Infinity,\n fetcher,\n onErrorRetry = defaultOnErrorRetry\n } = {\n ...settings,\n ...rewrittenSettings\n };\n if (cacheLifetime < dedupeTime)\n cacheLifetime = dedupeTime;\n const now = getNow();\n if (_runningFetches.has(key)) {\n if (!store.value.loading)\n setAsLoading(getCachedValueByKey(key)[0]);\n return;\n }\n let cachedValue, cachedError;\n const fromCache = cache.get(key);\n if (fromCache?.data !== void 0 || fromCache?.error) {\n [cachedValue, cachedError] = getCachedValueByKey(key);\n if ((fromCache.created || 0) + dedupeTime > now) {\n if (store.value.data != cachedValue || store.value.error != cachedError) {\n set({ ...notLoading, data: cachedValue, error: cachedError });\n }\n return;\n }\n }\n const finishTask = startTask();\n try {\n clearTimeout(_errorInvalidateTimeouts.get(key));\n const promise = fetcher(...keyParts);\n _runningFetches.set(key, promise);\n setAsLoading(cachedValue);\n const res = await promise;\n cache.set(key, {\n data: res,\n created: getNow(),\n expires: getNow() + cacheLifetime\n });\n set({ data: res, ...notLoading });\n } catch (error) {\n settings.onError?.(error);\n const retryCount = (cache.get(key)?.retryCount || 0) + 1;\n cache.set(key, {\n error,\n created: getNow(),\n expires: getNow() + cacheLifetime,\n retryCount\n });\n if (onErrorRetry) {\n const timer = onErrorRetry({\n error,\n key,\n retryCount\n });\n if (timer)\n _errorInvalidateTimeouts.set(\n key,\n setTimeout(() => {\n invalidateKeys(key);\n cache.set(key, { retryCount });\n }, timer)\n );\n }\n set({ data: store.value.data, error, ...notLoading });\n } finally {\n finishTask();\n _runningFetches.delete(key);\n }\n };\n const createFetcherStore = (keyInput, {\n fetcher = globalFetcher,\n ...fetcherSettings\n } = {}) => {\n if (process.env.NODE_ENV !== \"production\" && !fetcher) {\n throw new Error(\n \"You need to set up either global fetcher of fetcher in createFetcherStore\"\n );\n }\n const fetcherStore = map({\n ...notLoading\n }), settings = { ...globalSettings, ...fetcherSettings, fetcher };\n fetcherStore._ = fetcherSymbol;\n fetcherStore.invalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n invalidateKeys(key);\n }\n };\n fetcherStore.revalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n revalidateKeys(key);\n }\n };\n fetcherStore.mutate = (data) => {\n const { key } = fetcherStore;\n if (key) {\n mutateCache(key, data);\n }\n };\n fetcherStore.fetch = async () => {\n let resolve;\n const promise = new Promise((r) => resolve = r);\n const unsub = fetcherStore.listen(({ error, data }) => {\n if (error !== void 0)\n resolve({ error });\n if (data !== void 0)\n resolve({ data });\n });\n return promise.finally(unsub);\n };\n let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;\n let evtUnsubs = [];\n onStart(fetcherStore, () => {\n const firstRun = !keysInternalUnsub;\n [keyStore, keysInternalUnsub] = getKeyStore(keyInput);\n keyUnsub = keyStore.subscribe((currentKeys) => {\n if (currentKeys) {\n const [newKey, keyParts] = currentKeys;\n fetcherStore.key = newKey;\n runFetcher([newKey, keyParts], fetcherStore, settings);\n prevKey = newKey;\n prevKeyParts = keyParts;\n } else {\n fetcherStore.key = prevKey = prevKeyParts = void 0;\n fetcherStore.set({ ...notLoading });\n }\n });\n const currentKeyValue = keyStore.get();\n if (currentKeyValue) {\n [prevKey, prevKeyParts] = currentKeyValue;\n if (firstRun)\n handleNewListener();\n }\n const {\n revalidateInterval = 0,\n revalidateOnFocus,\n revalidateOnReconnect\n } = settings;\n const runRefetcher = () => {\n if (prevKey)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n if (revalidateInterval > 0) {\n _revalidateOnInterval.set(\n keyInput,\n setInterval(runRefetcher, revalidateInterval)\n );\n }\n if (revalidateOnFocus)\n evtUnsubs.push(events.on(FOCUS, runRefetcher));\n if (revalidateOnReconnect)\n evtUnsubs.push(events.on(RECONNECT, runRefetcher));\n const cacheKeyChangeHandler = (keySelector) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) {\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n }\n };\n evtUnsubs.push(\n events.on(INVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(REVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(SET_CACHE, (keySelector, data, full) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) {\n fetcherStore.set(\n full ? data : { data, ...notLoading }\n );\n }\n })\n );\n });\n const handleNewListener = () => {\n if (prevKey && prevKeyParts)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n const originListen = fetcherStore.listen;\n fetcherStore.listen = (listener) => {\n const unsub = originListen(listener);\n listener(fetcherStore.value);\n handleNewListener();\n return unsub;\n };\n onStop(fetcherStore, () => {\n fetcherStore.value = { ...notLoading };\n keysInternalUnsub?.();\n evtUnsubs.forEach((fn) => fn());\n evtUnsubs = [];\n keyUnsub?.();\n clearInterval(_revalidateOnInterval.get(keyInput));\n });\n return fetcherStore;\n };\n const iterOverCache = (keySelector, cb) => {\n for (const key of cache.keys()) {\n if (testKeyAgainstSelector(key, keySelector))\n cb(key);\n }\n };\n const invalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n cache.delete(key);\n });\n events.emit(INVALIDATE_KEYS, keySelector);\n };\n const revalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n const cached = cache.get(key);\n if (cached) {\n cache.set(key, { ...cached, created: -Infinity });\n }\n });\n events.emit(REVALIDATE_KEYS, keySelector);\n };\n const mutateCache = (keySelector, data) => {\n iterOverCache(keySelector, (key) => {\n if (data === void 0)\n cache.delete(key);\n else {\n cache.set(key, {\n data,\n created: getNow(),\n expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)\n });\n }\n });\n events.emit(SET_CACHE, keySelector, data);\n };\n function createMutatorStore(mutator, opts) {\n const { throttleCalls, onError } = opts ?? {\n throttleCalls: true,\n onError: globalSettings?.onError\n };\n const mutate = async (data) => {\n if (throttleCalls && store.value?.loading)\n return;\n const newMutator = rewrittenSettings.fetcher ?? mutator;\n const keysToInvalidate = [], keysToRevalidate = [];\n const safeKeySet = (k, v) => {\n if (store.lc) {\n store.setKey(k, v);\n }\n };\n try {\n store.set({\n error: void 0,\n data: void 0,\n mutate,\n ...loading\n });\n const result = await newMutator({\n data,\n invalidate: (key) => {\n keysToInvalidate.push(key);\n },\n revalidate: (key) => {\n keysToRevalidate.push(key);\n },\n getCacheUpdater: (key, shouldRevalidate = true) => [\n (newVal) => {\n mutateCache(key, newVal);\n if (shouldRevalidate) {\n keysToRevalidate.push(key);\n }\n },\n cache.get(key)?.data\n ]\n });\n safeKeySet(\"data\", result);\n return result;\n } catch (error) {\n onError?.(error);\n safeKeySet(\"error\", error);\n store.setKey(\"error\", error);\n } finally {\n safeKeySet(\"loading\", false);\n keysToInvalidate.forEach(invalidateKeys);\n keysToRevalidate.forEach(revalidateKeys);\n }\n };\n const store = map({\n mutate,\n ...notLoading\n });\n onStop(\n store,\n () => store.set({ mutate, ...notLoading })\n );\n store.mutate = mutate;\n return store;\n }\n const __unsafeOverruleSettings = (data) => {\n if (process.env.NODE_ENV !== \"test\") {\n console.warn(\n `You should only use __unsafeOverruleSettings in test environment`\n );\n }\n rewrittenSettings = data;\n };\n return [\n createFetcherStore,\n createMutatorStore,\n { __unsafeOverruleSettings, invalidateKeys, revalidateKeys, mutateCache }\n ];\n };\n function isSomeKey(key) {\n return typeof key === \"string\" || typeof key === \"number\" || key === true;\n }\n const getKeyStore = (keys) => {\n if (isSomeKey(keys))\n return [\n atom([\"\" + keys, [keys]]),\n () => {\n }\n ];\n const keyParts = [];\n const $key = atom(null);\n const keysAsStoresToIndexes = /* @__PURE__ */ new Map();\n const setKeyStoreValue = () => {\n if (keyParts.some((v) => v === null || v === void 0 || v === false)) {\n $key.set(null);\n } else {\n $key.set([keyParts.join(\"\"), keyParts]);\n }\n };\n for (let i = 0; i < keys.length; i++) {\n const keyOrStore = keys[i];\n if (isSomeKey(keyOrStore)) {\n keyParts.push(keyOrStore);\n } else {\n keyParts.push(null);\n keysAsStoresToIndexes.set(keyOrStore, i);\n }\n }\n const storesAsArray = [...keysAsStoresToIndexes.keys()];\n const $storeKeys = batched(storesAsArray, (...storeValues) => {\n for (let i = 0; i < storeValues.length; i++) {\n const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);\n keyParts[partIndex] = store._ === fetcherSymbol ? store.value && \"data\" in store.value ? store.key : null : storeValues[i];\n }\n setKeyStoreValue();\n });\n setKeyStoreValue();\n return [$key, $storeKeys.subscribe(noop)];\n };\n function noop() {\n }\n const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;\n const testKeyAgainstSelector = (key, selector) => {\n if (Array.isArray(selector))\n return selector.includes(key);\n else if (typeof selector === \"function\")\n return selector(key);\n else\n return key === selector;\n };\n const getNow = () => (/* @__PURE__ */ new Date()).getTime();\n const fetcherSymbol = Symbol();\n const loading = { loading: true }, notLoading = { loading: false };\n return nanoquery;\n};\n\nconst subscribe = (name, fn) => {\n const isServer = typeof window === \"undefined\";\n if (!isServer) {\n addEventListener(name, fn);\n }\n};\nconst browserCompat = [\n () => !document.hidden,\n (cb) => subscribe(\"visibilitychange\", cb),\n (cb) => subscribe(\"online\", cb)\n];\n\nconst nanoquery = nanoqueryFactory(browserCompat);\n\nexport { nanoquery, defaultOnErrorRetry as onErrorRetry };\n","import { resolveRouteFactories } from \"../api/route.js\";\nimport { getMountRoute } from \"../api/internal/route.js\";\nimport { RequestInputContext } from \"../api/request-input-context.js\";\nimport { RequestOutputContext } from \"../api/request-output-context.js\";\nimport { buildPath, extractPathParams } from \"../api/internal/path.js\";\nimport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError } from \"./client-error.js\";\nimport { parseContentType } from \"../util/content-type.js\";\nimport { handleNdjsonStreamingFirstItem } from \"./internal/ndjson-streaming.js\";\nimport { SSR_ENABLED, addStore, getInitialData } from \"../util/ssr.js\";\nimport { unwrapObject } from \"../util/nanostores.js\";\nimport { mergeFetcherConfigs } from \"./internal/fetcher-merge.js\";\nimport { computed, task } from \"nanostores\";\nimport { nanoquery } from \"@nanostores/query\";\n\n//#region src/client/client.ts\n/**\n* Symbols used to identify hook types\n*/\nconst GET_HOOK_SYMBOL = Symbol(\"fragno-get-hook\");\nconst MUTATOR_HOOK_SYMBOL = Symbol(\"fragno-mutator-hook\");\nconst STORE_SYMBOL = Symbol(\"fragno-store\");\n/**\n* @internal\n*/\nfunction buildUrl(config, params) {\n\tconst { baseUrl = \"\", mountRoute, path } = config;\n\tconst { pathParams, queryParams } = params ?? {};\n\tconst normalizedPathParams = unwrapObject(pathParams);\n\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\treturn `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : \"\"}`;\n}\n/**\n* This method returns an array, which can be passed directly to nanostores.\n*\n* The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)\n* Missing pathParams are replaced with \"<missing>\".\n* Atoms with undefined values are wrapped in computed atoms that map undefined to \"\" to avoid nanoquery treating the key as incomplete.\n* @param path\n* @param params\n* @returns\n* @internal\n*/\nfunction getCacheKey(method, path, params) {\n\tif (!params) return [method, path];\n\tconst { pathParams, queryParams } = params;\n\tconst pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? \"<missing>\");\n\tconst queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {\n\t\tconst value = queryParams[key];\n\t\tif (value && typeof value === \"object\" && \"get\" in value) return computed(value, (v) => v ?? \"\");\n\t\treturn value ?? \"\";\n\t}) : [];\n\treturn [\n\t\tmethod,\n\t\tpath,\n\t\t...pathParamValues,\n\t\t...queryParamValues\n\t];\n}\nfunction isStreamingResponse(response) {\n\tconst contentType = parseContentType(response.headers.get(\"content-type\"));\n\tif (!contentType) return false;\n\tif (!(response.headers.get(\"transfer-encoding\") === \"chunked\")) return false;\n\tif (contentType.subtype === \"octet-stream\") return \"octet-stream\";\n\tif (contentType.subtype === \"x-ndjson\") return \"ndjson\";\n\treturn false;\n}\n/**\n* @internal\n*/\nfunction isGetHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isMutatorHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isStore(obj) {\n\treturn typeof obj === \"object\" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;\n}\nvar ClientBuilder = class {\n\t#publicConfig;\n\t#fragmentConfig;\n\t#fetcherConfig;\n\t#cache = /* @__PURE__ */ new Map();\n\t#createFetcherStore;\n\t#createMutatorStore;\n\t#invalidateKeys;\n\tconstructor(publicConfig, fragmentConfig) {\n\t\tthis.#publicConfig = publicConfig;\n\t\tthis.#fragmentConfig = fragmentConfig;\n\t\tthis.#fetcherConfig = publicConfig.fetcherConfig;\n\t\tconst [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({ cache: this.#cache });\n\t\tthis.#createFetcherStore = createFetcherStore;\n\t\tthis.#createMutatorStore = createMutatorStore;\n\t\tthis.#invalidateKeys = invalidateKeys;\n\t}\n\tget cacheEntries() {\n\t\treturn Object.fromEntries(this.#cache.entries());\n\t}\n\tcreateStore(obj) {\n\t\treturn {\n\t\t\tobj,\n\t\t\t[STORE_SYMBOL]: true\n\t\t};\n\t}\n\t/**\n\t* Build a URL for a custom backend call using the configured baseUrl and mountRoute.\n\t* Useful for fragment authors who need to make custom fetch calls.\n\t*/\n\tbuildUrl(path, params) {\n\t\treturn buildUrl({\n\t\t\tbaseUrl: this.#publicConfig.baseUrl ?? \"\",\n\t\t\tmountRoute: getMountRoute(this.#fragmentConfig),\n\t\t\tpath\n\t\t}, {\n\t\t\tpathParams: params?.path,\n\t\t\tqueryParams: params?.query\n\t\t});\n\t}\n\t/**\n\t* Get the configured fetcher function for custom backend calls.\n\t* Returns fetch with merged options applied.\n\t*/\n\tgetFetcher() {\n\t\treturn {\n\t\t\tfetcher: this.#getFetcher(),\n\t\t\tdefaultOptions: this.#getFetcherOptions()\n\t\t};\n\t}\n\t#getFetcher() {\n\t\tif (this.#fetcherConfig?.type === \"function\") return this.#fetcherConfig.fetcher;\n\t\treturn fetch;\n\t}\n\t#getFetcherOptions() {\n\t\tif (this.#fetcherConfig?.type === \"options\") return this.#fetcherConfig.options;\n\t}\n\tcreateHook(path, options) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === \"GET\" && r.outputSchema !== void 0);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);\n\t\treturn this.#createRouteQueryHook(route, options);\n\t}\n\tcreateMutator(method, path, onInvalidate) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.method !== \"GET\" && r.path === path && r.method === method);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);\n\t\treturn this.#createRouteQueryMutator(route, onInvalidate);\n\t}\n\t#createRouteQueryHook(route, options = {}) {\n\t\tif (route.method !== \"GET\") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${route.method} route.`);\n\t\tif (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tasync function callServerSideHandler(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tconst normalizedPathParams = unwrapObject(pathParams);\n\t\t\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\t\t\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\t\t\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\t\t\treturn await route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tmethod: route.method,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: normalizedPathParams,\n\t\t\t\tsearchParams\n\t\t\t}), new RequestOutputContext(route.outputSchema));\n\t\t}\n\t\tasync function executeQuery(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tif (typeof window === \"undefined\") return task(async () => callServerSideHandler({\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t}));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\treturn {\n\t\t\troute,\n\t\t\tstore: (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst key = getCacheKey(route.method, route.path, {\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst store = this.#createFetcherStore(key, {\n\t\t\t\t\tfetcher: async () => {\n\t\t\t\t\t\tif (SSR_ENABLED) {\n\t\t\t\t\t\t\tconst initialData = getInitialData(key.map((d) => typeof d === \"string\" ? d : d.get()).join(\"\"));\n\t\t\t\t\t\t\tif (initialData) return initialData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\t\t\tpathParams: path,\n\t\t\t\t\t\t\tqueryParams: query\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\t\t\tif (!isStreaming) return response.json();\n\t\t\t\t\t\tif (typeof window === \"undefined\") return [];\n\t\t\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\t\t\t\tstore.set({\n\t\t\t\t\t\t\t\t\t\t...store.get(),\n\t\t\t\t\t\t\t\t\t\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\t\t\t\tstore.set({\n\t\t\t\t\t\t\t\t\t\t...store.get(),\n\t\t\t\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn [firstItem];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t\t\t},\n\t\t\t\t\tonErrorRetry: options?.onErrorRetry,\n\t\t\t\t\tdedupeTime: Infinity\n\t\t\t\t});\n\t\t\t\tif (typeof window === \"undefined\") addStore(store);\n\t\t\t\treturn store;\n\t\t\t},\n\t\t\tquery: async (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\tif (!isStreaming) return await response.json();\n\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\t\treturn await streamingPromise;\n\t\t\t\t}\n\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t},\n\t\t\t[GET_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#createRouteQueryMutator(route, onInvalidate = (invalidate, params) => invalidate(\"GET\", route.path, params)) {\n\t\tconst method = route.method;\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tasync function executeMutateQuery({ body, path, query }) {\n\t\t\tif (typeof window === \"undefined\") return task(async () => route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tinputSchema: route.inputSchema,\n\t\t\t\tmethod,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tsearchParams: new URLSearchParams(query),\n\t\t\t\tbody\n\t\t\t}), new RequestOutputContext(route.outputSchema)));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams: path,\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = await fetcher(url, {\n\t\t\t\t\t...fetcherOptions,\n\t\t\t\t\tmethod,\n\t\t\t\t\tbody: body !== void 0 ? JSON.stringify(body) : void 0\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\tconst mutatorStore = this.#createMutatorStore(async ({ data }) => {\n\t\t\tif (typeof window === \"undefined\") {}\n\t\t\tconst { body, path, query } = data;\n\t\t\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"Body is required.\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tonInvalidate(this.#invalidate.bind(this), {\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return response.json();\n\t\t\tif (typeof window === \"undefined\") return [];\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn [firstItem];\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t}, { onError: (error) => {\n\t\t\tconsole.error(\"Error in mutatorStore\", error);\n\t\t} });\n\t\tconst mutateQuery = (async (data) => {\n\t\t\tconst { body, path, query } = data;\n\t\t\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"Body is required for mutateQuery\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return response.json();\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\treturn await streamingPromise;\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported for mutations\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t});\n\t\treturn {\n\t\t\troute,\n\t\t\tmutateQuery,\n\t\t\tmutatorStore,\n\t\t\t[MUTATOR_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#invalidate(method, path, params) {\n\t\tconst prefix = getCacheKey(method, path, {\n\t\t\tpathParams: params?.pathParams,\n\t\t\tqueryParams: params?.queryParams\n\t\t}).map((k) => typeof k === \"string\" ? k : k.get()).join(\"\");\n\t\tthis.#invalidateKeys((key) => key.startsWith(prefix));\n\t}\n};\n/**\n* Create a client builder for fragments using the new fragment definition API.\n* This is the same as createClientBuilder but works with FragmentDefinition.\n*/\nfunction createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {\n\tconst routes = resolveRouteFactories({\n\t\tconfig: {},\n\t\tdeps: {},\n\t\tservices: {},\n\t\tserviceDeps: {}\n\t}, routesOrFactories);\n\tconst fragmentConfig = {\n\t\tname: definition.name,\n\t\troutes\n\t};\n\tconst mountRoute = publicConfig.mountRoute ?? `/${definition.name}`;\n\tconst mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);\n\treturn new ClientBuilder({\n\t\t...publicConfig,\n\t\tmountRoute,\n\t\tfetcherConfig: mergedFetcherConfig\n\t}, fragmentConfig);\n}\n\n//#endregion\nexport { ClientBuilder, FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError, buildUrl, createClientBuilder, getCacheKey, isGetHook, isMutatorHook, isStore };\n//# sourceMappingURL=client.js.map","import { defineFragment } from \"@fragno-dev/core\";\nimport { withDatabase } from \"@fragno-dev/db\";\nimport { formsSchema } from \"./schema\";\nimport type { FormsConfig } from \".\";\nimport type { JSONSchema, NewForm, UpdateForm, FormStatus, UIElementSchema } from \"./models\";\nimport { Validator, type Schema } from \"@cfworker/json-schema\";\n\nexport type ValidatedData<T = Record<string, unknown>> = T;\nexport type ValidationResult =\n | { success: true; data: ValidatedData }\n | {\n success: false;\n error: { message: string; errors: Array<{ path: string; message: string }> };\n };\n\n// External to this fragment\nconst asExternalForm = <\n T extends { id: { externalId: string }; status: string; dataSchema: unknown; uiSchema: unknown },\n>(\n form: T,\n) => ({\n ...form,\n id: form.id.externalId,\n status: form.status as FormStatus,\n dataSchema: form.dataSchema as JSONSchema,\n uiSchema: form.uiSchema as UIElementSchema,\n});\n\nconst asExternalResponse = <\n T extends {\n id: { externalId: string };\n formId: string | null;\n data: unknown;\n ip: string | null;\n userAgent: string | null;\n },\n>(\n response: T,\n) => ({\n ...response,\n id: response.id.externalId,\n data: response.data as Record<string, unknown>,\n});\n\nexport interface SubmissionSortOptions {\n field: \"submittedAt\";\n order: \"asc\" | \"desc\";\n}\n\nexport const formsFragmentDef = defineFragment<FormsConfig>(\"forms\")\n .extend(withDatabase(formsSchema))\n .withDependencies(({ db }) => ({ db }))\n .providesBaseService(({ deps }) => {\n return {\n createForm: async (input: NewForm) => {\n return (await deps.db.create(\"form\", input)).externalId;\n },\n\n getForm: async (id: string) => {\n const form = await deps.db.findFirst(\"form\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)),\n );\n return form ? asExternalForm(form) : null;\n },\n\n getFormBySlug: async (slug: string) => {\n const form = await deps.db.findFirst(\"form\", (b) =>\n b.whereIndex(\"idx_form_slug\", (eb) => eb(\"slug\", \"=\", slug)),\n );\n return form ? asExternalForm(form) : null;\n },\n\n updateForm: async (id: string, input: UpdateForm) => {\n const uow = deps.db\n .createUnitOfWork()\n .find(\"form\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)));\n\n const [currentForms] = await uow.executeRetrieve();\n\n if (currentForms.length === 0) {\n return { success: false };\n }\n // TODO: length > 1 ?\n\n const currentForm = currentForms[0];\n\n // Only increment version if changing data schema\n const newVersion = input.dataSchema ? currentForm.version + 1 : currentForm.version;\n\n uow.update(\"form\", currentForm.id, (b) => {\n b.set({ ...input, version: newVersion, updatedAt: new Date() }).check();\n });\n return uow.executeMutations();\n },\n\n listForms: async () => {\n const forms = await deps.db.find(\"form\", (b) => b.whereIndex(\"primary\"));\n return forms.map(asExternalForm);\n },\n\n deleteForm: async (id: string) => {\n await deps.db.delete(\"form\", id);\n },\n\n validateData: (schema: Schema, data: Record<string, unknown>): ValidationResult => {\n const validator = new Validator(schema);\n const result = validator.validate(data);\n\n if (result.valid) {\n return { success: true, data: data as ValidatedData };\n }\n console.error(\"ERROR\", JSON.stringify(result.errors));\n return {\n success: false,\n // TODO: better error type for validation errors?\n // see: https://jsonforms.io/docs/validation/#external-validation-errors\n error: {\n message: \"Validation failed\",\n errors: result.errors.map((e) => ({\n path: e.instanceLocation || \"\",\n message: e.error ?? \"Invalid value\",\n })),\n },\n };\n },\n\n createResponse: async (\n formId: string,\n formVersion: number,\n data: ValidatedData,\n metadata?: { ip?: string | null; userAgent?: string | null },\n ) => {\n return (\n await deps.db.create(\"response\", {\n formId,\n formVersion,\n data,\n ip: metadata?.ip ?? null,\n userAgent: metadata?.userAgent ?? null,\n })\n ).externalId;\n },\n\n getResponse: async (id: string) => {\n const response = await deps.db.findFirst(\"response\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)),\n );\n return response ? asExternalResponse(response) : null;\n },\n\n listResponses: async (\n formId: string,\n sort: SubmissionSortOptions = { field: \"submittedAt\", order: \"desc\" },\n ) => {\n const responses = await deps.db.find(\"response\", (b) =>\n b\n .whereIndex(\"idx_response_form\", (eb) => eb(\"formId\", \"=\", formId))\n .orderByIndex(\"idx_response_submitted_at\", sort.order),\n );\n return responses.map(asExternalResponse);\n },\n\n deleteResponse: async (id: string) => {\n return await deps.db.delete(\"response\", id);\n },\n };\n })\n .build();\n","import { z } from \"zod\";\n\nexport const JSONSchemaSchema = z.record(z.string(), z.unknown());\nexport const UISchemaElementSchema = z.record(z.string(), z.unknown());\n\nexport const FormStatusSchema = z.enum([\"draft\", \"open\", \"closed\", \"static\"]);\n\nexport const FormSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().nullable(),\n slug: z.string(),\n status: FormStatusSchema,\n dataSchema: JSONSchemaSchema,\n uiSchema: UISchemaElementSchema,\n version: z.number(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport const NewFormSchema = FormSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n version: true,\n});\n\nexport const UpdateFormSchema = NewFormSchema.partial();\n\nexport const ResponseMetadataSchema = z.object({\n ip: z.union([z.ipv4(), z.ipv6()]).nullable(),\n userAgent: z.string().max(4096).nullable(),\n});\n\nexport const ResponseSchema = z.object({\n id: z.string(),\n formId: z.string().nullable().describe(\"Form ID (static form ID or database form external ID)\"),\n formVersion: z.number(),\n data: z.record(z.string(), z.unknown()),\n submittedAt: z.date(),\n ip: z.string().max(45).nullable(),\n userAgent: z.string().max(512).nullable(),\n});\n\nexport const NewResponseSchema = ResponseSchema.omit({\n id: true,\n submittedAt: true,\n formId: true,\n formVersion: true,\n ip: true,\n userAgent: true,\n}).extend({\n securityToken: z.string().optional(),\n});\n\nexport type NewForm = z.infer<typeof NewFormSchema>;\nexport type UpdateForm = z.infer<typeof UpdateFormSchema>;\nexport type Form = z.infer<typeof FormSchema>;\nexport type NewResponse = z.infer<typeof NewResponseSchema>;\nexport type Response = z.infer<typeof ResponseSchema>;\nexport type ResponseMetadata = z.infer<typeof ResponseMetadataSchema>;\nexport type FormStatus = z.infer<typeof FormStatusSchema>;\nexport type JSONSchema = z.infer<typeof JSONSchemaSchema>;\nexport type UIElementSchema = z.infer<typeof UISchemaElementSchema>;\n","import { defineRoutes } from \"@fragno-dev/core\";\nimport type { Schema } from \"@cfworker/json-schema\";\nimport { z } from \"zod\";\nimport { formsFragmentDef } from \"./definition\";\nimport {\n FormSchema,\n NewFormSchema,\n NewResponseSchema,\n ResponseMetadataSchema,\n ResponseSchema,\n UpdateFormSchema,\n} from \"./models\";\nimport type { Form } from \"./models\";\nimport type { StaticForm } from \".\";\n\n/** Extract and validate request metadata from headers (untrusted input) */\nfunction extractRequestMetadata(headers: Headers) {\n const rawUserAgent = headers.get(\"User-Agent\");\n const rawIp =\n headers.get(\"CF-Connecting-IP\") ||\n headers.get(\"X-Forwarded-For\")?.split(\",\")[0].trim() ||\n headers.get(\"X-Real-IP\") ||\n null;\n const result = ResponseMetadataSchema.safeParse({\n ip: rawIp,\n userAgent: rawUserAgent,\n });\n\n // Return validated data or null values if validation fails\n return result.success ? result.data : { ip: null, userAgent: null };\n}\n\nconst staticAsRegularForm = (sf: StaticForm): Form => ({\n id: sf.id,\n title: sf.title,\n description: sf.description,\n slug: sf.slug,\n status: \"static\",\n dataSchema: sf.dataSchema,\n uiSchema: sf.uiSchema as unknown as Form[\"uiSchema\"],\n version: sf.version,\n createdAt: new Date(),\n updatedAt: new Date(),\n});\n\n// Public routes\nexport const publicRoutes = defineRoutes(formsFragmentDef).create(\n ({ services, defineRoute, config }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/:slug\",\n outputSchema: FormSchema,\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n // Check static forms first\n const staticForm = config.staticForms?.find((f) => f.slug === pathParams.slug);\n if (staticForm) {\n return json(staticAsRegularForm(staticForm));\n }\n\n const form = await services.getFormBySlug(pathParams.slug);\n if (!form) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n\n return json(form);\n },\n }),\n\n defineRoute({\n method: \"POST\",\n path: \"/:slug/submit\",\n inputSchema: NewResponseSchema,\n outputSchema: z.string(),\n errorCodes: [\"NOT_FOUND\", \"VALIDATION_ERROR\", \"FORM_NOT_OPEN\"] as const,\n handler: async ({ input, pathParams, headers }, { json, error }) => {\n const { data } = await input.valid();\n\n // Check static forms first\n const staticFormConfig = config.staticForms?.find((f) => f.slug === pathParams.slug);\n const form = staticFormConfig\n ? staticAsRegularForm(staticFormConfig)\n : await services.getFormBySlug(pathParams.slug);\n\n if (!form) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n\n // Static forms and open forms accept submissions\n if (form.status !== \"open\" && form.status !== \"static\") {\n return error(\n { message: \"Form is not open, has status \" + form.status, code: \"FORM_NOT_OPEN\" },\n 400,\n );\n }\n\n // Form validation\n const result = services.validateData(form.dataSchema as Schema, data);\n\n if (!result.success) {\n const message = result.error.errors.map((e) => e.message).join(\" \");\n return error({ message, code: \"VALIDATION_ERROR\" }, 400);\n }\n\n // Extract and validate request metadata from headers\n const metadata = extractRequestMetadata(headers);\n\n const responseId = await services.createResponse(\n form.id,\n form.version,\n result.data,\n metadata,\n );\n\n if (config.onResponseSubmitted) {\n await config.onResponseSubmitted({\n id: responseId,\n formId: form.id,\n formVersion: form.version,\n data,\n submittedAt: new Date(),\n ip: metadata?.ip,\n userAgent: metadata?.userAgent,\n });\n }\n\n return json(responseId);\n },\n }),\n ];\n },\n);\n\n// Admin routes\nexport const adminRoutes = defineRoutes(formsFragmentDef).create(\n ({ services, defineRoute, config }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/forms\",\n outputSchema: z.array(FormSchema),\n handler: async (_ctx, { json }) => {\n const dbForms = await services.listForms();\n const staticForms = (config.staticForms ?? []).map(staticAsRegularForm);\n return json([...staticForms, ...dbForms]);\n },\n }),\n\n defineRoute({\n method: \"POST\",\n path: \"/admin/forms\",\n inputSchema: NewFormSchema,\n outputSchema: z.string(),\n errorCodes: [\"CREATE_FAILED\"] as const,\n handler: async ({ input }, { json }) => {\n const data = await input.valid();\n const formId = await services.createForm(data);\n if (config.onFormCreated) {\n await config.onFormCreated({ ...data, id: formId });\n }\n return json(formId);\n },\n }),\n\n defineRoute({\n method: \"PUT\",\n path: \"/admin/forms/:id\",\n inputSchema: UpdateFormSchema,\n errorCodes: [\"NOT_FOUND\", \"STATIC_FORM_READ_ONLY\"] as const,\n handler: async ({ input, pathParams }, { json, error }) => {\n const isStatic = config.staticForms?.some((f) => f.id === pathParams.id);\n if (isStatic) {\n return error(\n { message: \"Static forms cannot be modified\", code: \"STATIC_FORM_READ_ONLY\" },\n 403,\n );\n }\n const data = await input.valid();\n const { success } = await services.updateForm(pathParams.id, data);\n if (!success) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n return json(success);\n },\n }),\n\n defineRoute({\n method: \"DELETE\",\n path: \"/admin/forms/:id\",\n errorCodes: [\"NOT_FOUND\", \"STATIC_FORM_READ_ONLY\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n const isStatic = config.staticForms?.some((f) => f.id === pathParams.id);\n if (isStatic) {\n return error(\n { message: \"Static forms cannot be deleted\", code: \"STATIC_FORM_READ_ONLY\" },\n 403,\n );\n }\n await services.deleteForm(pathParams.id);\n // TODO: 404 when form not found\n // if (!deleted) {\n // return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n // }\n return json(true);\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/admin/forms/:id/submissions\",\n queryParameters: [\"sortOrder\"] as const,\n outputSchema: z.array(ResponseSchema),\n handler: async ({ pathParams, query }, { json }) => {\n const sortOrder = query.get(\"sortOrder\") === \"asc\" ? \"asc\" : \"desc\";\n const responses = await services.listResponses(pathParams.id, {\n field: \"submittedAt\",\n order: sortOrder,\n });\n return json(responses);\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/admin/submissions/:id\",\n outputSchema: ResponseSchema,\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n const response = await services.getResponse(pathParams.id);\n if (!response) {\n return error({ message: \"Submission not found\", code: \"NOT_FOUND\" }, 404);\n }\n return json(response);\n },\n }),\n\n defineRoute({\n method: \"DELETE\",\n path: \"/admin/submissions/:id\",\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json }) => {\n await services.deleteResponse(pathParams.id);\n // TODO: 404 when response not found\n // if (!deleted) {\n // return error({ message: \"Submission not found\", code: \"NOT_FOUND\" }, 404);\n // }\n return json(true);\n },\n }),\n ];\n },\n);\n","import { createClientBuilder } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicClientConfig } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicConfigWithDatabase } from \"@fragno-dev/db\";\nimport { instantiate } from \"@fragno-dev/core\";\nimport { publicRoutes, adminRoutes } from \"./routes\";\nimport { formsFragmentDef } from \"./definition\";\nimport type { Form, JSONSchema, Response } from \"./models\";\nimport type { UISchemaElement } from \"@jsonforms/core\";\n\n// Forms that exist in code, but submissions are stored in the DB\n// Static forms always have status: \"static\" and accept submissions\nexport interface StaticForm {\n id: string;\n title: string;\n description: string | null;\n slug: string;\n dataSchema: JSONSchema;\n uiSchema: UISchemaElement;\n version: number;\n}\n\nexport interface FormsConfig {\n onFormCreated?: (form: Omit<Form, \"version\" | \"createdAt\" | \"updatedAt\">) => Promise<void>;\n onResponseSubmitted?: (response: Response) => Promise<void>;\n staticForms?: StaticForm[];\n}\n\nexport const routes = [publicRoutes, adminRoutes] as const;\n\nexport function createFormsFragment(\n config: FormsConfig = {},\n options: FragnoPublicConfigWithDatabase,\n) {\n return instantiate(formsFragmentDef)\n .withConfig(config)\n .withRoutes(routes)\n .withOptions(options)\n .build();\n}\n\nexport function createFormsClients(fragnoConfig: FragnoPublicClientConfig) {\n const b = createClientBuilder(formsFragmentDef, fragnoConfig, routes);\n\n return {\n // Public\n useForm: b.createHook(\"/:slug\"),\n useSubmitForm: b.createMutator(\"POST\", \"/:slug/submit\"),\n\n // Admin - Forms\n useForms: b.createHook(\"/admin/forms\"),\n useCreateForm: b.createMutator(\"POST\", \"/admin/forms\"),\n useUpdateForm: b.createMutator(\"PUT\", \"/admin/forms/:id\"),\n useDeleteForm: b.createMutator(\"DELETE\", \"/admin/forms/:id\"),\n\n // Admin - Submissions\n useSubmissions: b.createHook(\"/admin/forms/:id/submissions\"),\n useSubmission: b.createHook(\"/admin/submissions/:id\"),\n useDeleteSubmission: b.createMutator(\"DELETE\", \"/admin/submissions/:id\"),\n };\n}\n\nexport { formsFragmentDef } from \"./definition\";\nexport type { SubmissionSortOptions } from \"./definition\";\nexport type { FragnoRouteConfig } from \"@fragno-dev/core\";\n"],"x_google_ignoreList":[10,11,12,13,14,15,19,20],"mappings":";;;;;;;;;AAKA,SAASA,sBAAsBC,SAASC,mBAAmB;CAC1D,MAAMC,WAAS,CAAE;AACjB,MAAK,MAAMC,QAAQF,kBAAmB,YAAWE,SAAS,YAAY;EACrE,MAAMC,gBAAgBD,KAAKH,QAAQ;AACnCE,WAAOG,KAAK,GAAGD,cAAc;CAC7B,MAAMF,UAAOG,KAAKF,KAAK;AACxB,QAAOD;AACR;;;;ACXA,SAASW,cAAcC,MAAM;CAC5B,MAAMC,aAAaD,KAAKC,eAAc,OAAQD,KAAKE,KAAI;AACvD,KAAID,WAAWE,SAAS,IAAI,CAAE,QAAOF,WAAWG,MAAM,GAAG,GAAG;AAC5D,QAAOH;AACR;;;;ACJA,IAAII,iBAAiB,cAAcC,MAAM;CACxC;CACA;CACAG,YAAY,EAAEC,SAASF,MAAM,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B,eAAe;GACrCa,SAAOA,MAAA,CAAA;EAQR,EAAC;EAEFP,YAAY;GACVE,QAAQ;GACRC,MAAM;GACNC,cAAcV;GACdW,YAAY,CAAC,WAAY;GACzBE,SAAOA,MAAA,CAAA;EAOR,EAAC;EAEFP,YAAY;GACVE,QAAQ;GACRC,MAAM;GACNE,YAAY,CAAC,WAAY;GACzBE,SAAOA,MAAA,CAAA;EAQR,EAAC;CACH;AAEL,EAAC;;;;ACjOD,MAAagC,SAAS,CAACvB,cAAcC,WAAY;AAEjD,SAAgBwB,oBACdC,SAAsB,CAAE,GACxBC,SACA;AACA,QAAA,CAAA;AAKF;AAEA,SAAgBE,mBAAmBC,cAAwC;CACzE,MAAMC,IAAIlC,oBAAoBK,kBAAkB4B,cAAcP,OAAO;AAErE,QAAO;EAELS,SAASD,EAAEE,WAAW,SAAS;EAC/BC,eAAeH,EAAEI,cAAc,QAAQ,gBAAgB;EAGvDC,UAAUL,EAAEE,WAAW,eAAe;EACtCI,eAAeN,EAAEI,cAAc,QAAQ,eAAe;EACtDG,eAAeP,EAAEI,cAAc,OAAO,mBAAmB;EACzDI,eAAeR,EAAEI,cAAc,UAAU,mBAAmB;EAG5DK,gBAAgBT,EAAEE,WAAW,+BAA+B;EAC5DQ,eAAeV,EAAEE,WAAW,yBAAyB;EACrDS,qBAAqBX,EAAEI,cAAc,UAAU,yBAAwB;CACxE;AACH"}
1
+ {"version":3,"file":"src-DbMX_NY6.js","names":["resolveRouteFactories","context","routesOrFactories","routes","item","factoryRoutes","push","defineRoute","config","defineRoutes","_definition","create","fn","ctx","getMountRoute","opts","mountRoute","name","endsWith","slice","FragnoApiError","Error","status","code","constructor","message","name","toResponse","Response","json","FragnoApiValidationError","issues","FragnoApiValidationError","RequestInputContext","path","method","pathParams","searchParams","headers","body","parsedBody","inputSchema","shouldValidateInput","constructor","config","rawBody","fromRequest","state","fromSSRContext","URLSearchParams","Headers","query","input","schema","valid","validateInput","#validateInput","Error","FormData","Blob","result","validate","issues","value","ResponseStream","writer","encoder","abortSubscribers","responseReadable","aborted","closed","constructor","writable","readable","getWriter","TextEncoder","reader","getReader","push","cancel","ReadableStream","pull","controller","done","value","read","close","enqueue","abort","writeRaw","input","encode","write","JSON","stringify","sleep","ms","Promise","res","setTimeout","onAbort","listener","forEach","subscriber","ResponseStream","mergeHeaders","headerSources","mergedHeaders","Headers","headerSource","key","value","entries","set","Array","isArray","Object","OutputContext","error","message","code","initOrStatus","headers","Response","json","status","empty","defaultHeaders","mergedHeaders$1","object","jsonStream","cb","onError","readable","writable","TransformStream","stream","e","Error","console","close","responseReadable","RequestOutputContext","outputSchema","constructor","extractPathParams","pathPattern","segments","split","filter","s","length","names","segment","startsWith","push","slice","buildPath","params","patternSegments","builtSegments","name","value","Error","encodeURIComponent","join","FragnoClientError","Error","code","constructor","message","options","cause","name","FragnoClientFetchError","fromUnknownFetchError","error","FragnoClientFetchNetworkError","FragnoClientFetchAbortError","FragnoClientUnknownApiError","status","FragnoClientApiError","fromResponse","response","unknown","json","parseContentType","contentType","trimmed","trim","parts","split","map","part","mediaType","typeParts","length","type","subtype","toLowerCase","parameters","i","param","equalIndex","indexOf","key","slice","value","startsWith","endsWith","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientUnknownApiError","createAbortPromise","abortSignal","Promise","_","reject","abortHandler","aborted","addEventListener","once","handleNdjsonStreamingFirstItem","response","store","options","body","decoder","TextDecoder","reader","getReader","buffer","firstItem","items","releaseLock","done","value","race","read","decode","stream","lines","split","pop","line","trim","jsonObject","JSON","parse","push","streamingPromise","continueStreaming","parseError","cause","error","setError","clientError","initialBuffer","lines$1","setData","tasks","resolves","startTask","prevResolves","i","task","cb","endTask","promise","finally","t","allTasks","Promise","resolve","push","cleanTasks","cleanTasks","clean","Symbol","cleanStores","stores","process","env","NODE_ENV","Error","$store","mocked","clean","listenerQueue","lqIndex","QUEUE_ITEMS_PER_LISTENER","epoch","atom","initialValue","listeners","$atom","get","lc","listen","value","listener","push","i","length","splice","index","indexOf","off","notify","oldValue","changedKey","runListenerQueue","set","newValue","subscribe","unbind","process","env","NODE_ENV","readonlyType","store","clean","START","STOP","SET","NOTIFY","MOUNT","UNMOUNT","REVERT_MUTATION","on","object","listener","eventKey","mutateStore","events","eventProps","reduceRight","event","l","shared","push","currentListeners","index","indexOf","splice","length","onStart","$store","runListeners","originListen","listen","arg","lc","starting","onStop","originOff","off","onSet","originSet","set","originSetKey","setKey","changed","changedValue","isAborted","abort","newValue","value","onNotify","originNotify","notify","oldValue","STORE_UNMOUNT_DELAY","onMount","initialize","payload","destroy","args","active","setTimeout","process","env","NODE_ENV","originClean","atom","epoch","onMount","computedStore","stores","cb","batched","Array","isArray","previousArgs","currentEpoch","set","args","map","$store","get","some","arg","i","value","then","t","asyncValue","$computed","undefined","timer","run","clearTimeout","setTimeout","unbinds","listen","unbind","computed","fn","atom","map","initial","$map","setKey","key","value","oldMap","notify","allTasks","stores","SSR_ENABLED","getStores","addStore","store","push","cleanStores","clientInitialData","hydrateFromWindow","window","__FRAGNO_INITIAL_DATA__","Map","console","warn","Array","from","entries","getInitialData","key","has","data","get","delete","listenToStores","listen","getFinalStoreValues","stores$1","storesInitialValue","value","loading","set","unwrapAtom","value","get","unwrapObject","params","Object","fromEntries","entries","map","key","isReadableAtom","lc","notify","off","subscribe","mergeFetcherConfigs","authorConfig","userConfig","type","authorOpts","options","userOpts","Object","keys","length","headers","mergeHeaders","author","user","merged","Headers","forEach","value","key","set","next","done","createNanoEvents","emit","event","args","callbacks","events","i","length","on","cb","push","filter","map","onStart","onStop","atom","batched","startTask","createNanoEvents","defaultOnErrorRetry","retryCount","Math","random","nanoqueryFactory","isAppVisible","visibilityChangeSubscribe","reconnectChangeSubscribe","nanoquery","cache","Map","fetcher","globalFetcher","globalSettings","events","focus","emit","FOCUS","RECONNECT","_revalidateOnInterval","_errorInvalidateTimeouts","_runningFetches","rewrittenSettings","getCachedValueByKey","key","fromCache","get","cacheHit","expires","getNow","data","error","runFetcher","keyParts","store","settings","set","v","SET_CACHE","setAsLoading","prev","toSet","loading","promise","dedupeTime","cacheLifetime","Infinity","onErrorRetry","now","has","value","cachedValue","cachedError","created","notLoading","finishTask","clearTimeout","res","onError","timer","setTimeout","invalidateKeys","delete","createFetcherStore","keyInput","fetcherSettings","process","env","NODE_ENV","Error","fetcherStore","_","fetcherSymbol","invalidate","revalidate","revalidateKeys","mutate","mutateCache","fetch","resolve","Promise","r","unsub","listen","finally","keysInternalUnsub","prevKey","prevKeyParts","keyUnsub","keyStore","evtUnsubs","firstRun","getKeyStore","subscribe","currentKeys","newKey","currentKeyValue","handleNewListener","revalidateInterval","revalidateOnFocus","revalidateOnReconnect","runRefetcher","setInterval","push","on","cacheKeyChangeHandler","keySelector","testKeyAgainstSelector","INVALIDATE_KEYS","REVALIDATE_KEYS","full","originListen","listener","forEach","fn","clearInterval","iterOverCache","cb","keys","cached","createMutatorStore","mutator","opts","throttleCalls","newMutator","keysToInvalidate","keysToRevalidate","safeKeySet","k","lc","setKey","result","getCacheUpdater","shouldRevalidate","newVal","__unsafeOverruleSettings","console","warn","isSomeKey","$key","keysAsStoresToIndexes","setKeyStoreValue","some","join","i","length","keyOrStore","storesAsArray","$storeKeys","storeValues","partIndex","noop","selector","Array","isArray","includes","Date","getTime","Symbol","name","isServer","window","addEventListener","browserCompat","document","hidden","resolveRouteFactories","getMountRoute","RequestInputContext","RequestOutputContext","buildPath","extractPathParams","FragnoClientApiError","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientFetchNetworkError","FragnoClientUnknownApiError","parseContentType","handleNdjsonStreamingFirstItem","SSR_ENABLED","addStore","getInitialData","unwrapObject","mergeFetcherConfigs","computed","task","nanoquery","GET_HOOK_SYMBOL","Symbol","MUTATOR_HOOK_SYMBOL","STORE_SYMBOL","buildUrl","config","params","baseUrl","mountRoute","path","pathParams","queryParams","normalizedPathParams","normalizedQueryParams","filteredQueryParams","Object","fromEntries","entries","filter","_","value","searchParams","URLSearchParams","toString","getCacheKey","method","pathParamValues","map","name","queryParamValues","keys","sort","key","v","isStreamingResponse","response","contentType","headers","get","subtype","isGetHook","hook","isMutatorHook","isStore","obj","ClientBuilder","publicConfig","fragmentConfig","fetcherConfig","cache","Map","createFetcherStore","createMutatorStore","invalidateKeys","constructor","cacheEntries","createStore","query","getFetcher","fetcher","defaultOptions","getFetcherOptions","#getFetcher","type","fetch","#getFetcherOptions","options","createHook","route","routes","find","r","outputSchema","Error","createRouteQueryHook","createMutator","onInvalidate","createRouteQueryMutator","#createRouteQueryHook","fetcherOptions","callServerSideHandler","handler","fromSSRContext","executeQuery","window","url","error","fromUnknownFetchError","ok","fromResponse","store","args","initialData","d","join","isStreaming","json","firstItem","setData","set","loading","Array","isArray","length","data","setError","onErrorRetry","dedupeTime","Infinity","streamingPromise","#createRouteQueryMutator","invalidate","executeMutateQuery","body","inputSchema","JSON","stringify","mutatorStore","bind","status","onError","console","mutateQuery","#invalidate","prefix","k","startsWith","createClientBuilder","definition","routesOrFactories","authorFetcherConfig","deps","services","serviceDeps","mergedFetcherConfig","defineFragment","FormsConfig","NewForm","UpdateForm","Schema","ValidatedData","Record","T","ValidationResult","success","data","error","message","errors","Array","path","SubmissionSortOptions","field","order","formsFragmentDef","extend","x","withDependencies","providesBaseService","build","z","JSONSchemaSchema","record","string","unknown","UISchemaElementSchema","FormStatusSchema","enum","FormSchema","object","id","title","description","nullable","slug","status","dataSchema","uiSchema","version","number","createdAt","date","updatedAt","NewFormSchema","omit","UpdateFormSchema","partial","ResponseMetadataSchema","ip","union","ipv4","ipv6","userAgent","max","ResponseSchema","formId","describe","formVersion","data","submittedAt","NewResponseSchema","extend","securityToken","optional","NewForm","infer","UpdateForm","Form","NewResponse","Response","ResponseMetadata","FormStatus","JSONSchema","UIElementSchema","defineRoutes","z","formsFragmentDef","FormSchema","NewFormSchema","NewResponseSchema","ResponseSchema","UpdateFormSchema","StaticForm","publicRoutes","create","services","defineRoute","config","method","path","outputSchema","errorCodes","const","handler","inputSchema","string","adminRoutes","array","queryParameters","createClientBuilder","FragnoPublicClientConfig","FragnoPublicConfig","publicRoutes","adminRoutes","formsFragmentDef","Form","JSONSchema","Response","UISchemaElement","StaticForm","id","title","description","slug","dataSchema","uiSchema","version","FormsConfig","onFormCreated","form","Omit","Promise","onResponseSubmitted","response","staticForms","routes","const","createFormsFragment","config","options","FragnoPublicConfigWithDatabase","createFormsClients","fragnoConfig","b","useForm","createHook","useSubmitForm","createMutator","useForms","useCreateForm","useUpdateForm","useDeleteForm","useSubmissions","useSubmission","useDeleteSubmission","SubmissionSortOptions","FragnoRouteConfig"],"sources":["../../../fragno/dist/api/route.js","../../../fragno/dist/api/internal/route.js","../../../fragno/dist/api/error.js","../../../fragno/dist/api/request-input-context.js","../../../fragno/dist/api/internal/response-stream.js","../../../fragno/dist/api/request-output-context.js","../../../fragno/dist/api/internal/path.js","../../../fragno/dist/client/client-error.js","../../../fragno/dist/util/content-type.js","../../../fragno/dist/client/internal/ndjson-streaming.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/task/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/clean-stores/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/atom/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/lifecycle/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/computed/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/map/index.js","../../../fragno/dist/util/ssr.js","../../../fragno/dist/util/nanostores.js","../../../fragno/dist/client/internal/fetcher-merge.js","../../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../../../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.1.0/node_modules/@nanostores/query/dist/nanoquery.js","../../../fragno/dist/client/client.js","../../src/definition.ts","../../src/models.ts","../../src/routes.ts","../../src/index.ts"],"sourcesContent":["//#region src/api/route.ts\n/**\n* Helper to resolve route factories into routes\n* @internal\n*/\nfunction resolveRouteFactories(context, routesOrFactories) {\n\tconst routes = [];\n\tfor (const item of routesOrFactories) if (typeof item === \"function\") {\n\t\tconst factoryRoutes = item(context);\n\t\troutes.push(...factoryRoutes);\n\t} else routes.push(item);\n\treturn routes;\n}\nfunction defineRoute(config) {\n\treturn config;\n}\nfunction defineRoutes(_definition) {\n\treturn { create: (fn) => {\n\t\treturn (ctx) => {\n\t\t\treturn fn({\n\t\t\t\t...ctx,\n\t\t\t\tdefineRoute\n\t\t\t});\n\t\t};\n\t} };\n}\n\n//#endregion\nexport { defineRoute, defineRoutes, resolveRouteFactories };\n//# sourceMappingURL=route.js.map","//#region src/api/internal/route.ts\nfunction getMountRoute(opts) {\n\tconst mountRoute = opts.mountRoute ?? `/api/${opts.name}`;\n\tif (mountRoute.endsWith(\"/\")) return mountRoute.slice(0, -1);\n\treturn mountRoute;\n}\n\n//#endregion\nexport { getMountRoute };\n//# sourceMappingURL=route.js.map","//#region src/api/error.ts\nvar FragnoApiError = class extends Error {\n\t#status;\n\t#code;\n\tconstructor({ message, code }, status) {\n\t\tsuper(message);\n\t\tthis.name = \"FragnoApiError\";\n\t\tthis.#status = status;\n\t\tthis.#code = code;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\nvar FragnoApiValidationError = class extends FragnoApiError {\n\t#issues;\n\tconstructor(message, issues) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tcode: \"FRAGNO_VALIDATION_ERROR\"\n\t\t}, 400);\n\t\tthis.name = \"FragnoApiValidationError\";\n\t\tthis.#issues = issues;\n\t}\n\tget issues() {\n\t\treturn this.#issues;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tissues: this.#issues,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\n\n//#endregion\nexport { FragnoApiError, FragnoApiValidationError };\n//# sourceMappingURL=error.js.map","import { FragnoApiValidationError } from \"./error.js\";\n\n//#region src/api/request-input-context.ts\nvar RequestInputContext = class RequestInputContext {\n\t#path;\n\t#method;\n\t#pathParams;\n\t#searchParams;\n\t#headers;\n\t#body;\n\t#parsedBody;\n\t#inputSchema;\n\t#shouldValidateInput;\n\tconstructor(config) {\n\t\tthis.#path = config.path;\n\t\tthis.#method = config.method;\n\t\tthis.#pathParams = config.pathParams;\n\t\tthis.#searchParams = config.searchParams;\n\t\tthis.#headers = config.headers;\n\t\tthis.#body = config.rawBody;\n\t\tthis.#parsedBody = config.parsedBody;\n\t\tthis.#inputSchema = config.inputSchema;\n\t\tthis.#shouldValidateInput = config.shouldValidateInput ?? true;\n\t}\n\t/**\n\t* Create a RequestContext from a Request object for server-side handling\n\t*/\n\tstatic async fromRequest(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.state.pathParams,\n\t\t\tsearchParams: config.state.searchParams,\n\t\t\theaders: config.state.headers,\n\t\t\tparsedBody: config.state.body,\n\t\t\trawBody: config.rawBody,\n\t\t\tinputSchema: config.inputSchema,\n\t\t\tshouldValidateInput: config.shouldValidateInput\n\t\t});\n\t}\n\t/**\n\t* Create a RequestContext for server-side rendering contexts (no Request object)\n\t*/\n\tstatic fromSSRContext(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.pathParams,\n\t\t\tsearchParams: config.searchParams ?? new URLSearchParams(),\n\t\t\theaders: config.headers ?? new Headers(),\n\t\t\tparsedBody: \"body\" in config ? config.body : void 0,\n\t\t\tinputSchema: \"inputSchema\" in config ? config.inputSchema : void 0,\n\t\t\tshouldValidateInput: false\n\t\t});\n\t}\n\t/**\n\t* The HTTP method as string (e.g., `GET`, `POST`)\n\t*/\n\tget method() {\n\t\treturn this.#method;\n\t}\n\t/**\n\t* The matched route path (e.g., `/users/:id`)\n\t* @remarks `string`\n\t*/\n\tget path() {\n\t\treturn this.#path;\n\t}\n\t/**\n\t* Extracted path parameters as object (e.g., `{ id: '123' }`)\n\t* @remarks `Record<string, string>`\n\t*/\n\tget pathParams() {\n\t\treturn this.#pathParams;\n\t}\n\t/**\n\t* [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters\n\t* @remarks `URLSearchParams`\n\t*/\n\tget query() {\n\t\treturn this.#searchParams;\n\t}\n\t/**\n\t* [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers\n\t* @remarks `Headers`\n\t*/\n\tget headers() {\n\t\treturn this.#headers;\n\t}\n\tget rawBody() {\n\t\treturn this.#body;\n\t}\n\t/**\n\t* Input validation context (only if inputSchema is defined)\n\t* @remarks `InputContext`\n\t*/\n\tget input() {\n\t\tif (!this.#inputSchema) return;\n\t\treturn {\n\t\t\tschema: this.#inputSchema,\n\t\t\tvalid: async () => {\n\t\t\t\tif (!this.#shouldValidateInput) return this.#parsedBody;\n\t\t\t\treturn this.#validateInput();\n\t\t\t}\n\t\t};\n\t}\n\tasync #validateInput() {\n\t\tif (!this.#inputSchema) throw new Error(\"No input schema defined for this route\");\n\t\tif (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error(\"Schema validation is only supported for JSON data, not FormData or Blob\");\n\t\tconst result = await this.#inputSchema[\"~standard\"].validate(this.#parsedBody);\n\t\tif (result.issues) throw new FragnoApiValidationError(\"Validation failed\", result.issues);\n\t\treturn result.value;\n\t}\n};\n\n//#endregion\nexport { RequestInputContext };\n//# sourceMappingURL=request-input-context.js.map","//#region src/api/internal/response-stream.ts\nvar ResponseStream = class {\n\t#writer;\n\t#encoder;\n\t#abortSubscribers = [];\n\t#responseReadable;\n\t#aborted = false;\n\t#closed = false;\n\t/**\n\t* Whether the stream has been aborted.\n\t*/\n\tget aborted() {\n\t\treturn this.#aborted;\n\t}\n\t/**\n\t* Whether the stream has been closed normally.\n\t*/\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\t/**\n\t* The readable stream that the response is piped to.\n\t*/\n\tget responseReadable() {\n\t\treturn this.#responseReadable;\n\t}\n\tconstructor(writable, readable) {\n\t\tthis.#writer = writable.getWriter();\n\t\tthis.#encoder = new TextEncoder();\n\t\tconst reader = readable.getReader();\n\t\tthis.#abortSubscribers.push(async () => {\n\t\t\tawait reader.cancel();\n\t\t});\n\t\tthis.#responseReadable = new ReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tthis.abort();\n\t\t\t}\n\t\t});\n\t}\n\tasync writeRaw(input) {\n\t\ttry {\n\t\t\tif (typeof input === \"string\") input = this.#encoder.encode(input);\n\t\t\tawait this.#writer.write(input);\n\t\t} catch {}\n\t}\n\twrite(input) {\n\t\treturn this.writeRaw(JSON.stringify(input) + \"\\n\");\n\t}\n\tsleep(ms) {\n\t\treturn new Promise((res) => setTimeout(res, ms));\n\t}\n\tasync close() {\n\t\ttry {\n\t\t\tawait this.#writer.close();\n\t\t} catch {} finally {\n\t\t\tthis.#closed = true;\n\t\t}\n\t}\n\tonAbort(listener) {\n\t\tthis.#abortSubscribers.push(listener);\n\t}\n\t/**\n\t* Abort the stream.\n\t* You can call this method when stream is aborted by external event.\n\t*/\n\tabort() {\n\t\tif (!this.aborted) {\n\t\t\tthis.#aborted = true;\n\t\t\tthis.#abortSubscribers.forEach((subscriber) => subscriber());\n\t\t}\n\t}\n};\n\n//#endregion\nexport { ResponseStream };\n//# sourceMappingURL=response-stream.js.map","import { ResponseStream } from \"./internal/response-stream.js\";\n\n//#region src/api/request-output-context.ts\n/**\n* Utility function to merge headers from multiple sources.\n* Later headers override earlier ones.\n*/\nfunction mergeHeaders(...headerSources) {\n\tconst mergedHeaders = new Headers();\n\tfor (const headerSource of headerSources) {\n\t\tif (!headerSource) continue;\n\t\tif (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);\n\t\telse if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);\n\t\telse for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);\n\t}\n\treturn mergedHeaders;\n}\nvar OutputContext = class {\n\t/**\n\t* Creates an error response.\n\t*\n\t* Shortcut for `throw new FragnoApiError(...)`\n\t*/\n\terror = ({ message, code }, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: 500,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tempty = (initOrStatus, headers) => {\n\t\tconst defaultHeaders = {};\n\t\tif (typeof initOrStatus === \"undefined\") {\n\t\t\tconst mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 201,\n\t\t\t\theaders: mergedHeaders$1\n\t\t\t});\n\t\t}\n\t\tif (typeof initOrStatus === \"number\") {\n\t\t\tconst mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: initOrStatus,\n\t\t\t\theaders: mergedHeaders$1\n\t\t\t});\n\t\t}\n\t\tconst mergedHeaders = mergeHeaders(defaultHeaders, initOrStatus.headers, headers);\n\t\treturn new Response(null, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjson = (object, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json(object, {\n\t\t\tstatus: 200,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json(object, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json(object, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjsonStream = (cb, { onError, headers } = {}) => {\n\t\tconst defaultHeaders = {\n\t\t\t\"content-type\": \"application/x-ndjson; charset=utf-8\",\n\t\t\t\"transfer-encoding\": \"chunked\",\n\t\t\t\"cache-control\": \"no-cache\"\n\t\t};\n\t\tconst { readable, writable } = new TransformStream();\n\t\tconst stream = new ResponseStream(writable, readable);\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tawait cb(stream);\n\t\t\t} catch (e) {\n\t\t\t\tif (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);\n\t\t\t\telse console.error(e);\n\t\t\t} finally {\n\t\t\t\tstream.close();\n\t\t\t}\n\t\t})();\n\t\treturn new Response(stream.responseReadable, {\n\t\t\tstatus: 200,\n\t\t\theaders: mergeHeaders(defaultHeaders, headers)\n\t\t});\n\t};\n};\nvar RequestOutputContext = class extends OutputContext {\n\t#outputSchema;\n\tconstructor(outputSchema) {\n\t\tsuper();\n\t\tthis.#outputSchema = outputSchema;\n\t}\n};\n\n//#endregion\nexport { OutputContext, RequestOutputContext };\n//# sourceMappingURL=request-output-context.js.map","//#region src/api/internal/path.ts\n/**\n* Extract parameter names from a path pattern at runtime.\n* Examples:\n* - \"/users/:id\" => [\"id\"]\n* - \"/files/**\" => [\"**\"]\n* - \"/files/**:rest\" => [\"rest\"]\n*/\nfunction extractPathParams(pathPattern) {\n\tconst segments = pathPattern.split(\"/\").filter((s) => s.length > 0);\n\tconst names = [];\n\tfor (const segment of segments) {\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tnames.push(segment.slice(1));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tnames.push(\"**\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tnames.push(segment.slice(3));\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn names;\n}\n/**\n* Build a concrete path by replacing placeholders in a path pattern with values.\n*\n* Supports the same placeholder syntax as the matcher:\n* - Named parameter \":name\" is URL-encoded as a single segment\n* - Anonymous wildcard \"**\" inserts the remainder as-is (slashes preserved)\n* - Named wildcard \"**:name\" inserts the remainder from the named key\n*\n* Examples:\n* - buildPath(\"/users/:id\", { id: \"123\" }) => \"/users/123\"\n* - buildPath(\"/files/**\", { \"**\": \"a/b\" }) => \"/files/a/b\"\n* - buildPath(\"/files/**:rest\", { rest: \"a/b\" }) => \"/files/a/b\"\n*/\nfunction buildPath(pathPattern, params) {\n\tconst patternSegments = pathPattern.split(\"/\");\n\tconst builtSegments = [];\n\tfor (const segment of patternSegments) {\n\t\tif (segment.length === 0) {\n\t\t\tbuiltSegments.push(\"\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tconst name = segment.slice(1);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path parameter :${name}`);\n\t\t\tbuiltSegments.push(encodeURIComponent(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tconst value = params[\"**\"];\n\t\t\tif (value === void 0) throw new Error(\"Missing value for path wildcard **\");\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tconst name = segment.slice(3);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tbuiltSegments.push(segment);\n\t}\n\treturn builtSegments.join(\"/\");\n}\n\n//#endregion\nexport { buildPath, extractPathParams };\n//# sourceMappingURL=path.js.map","//#region src/client/client-error.ts\n/**\n* Base error class for all Fragno client errors.\n*/\nvar FragnoClientError = class extends Error {\n\t#code;\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, { cause: options.cause });\n\t\tthis.name = \"FragnoClientError\";\n\t\tthis.#code = code;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n};\nvar FragnoClientFetchError = class extends FragnoClientError {\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientFetchError\";\n\t}\n\tstatic fromUnknownFetchError(error) {\n\t\tif (!(error instanceof Error)) return new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t\tif (error.name === \"AbortError\") return new FragnoClientFetchAbortError(\"Request was aborted\", { cause: error });\n\t\treturn new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t}\n};\n/**\n* Error thrown when a network request fails (e.g., no internet connection, DNS failure).\n*/\nvar FragnoClientFetchNetworkError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Network request failed\", options = {}) {\n\t\tsuper(message, \"NETWORK_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchNetworkError\";\n\t}\n};\n/**\n* Error thrown when a request is aborted (e.g., user cancels request, timeout).\n*/\nvar FragnoClientFetchAbortError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Request was aborted\", options = {}) {\n\t\tsuper(message, \"ABORT_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchAbortError\";\n\t}\n};\n/**\n* Error thrown when the API result is unexpected, e.g. no json is returned.\n*/\nvar FragnoClientUnknownApiError = class extends FragnoClientError {\n\t#status;\n\tconstructor(message = \"Unknown API error\", status, options = {}) {\n\t\tsuper(message, \"UNKNOWN_API_ERROR\", options);\n\t\tthis.name = \"FragnoClientUnknownApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n};\nvar FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {\n\t#status;\n\tconstructor({ message, code }, status, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\t/**\n\t* The error code returned by the API.\n\t*\n\t* The type is `TErrorCode` (the set of known error codes for this route), but may also be a string\n\t* for forward compatibility with future error codes.\n\t*/\n\tget code() {\n\t\treturn super.code;\n\t}\n\tstatic async fromResponse(response) {\n\t\tconst unknown = await response.json();\n\t\tconst status = response.status;\n\t\tif (!(\"message\" in unknown || \"code\" in unknown)) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\tif (!(typeof unknown.message === \"string\" && typeof unknown.code === \"string\")) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\treturn new FragnoClientApiError({\n\t\t\tmessage: unknown.message,\n\t\t\tcode: unknown.code\n\t\t}, status);\n\t}\n};\n\n//#endregion\nexport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError };\n//# sourceMappingURL=client-error.js.map","//#region src/util/content-type.ts\n/**\n* Parses a content-type header string into its components\n*\n* @param contentType - The content-type header value to parse\n* @returns A ParsedContentType object or null if the input is invalid\n*\n* @example\n* ```ts\n* const { type, subtype, mediaType, parameters }\n* = parseContentType(\"application/json; charset=utf-8\");\n* console.assert(type === \"application\");\n* console.assert(subtype === \"json\");\n* console.assert(mediaType === \"application/json\");\n* console.assert(parameters[\"charset\"] === \"utf-8\");\n*/\nfunction parseContentType(contentType) {\n\tif (!contentType || typeof contentType !== \"string\") return null;\n\tconst trimmed = contentType.trim();\n\tif (!trimmed) return null;\n\tconst parts = trimmed.split(\";\").map((part) => part.trim());\n\tconst mediaType = parts[0];\n\tif (!mediaType) return null;\n\tconst typeParts = mediaType.split(\"/\");\n\tif (typeParts.length !== 2) return null;\n\tconst [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());\n\tif (!type || !subtype) return null;\n\tconst parameters = {};\n\tfor (let i = 1; i < parts.length; i++) {\n\t\tconst param = parts[i];\n\t\tconst equalIndex = param.indexOf(\"=\");\n\t\tif (equalIndex > 0) {\n\t\t\tconst key = param.slice(0, equalIndex).trim().toLowerCase();\n\t\t\tlet value = param.slice(equalIndex + 1).trim();\n\t\t\tif (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) value = value.slice(1, -1);\n\t\t\tif (key) parameters[key] = value;\n\t\t}\n\t}\n\treturn {\n\t\ttype,\n\t\tsubtype,\n\t\tmediaType: `${type}/${subtype}`,\n\t\tparameters\n\t};\n}\n\n//#endregion\nexport { parseContentType };\n//# sourceMappingURL=content-type.js.map","import { FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientUnknownApiError } from \"../client-error.js\";\n\n//#region src/client/internal/ndjson-streaming.ts\n/**\n* Creates a promise that rejects when the abort signal is triggered\n*/\nfunction createAbortPromise(abortSignal) {\n\treturn new Promise((_, reject) => {\n\t\tconst abortHandler = () => {\n\t\t\treject(new FragnoClientFetchAbortError(\"Operation was aborted\"));\n\t\t};\n\t\tif (abortSignal.aborted) abortHandler();\n\t\telse abortSignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t});\n}\n/**\n* Handles NDJSON streaming responses by returning the first item from the fetcher\n* and then continuing to stream updates via the store's mutate method.\n*\n* This makes it so that we can wait until the first chunk before updating the store, if we did\n* not do this, `loading` would briefly be false before the first item would be populated in the\n* result.\n*\n* @param response - The fetch Response object containing the NDJSON stream\n* @param store - The fetcher store to update with streaming data\n* @param abortSignal - Optional AbortSignal to cancel the streaming operation\n* @returns A promise that resolves to an object containing the first item and a streaming promise\n*/\nasync function handleNdjsonStreamingFirstItem(response, store, options = {}) {\n\tif (!response.body) throw new FragnoClientFetchError(\"Streaming response has no body\", \"NO_BODY\");\n\tconst { abortSignal } = options;\n\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\tconst decoder = new TextDecoder();\n\tconst reader = response.body.getReader();\n\tlet buffer = \"\";\n\tlet firstItem = null;\n\tconst items = [];\n\ttry {\n\t\twhile (firstItem === null) {\n\t\t\tif (abortSignal?.aborted) {\n\t\t\t\treader.releaseLock();\n\t\t\t\tthrow new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\t}\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tif (firstItem === null) {\n\t\t\t\t\t\tfirstItem = jsonObject;\n\t\t\t\t\t\tconst streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tfirstItem,\n\t\t\t\t\t\t\tstreamingPromise\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 500, { cause: parseError });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (firstItem === null) {\n\t\t\treader.releaseLock();\n\t\t\tthrow new FragnoClientUnknownApiError(\"NDJSON stream contained no valid items\", 500);\n\t\t}\n\t\treader.releaseLock();\n\t\tthrow new FragnoClientFetchError(\"Unexpected end of stream processing\", \"NO_BODY\");\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientError) {\n\t\t\tstore?.setError(error);\n\t\t\tthrow error;\n\t\t} else {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 500, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\n\t}\n}\n/**\n* Continues streaming the remaining items in the background\n*/\nasync function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {\n\tlet buffer = initialBuffer;\n\ttry {\n\t\twhile (true) {\n\t\t\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) {\n\t\t\t\tif (buffer.trim()) {\n\t\t\t\t\tconst lines$1 = buffer.split(\"\\n\");\n\t\t\t\t\tfor (const line of lines$1) {\n\t\t\t\t\t\tif (!line.trim()) continue;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t\t\t} catch (parseError) {\n\t\t\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientError) store?.setError(error);\n\t\telse {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 400, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn items;\n}\n\n//#endregion\nexport { handleNdjsonStreamingFirstItem };\n//# sourceMappingURL=ndjson-streaming.js.map","let tasks = 0\nlet resolves = []\n\nexport function startTask() {\n tasks += 1\n return () => {\n tasks -= 1\n if (tasks === 0) {\n let prevResolves = resolves\n resolves = []\n for (let i of prevResolves) i()\n }\n }\n}\n\nexport function task(cb) {\n let endTask = startTask()\n let promise = cb().finally(endTask)\n promise.t = true\n return promise\n}\n\nexport function allTasks() {\n if (tasks === 0) {\n return Promise.resolve()\n } else {\n return new Promise(resolve => {\n resolves.push(resolve)\n })\n }\n}\n\nexport function cleanTasks() {\n tasks = 0\n}\n","import { cleanTasks } from '../task/index.js'\n\nexport let clean = Symbol('clean')\n\nexport let cleanStores = (...stores) => {\n if (process.env.NODE_ENV === 'production') {\n throw new Error(\n 'cleanStores() can be used only during development or tests'\n )\n }\n cleanTasks()\n for (let $store of stores) {\n if ($store) {\n if ($store.mocked) delete $store.mocked\n if ($store[clean]) $store[clean]()\n }\n }\n}\n","import { clean } from '../clean-stores/index.js'\n\nlet listenerQueue = []\nlet lqIndex = 0\nconst QUEUE_ITEMS_PER_LISTENER = 4\nexport let epoch = 0\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const atom = initialValue => {\n let listeners = []\n let $atom = {\n get() {\n if (!$atom.lc) {\n $atom.listen(() => {})()\n }\n return $atom.value\n },\n lc: 0,\n listen(listener) {\n $atom.lc = listeners.push(listener)\n\n return () => {\n for (\n let i = lqIndex + QUEUE_ITEMS_PER_LISTENER;\n i < listenerQueue.length;\n\n ) {\n if (listenerQueue[i] === listener) {\n listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER)\n } else {\n i += QUEUE_ITEMS_PER_LISTENER\n }\n }\n\n let index = listeners.indexOf(listener)\n if (~index) {\n listeners.splice(index, 1)\n if (!--$atom.lc) $atom.off()\n }\n }\n },\n notify(oldValue, changedKey) {\n epoch++\n let runListenerQueue = !listenerQueue.length\n for (let listener of listeners) {\n listenerQueue.push(listener, $atom.value, oldValue, changedKey)\n }\n\n if (runListenerQueue) {\n for (\n lqIndex = 0;\n lqIndex < listenerQueue.length;\n lqIndex += QUEUE_ITEMS_PER_LISTENER\n ) {\n listenerQueue[lqIndex](\n listenerQueue[lqIndex + 1],\n listenerQueue[lqIndex + 2],\n listenerQueue[lqIndex + 3]\n )\n }\n listenerQueue.length = 0\n }\n },\n /* It will be called on last listener unsubscribing.\n We will redefine it in onMount and onStop. */\n off() {},\n set(newValue) {\n let oldValue = $atom.value\n if (oldValue !== newValue) {\n $atom.value = newValue\n $atom.notify(oldValue)\n }\n },\n subscribe(listener) {\n let unbind = $atom.listen(listener)\n listener($atom.value)\n return unbind\n },\n value: initialValue\n }\n\n if (process.env.NODE_ENV !== 'production') {\n $atom[clean] = () => {\n listeners = []\n $atom.lc = 0\n $atom.off()\n }\n }\n\n return $atom\n}\n\nexport const readonlyType = store => store\n","import { clean } from '../clean-stores/index.js'\n\nconst START = 0\nconst STOP = 1\nconst SET = 2\nconst NOTIFY = 3\nconst MOUNT = 5\nconst UNMOUNT = 6\nconst REVERT_MUTATION = 10\n\nexport let on = (object, listener, eventKey, mutateStore) => {\n object.events = object.events || {}\n if (!object.events[eventKey + REVERT_MUTATION]) {\n object.events[eventKey + REVERT_MUTATION] = mutateStore(eventProps => {\n // eslint-disable-next-line no-sequences\n object.events[eventKey].reduceRight((event, l) => (l(event), event), {\n shared: {},\n ...eventProps\n })\n })\n }\n object.events[eventKey] = object.events[eventKey] || []\n object.events[eventKey].push(listener)\n return () => {\n let currentListeners = object.events[eventKey]\n let index = currentListeners.indexOf(listener)\n currentListeners.splice(index, 1)\n if (!currentListeners.length) {\n delete object.events[eventKey]\n object.events[eventKey + REVERT_MUTATION]()\n delete object.events[eventKey + REVERT_MUTATION]\n }\n }\n}\n\nexport let onStart = ($store, listener) =>\n on($store, listener, START, runListeners => {\n let originListen = $store.listen\n $store.listen = arg => {\n if (!$store.lc && !$store.starting) {\n $store.starting = true\n runListeners()\n delete $store.starting\n }\n return originListen(arg)\n }\n return () => {\n $store.listen = originListen\n }\n })\n\nexport let onStop = ($store, listener) =>\n on($store, listener, STOP, runListeners => {\n let originOff = $store.off\n $store.off = () => {\n runListeners()\n originOff()\n }\n return () => {\n $store.off = originOff\n }\n })\n\nexport let onSet = ($store, listener) =>\n on($store, listener, SET, runListeners => {\n let originSet = $store.set\n let originSetKey = $store.setKey\n if ($store.setKey) {\n $store.setKey = (changed, changedValue) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({\n abort,\n changed,\n newValue: { ...$store.value, [changed]: changedValue }\n })\n if (!isAborted) return originSetKey(changed, changedValue)\n }\n }\n $store.set = newValue => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, newValue })\n if (!isAborted) return originSet(newValue)\n }\n return () => {\n $store.set = originSet\n $store.setKey = originSetKey\n }\n })\n\nexport let onNotify = ($store, listener) =>\n on($store, listener, NOTIFY, runListeners => {\n let originNotify = $store.notify\n $store.notify = (oldValue, changed) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, changed, oldValue })\n if (!isAborted) return originNotify(oldValue, changed)\n }\n return () => {\n $store.notify = originNotify\n }\n })\n\nexport let STORE_UNMOUNT_DELAY = 1000\n\nexport let onMount = ($store, initialize) => {\n let listener = payload => {\n let destroy = initialize(payload)\n if (destroy) $store.events[UNMOUNT].push(destroy)\n }\n return on($store, listener, MOUNT, runListeners => {\n let originListen = $store.listen\n $store.listen = (...args) => {\n if (!$store.lc && !$store.active) {\n $store.active = true\n runListeners()\n }\n return originListen(...args)\n }\n\n let originOff = $store.off\n $store.events[UNMOUNT] = []\n $store.off = () => {\n originOff()\n setTimeout(() => {\n if ($store.active && !$store.lc) {\n $store.active = false\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n }\n }, STORE_UNMOUNT_DELAY)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n let originClean = $store[clean]\n $store[clean] = () => {\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n $store.active = false\n originClean()\n }\n }\n\n return () => {\n $store.listen = originListen\n $store.off = originOff\n }\n })\n}\n","import { atom, epoch } from '../atom/index.js'\nimport { onMount } from '../lifecycle/index.js'\n\nlet computedStore = (stores, cb, batched) => {\n if (!Array.isArray(stores)) stores = [stores]\n\n let previousArgs\n let currentEpoch\n let set = () => {\n if (currentEpoch === epoch) return\n currentEpoch = epoch\n let args = stores.map($store => $store.get())\n if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {\n previousArgs = args\n let value = cb(...args)\n if (value && value.then && value.t) {\n value.then(asyncValue => {\n if (previousArgs === args) {\n // Prevent a stale set\n $computed.set(asyncValue)\n }\n })\n } else {\n $computed.set(value)\n currentEpoch = epoch\n }\n }\n }\n let $computed = atom(undefined)\n let get = $computed.get\n $computed.get = () => {\n set()\n return get()\n }\n\n let timer\n let run = batched\n ? () => {\n clearTimeout(timer)\n timer = setTimeout(set)\n }\n : set\n\n onMount($computed, () => {\n let unbinds = stores.map($store => $store.listen(run))\n set()\n return () => {\n for (let unbind of unbinds) unbind()\n }\n })\n\n return $computed\n}\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const computed = (stores, fn) => computedStore(stores, fn)\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const batched = (stores, fn) => computedStore(stores, fn, true)\n","import { atom } from '../atom/index.js'\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const map = (initial = {}) => {\n let $map = atom(initial)\n\n $map.setKey = function (key, value) {\n let oldMap = $map.value\n if (typeof value === 'undefined' && key in $map.value) {\n $map.value = { ...$map.value }\n delete $map.value[key]\n $map.notify(oldMap, key)\n } else if ($map.value[key] !== value) {\n $map.value = {\n ...$map.value,\n [key]: value\n }\n $map.notify(oldMap, key)\n }\n }\n\n return $map\n}\n","import { allTasks } from \"nanostores\";\n\n//#region src/util/ssr.ts\nlet stores = [];\nconst SSR_ENABLED = false;\nfunction getStores() {\n\treturn stores;\n}\nfunction addStore(store) {\n\tstores.push(store);\n}\nfunction cleanStores() {\n\tstores = [];\n}\nlet clientInitialData;\nfunction hydrateFromWindow() {\n\tif (typeof window !== \"undefined\" && window.__FRAGNO_INITIAL_DATA__) {\n\t\tclientInitialData = new Map(window.__FRAGNO_INITIAL_DATA__);\n\t\tdelete window.__FRAGNO_INITIAL_DATA__;\n\t\tconsole.warn(\"hydrateFromWindow\", { clientInitialData: Array.from(clientInitialData.entries()) });\n\t}\n}\nfunction getInitialData(key) {\n\tif (clientInitialData?.has(key)) {\n\t\tconst data = clientInitialData.get(key);\n\t\tclientInitialData.delete(key);\n\t\treturn data;\n\t}\n}\nfunction listenToStores() {\n\tfor (const store of getStores()) store.listen(() => {});\n}\nasync function getFinalStoreValues() {\n\tlistenToStores();\n\tawait allTasks();\n\tconst stores$1 = getStores();\n\tconst storesInitialValue = /* @__PURE__ */ new Map();\n\tfor (const store of stores$1) {\n\t\tconst value = store.get();\n\t\tif (!value || !store.key || value.loading) continue;\n\t\tstoresInitialValue.set(store.key, value.data);\n\t}\n\treturn storesInitialValue;\n}\n\n//#endregion\nexport { SSR_ENABLED, addStore, cleanStores, getFinalStoreValues, getInitialData, hydrateFromWindow };\n//# sourceMappingURL=ssr.js.map","//#region src/util/nanostores.ts\n/**\n* Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.\n*/\nfunction unwrapAtom(value) {\n\tif (value && typeof value === \"object\" && \"get\" in value && typeof value.get === \"function\") return value.get();\n\treturn value;\n}\n/**\n* Normalizes an object where values can be plain values, Atoms, or Vue Refs.\n* Returns a new object with all values normalized to plain values.\n*/\nfunction unwrapObject(params) {\n\tif (!params) return;\n\treturn Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));\n}\nfunction isReadableAtom(value) {\n\tif (!value) return false;\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"get\" in value) || typeof value.get !== \"function\") return false;\n\tif (!(\"lc\" in value) || typeof value.lc !== \"number\") return false;\n\tif (!(\"notify\" in value) || typeof value.notify !== \"function\") return false;\n\tif (!(\"off\" in value) || typeof value.off !== \"function\") return false;\n\tif (!(\"subscribe\" in value) || typeof value.subscribe !== \"function\") return false;\n\tif (!(\"value\" in value)) return false;\n\treturn true;\n}\n\n//#endregion\nexport { isReadableAtom, unwrapObject };\n//# sourceMappingURL=nanostores.js.map","//#region src/client/internal/fetcher-merge.ts\n/**\n* Merge two fetcher configurations, with user config taking precedence.\n* If user provides a custom function, it takes full precedence.\n* Otherwise, deep merge RequestInit options.\n*/\nfunction mergeFetcherConfigs(authorConfig, userConfig) {\n\tif (userConfig?.type === \"function\") return userConfig;\n\tif (!userConfig && authorConfig?.type === \"function\") return authorConfig;\n\tconst authorOpts = authorConfig?.type === \"options\" ? authorConfig.options : {};\n\tconst userOpts = userConfig?.type === \"options\" ? userConfig.options : {};\n\tif (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;\n\treturn {\n\t\ttype: \"options\",\n\t\toptions: {\n\t\t\t...authorOpts,\n\t\t\t...userOpts,\n\t\t\theaders: mergeHeaders(authorOpts.headers, userOpts.headers)\n\t\t}\n\t};\n}\n/**\n* Merge headers from author and user configs.\n* User headers override author headers.\n*/\nfunction mergeHeaders(author, user) {\n\tif (!author && !user) return;\n\tconst merged = new Headers(author);\n\tnew Headers(user).forEach((value, key) => merged.set(key, value));\n\tif (merged.keys().next().done) return;\n\treturn merged;\n}\n\n//#endregion\nexport { mergeFetcherConfigs };\n//# sourceMappingURL=fetcher-merge.js.map","export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n","import { map, onStart, onStop, atom, batched, startTask } from 'nanostores';\nimport { createNanoEvents } from 'nanoevents';\n\nfunction defaultOnErrorRetry({ retryCount }) {\n return ~~((Math.random() + 0.5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;\n}\nconst nanoqueryFactory = ([\n isAppVisible,\n visibilityChangeSubscribe,\n reconnectChangeSubscribe\n]) => {\n const nanoquery = ({\n cache = /* @__PURE__ */ new Map(),\n fetcher: globalFetcher,\n ...globalSettings\n } = {}) => {\n const events = createNanoEvents();\n let focus = true;\n visibilityChangeSubscribe(() => {\n focus = isAppVisible();\n focus && events.emit(FOCUS);\n });\n reconnectChangeSubscribe(() => events.emit(RECONNECT));\n const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();\n let rewrittenSettings = {};\n const getCachedValueByKey = (key) => {\n const fromCache = cache.get(key);\n if (!fromCache)\n return [];\n const cacheHit = (fromCache.expires || 0) > getNow();\n return cacheHit ? [fromCache.data, fromCache.error] : [];\n };\n const runFetcher = async ([key, keyParts], store, settings) => {\n if (!focus)\n return;\n const set = (v) => {\n if (store.key === key) {\n store.set(v);\n events.emit(SET_CACHE, key, v, true);\n }\n };\n const setAsLoading = (prev) => {\n const toSet = prev === void 0 ? {} : { data: prev };\n set({\n ...toSet,\n ...loading,\n promise: _runningFetches.get(key)\n });\n };\n let {\n dedupeTime = 4e3,\n cacheLifetime = Infinity,\n fetcher,\n onErrorRetry = defaultOnErrorRetry\n } = {\n ...settings,\n ...rewrittenSettings\n };\n if (cacheLifetime < dedupeTime)\n cacheLifetime = dedupeTime;\n const now = getNow();\n if (_runningFetches.has(key)) {\n if (!store.value.loading)\n setAsLoading(getCachedValueByKey(key)[0]);\n return;\n }\n let cachedValue, cachedError;\n const fromCache = cache.get(key);\n if (fromCache?.data !== void 0 || fromCache?.error) {\n [cachedValue, cachedError] = getCachedValueByKey(key);\n if ((fromCache.created || 0) + dedupeTime > now) {\n if (store.value.data != cachedValue || store.value.error != cachedError) {\n set({ ...notLoading, data: cachedValue, error: cachedError });\n }\n return;\n }\n }\n const finishTask = startTask();\n try {\n clearTimeout(_errorInvalidateTimeouts.get(key));\n const promise = fetcher(...keyParts);\n _runningFetches.set(key, promise);\n setAsLoading(cachedValue);\n const res = await promise;\n cache.set(key, {\n data: res,\n created: getNow(),\n expires: getNow() + cacheLifetime\n });\n set({ data: res, ...notLoading });\n } catch (error) {\n settings.onError?.(error);\n const retryCount = (cache.get(key)?.retryCount || 0) + 1;\n cache.set(key, {\n error,\n created: getNow(),\n expires: getNow() + cacheLifetime,\n retryCount\n });\n if (onErrorRetry) {\n const timer = onErrorRetry({\n error,\n key,\n retryCount\n });\n if (timer)\n _errorInvalidateTimeouts.set(\n key,\n setTimeout(() => {\n invalidateKeys(key);\n cache.set(key, { retryCount });\n }, timer)\n );\n }\n set({ data: store.value.data, error, ...notLoading });\n } finally {\n finishTask();\n _runningFetches.delete(key);\n }\n };\n const createFetcherStore = (keyInput, {\n fetcher = globalFetcher,\n ...fetcherSettings\n } = {}) => {\n if (process.env.NODE_ENV !== \"production\" && !fetcher) {\n throw new Error(\n \"You need to set up either global fetcher of fetcher in createFetcherStore\"\n );\n }\n const fetcherStore = map({\n ...notLoading\n }), settings = { ...globalSettings, ...fetcherSettings, fetcher };\n fetcherStore._ = fetcherSymbol;\n fetcherStore.invalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n invalidateKeys(key);\n }\n };\n fetcherStore.revalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n revalidateKeys(key);\n }\n };\n fetcherStore.mutate = (data) => {\n const { key } = fetcherStore;\n if (key) {\n mutateCache(key, data);\n }\n };\n fetcherStore.fetch = async () => {\n let resolve;\n const promise = new Promise((r) => resolve = r);\n const unsub = fetcherStore.listen(({ error, data }) => {\n if (error !== void 0)\n resolve({ error });\n if (data !== void 0)\n resolve({ data });\n });\n return promise.finally(unsub);\n };\n let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;\n let evtUnsubs = [];\n onStart(fetcherStore, () => {\n const firstRun = !keysInternalUnsub;\n [keyStore, keysInternalUnsub] = getKeyStore(keyInput);\n keyUnsub = keyStore.subscribe((currentKeys) => {\n if (currentKeys) {\n const [newKey, keyParts] = currentKeys;\n fetcherStore.key = newKey;\n runFetcher([newKey, keyParts], fetcherStore, settings);\n prevKey = newKey;\n prevKeyParts = keyParts;\n } else {\n fetcherStore.key = prevKey = prevKeyParts = void 0;\n fetcherStore.set({ ...notLoading });\n }\n });\n const currentKeyValue = keyStore.get();\n if (currentKeyValue) {\n [prevKey, prevKeyParts] = currentKeyValue;\n if (firstRun)\n handleNewListener();\n }\n const {\n revalidateInterval = 0,\n revalidateOnFocus,\n revalidateOnReconnect\n } = settings;\n const runRefetcher = () => {\n if (prevKey)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n if (revalidateInterval > 0) {\n _revalidateOnInterval.set(\n keyInput,\n setInterval(runRefetcher, revalidateInterval)\n );\n }\n if (revalidateOnFocus)\n evtUnsubs.push(events.on(FOCUS, runRefetcher));\n if (revalidateOnReconnect)\n evtUnsubs.push(events.on(RECONNECT, runRefetcher));\n const cacheKeyChangeHandler = (keySelector) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) {\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n }\n };\n evtUnsubs.push(\n events.on(INVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(REVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(SET_CACHE, (keySelector, data, full) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) {\n fetcherStore.set(\n full ? data : { data, ...notLoading }\n );\n }\n })\n );\n });\n const handleNewListener = () => {\n if (prevKey && prevKeyParts)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n const originListen = fetcherStore.listen;\n fetcherStore.listen = (listener) => {\n const unsub = originListen(listener);\n listener(fetcherStore.value);\n handleNewListener();\n return unsub;\n };\n onStop(fetcherStore, () => {\n fetcherStore.value = { ...notLoading };\n keysInternalUnsub?.();\n evtUnsubs.forEach((fn) => fn());\n evtUnsubs = [];\n keyUnsub?.();\n clearInterval(_revalidateOnInterval.get(keyInput));\n });\n return fetcherStore;\n };\n const iterOverCache = (keySelector, cb) => {\n for (const key of cache.keys()) {\n if (testKeyAgainstSelector(key, keySelector))\n cb(key);\n }\n };\n const invalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n cache.delete(key);\n });\n events.emit(INVALIDATE_KEYS, keySelector);\n };\n const revalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n const cached = cache.get(key);\n if (cached) {\n cache.set(key, { ...cached, created: -Infinity });\n }\n });\n events.emit(REVALIDATE_KEYS, keySelector);\n };\n const mutateCache = (keySelector, data) => {\n iterOverCache(keySelector, (key) => {\n if (data === void 0)\n cache.delete(key);\n else {\n cache.set(key, {\n data,\n created: getNow(),\n expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)\n });\n }\n });\n events.emit(SET_CACHE, keySelector, data);\n };\n function createMutatorStore(mutator, opts) {\n const { throttleCalls, onError } = opts ?? {\n throttleCalls: true,\n onError: globalSettings?.onError\n };\n const mutate = async (data) => {\n if (throttleCalls && store.value?.loading)\n return;\n const newMutator = rewrittenSettings.fetcher ?? mutator;\n const keysToInvalidate = [], keysToRevalidate = [];\n const safeKeySet = (k, v) => {\n if (store.lc) {\n store.setKey(k, v);\n }\n };\n try {\n store.set({\n error: void 0,\n data: void 0,\n mutate,\n ...loading\n });\n const result = await newMutator({\n data,\n invalidate: (key) => {\n keysToInvalidate.push(key);\n },\n revalidate: (key) => {\n keysToRevalidate.push(key);\n },\n getCacheUpdater: (key, shouldRevalidate = true) => [\n (newVal) => {\n mutateCache(key, newVal);\n if (shouldRevalidate) {\n keysToRevalidate.push(key);\n }\n },\n cache.get(key)?.data\n ]\n });\n safeKeySet(\"data\", result);\n return result;\n } catch (error) {\n onError?.(error);\n safeKeySet(\"error\", error);\n store.setKey(\"error\", error);\n } finally {\n safeKeySet(\"loading\", false);\n keysToInvalidate.forEach(invalidateKeys);\n keysToRevalidate.forEach(revalidateKeys);\n }\n };\n const store = map({\n mutate,\n ...notLoading\n });\n onStop(\n store,\n () => store.set({ mutate, ...notLoading })\n );\n store.mutate = mutate;\n return store;\n }\n const __unsafeOverruleSettings = (data) => {\n if (process.env.NODE_ENV !== \"test\") {\n console.warn(\n `You should only use __unsafeOverruleSettings in test environment`\n );\n }\n rewrittenSettings = data;\n };\n return [\n createFetcherStore,\n createMutatorStore,\n { __unsafeOverruleSettings, invalidateKeys, revalidateKeys, mutateCache }\n ];\n };\n function isSomeKey(key) {\n return typeof key === \"string\" || typeof key === \"number\" || key === true;\n }\n const getKeyStore = (keys) => {\n if (isSomeKey(keys))\n return [\n atom([\"\" + keys, [keys]]),\n () => {\n }\n ];\n const keyParts = [];\n const $key = atom(null);\n const keysAsStoresToIndexes = /* @__PURE__ */ new Map();\n const setKeyStoreValue = () => {\n if (keyParts.some((v) => v === null || v === void 0 || v === false)) {\n $key.set(null);\n } else {\n $key.set([keyParts.join(\"\"), keyParts]);\n }\n };\n for (let i = 0; i < keys.length; i++) {\n const keyOrStore = keys[i];\n if (isSomeKey(keyOrStore)) {\n keyParts.push(keyOrStore);\n } else {\n keyParts.push(null);\n keysAsStoresToIndexes.set(keyOrStore, i);\n }\n }\n const storesAsArray = [...keysAsStoresToIndexes.keys()];\n const $storeKeys = batched(storesAsArray, (...storeValues) => {\n for (let i = 0; i < storeValues.length; i++) {\n const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);\n keyParts[partIndex] = store._ === fetcherSymbol ? store.value && \"data\" in store.value ? store.key : null : storeValues[i];\n }\n setKeyStoreValue();\n });\n setKeyStoreValue();\n return [$key, $storeKeys.subscribe(noop)];\n };\n function noop() {\n }\n const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;\n const testKeyAgainstSelector = (key, selector) => {\n if (Array.isArray(selector))\n return selector.includes(key);\n else if (typeof selector === \"function\")\n return selector(key);\n else\n return key === selector;\n };\n const getNow = () => (/* @__PURE__ */ new Date()).getTime();\n const fetcherSymbol = Symbol();\n const loading = { loading: true }, notLoading = { loading: false };\n return nanoquery;\n};\n\nconst subscribe = (name, fn) => {\n const isServer = typeof window === \"undefined\";\n if (!isServer) {\n addEventListener(name, fn);\n }\n};\nconst browserCompat = [\n () => !document.hidden,\n (cb) => subscribe(\"visibilitychange\", cb),\n (cb) => subscribe(\"online\", cb)\n];\n\nconst nanoquery = nanoqueryFactory(browserCompat);\n\nexport { nanoquery, defaultOnErrorRetry as onErrorRetry };\n","import { resolveRouteFactories } from \"../api/route.js\";\nimport { getMountRoute } from \"../api/internal/route.js\";\nimport { RequestInputContext } from \"../api/request-input-context.js\";\nimport { RequestOutputContext } from \"../api/request-output-context.js\";\nimport { buildPath, extractPathParams } from \"../api/internal/path.js\";\nimport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError } from \"./client-error.js\";\nimport { parseContentType } from \"../util/content-type.js\";\nimport { handleNdjsonStreamingFirstItem } from \"./internal/ndjson-streaming.js\";\nimport { SSR_ENABLED, addStore, getInitialData } from \"../util/ssr.js\";\nimport { unwrapObject } from \"../util/nanostores.js\";\nimport { mergeFetcherConfigs } from \"./internal/fetcher-merge.js\";\nimport { computed, task } from \"nanostores\";\nimport { nanoquery } from \"@nanostores/query\";\n\n//#region src/client/client.ts\n/**\n* Symbols used to identify hook types\n*/\nconst GET_HOOK_SYMBOL = Symbol(\"fragno-get-hook\");\nconst MUTATOR_HOOK_SYMBOL = Symbol(\"fragno-mutator-hook\");\nconst STORE_SYMBOL = Symbol(\"fragno-store\");\n/**\n* @internal\n*/\nfunction buildUrl(config, params) {\n\tconst { baseUrl = \"\", mountRoute, path } = config;\n\tconst { pathParams, queryParams } = params ?? {};\n\tconst normalizedPathParams = unwrapObject(pathParams);\n\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\treturn `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : \"\"}`;\n}\n/**\n* This method returns an array, which can be passed directly to nanostores.\n*\n* The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)\n* Missing pathParams are replaced with \"<missing>\".\n* Atoms with undefined values are wrapped in computed atoms that map undefined to \"\" to avoid nanoquery treating the key as incomplete.\n* @param path\n* @param params\n* @returns\n* @internal\n*/\nfunction getCacheKey(method, path, params) {\n\tif (!params) return [method, path];\n\tconst { pathParams, queryParams } = params;\n\tconst pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? \"<missing>\");\n\tconst queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {\n\t\tconst value = queryParams[key];\n\t\tif (value && typeof value === \"object\" && \"get\" in value) return computed(value, (v) => v ?? \"\");\n\t\treturn value ?? \"\";\n\t}) : [];\n\treturn [\n\t\tmethod,\n\t\tpath,\n\t\t...pathParamValues,\n\t\t...queryParamValues\n\t];\n}\nfunction isStreamingResponse(response) {\n\tconst contentType = parseContentType(response.headers.get(\"content-type\"));\n\tif (!contentType) return false;\n\tif (!(response.headers.get(\"transfer-encoding\") === \"chunked\")) return false;\n\tif (contentType.subtype === \"octet-stream\") return \"octet-stream\";\n\tif (contentType.subtype === \"x-ndjson\") return \"ndjson\";\n\treturn false;\n}\n/**\n* @internal\n*/\nfunction isGetHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isMutatorHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isStore(obj) {\n\treturn typeof obj === \"object\" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;\n}\nvar ClientBuilder = class {\n\t#publicConfig;\n\t#fragmentConfig;\n\t#fetcherConfig;\n\t#cache = /* @__PURE__ */ new Map();\n\t#createFetcherStore;\n\t#createMutatorStore;\n\t#invalidateKeys;\n\tconstructor(publicConfig, fragmentConfig) {\n\t\tthis.#publicConfig = publicConfig;\n\t\tthis.#fragmentConfig = fragmentConfig;\n\t\tthis.#fetcherConfig = publicConfig.fetcherConfig;\n\t\tconst [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({ cache: this.#cache });\n\t\tthis.#createFetcherStore = createFetcherStore;\n\t\tthis.#createMutatorStore = createMutatorStore;\n\t\tthis.#invalidateKeys = invalidateKeys;\n\t}\n\tget cacheEntries() {\n\t\treturn Object.fromEntries(this.#cache.entries());\n\t}\n\tcreateStore(obj) {\n\t\treturn {\n\t\t\tobj,\n\t\t\t[STORE_SYMBOL]: true\n\t\t};\n\t}\n\t/**\n\t* Build a URL for a custom backend call using the configured baseUrl and mountRoute.\n\t* Useful for fragment authors who need to make custom fetch calls.\n\t*/\n\tbuildUrl(path, params) {\n\t\treturn buildUrl({\n\t\t\tbaseUrl: this.#publicConfig.baseUrl ?? \"\",\n\t\t\tmountRoute: getMountRoute(this.#fragmentConfig),\n\t\t\tpath\n\t\t}, {\n\t\t\tpathParams: params?.path,\n\t\t\tqueryParams: params?.query\n\t\t});\n\t}\n\t/**\n\t* Get the configured fetcher function for custom backend calls.\n\t* Returns fetch with merged options applied.\n\t*/\n\tgetFetcher() {\n\t\treturn {\n\t\t\tfetcher: this.#getFetcher(),\n\t\t\tdefaultOptions: this.#getFetcherOptions()\n\t\t};\n\t}\n\t#getFetcher() {\n\t\tif (this.#fetcherConfig?.type === \"function\") return this.#fetcherConfig.fetcher;\n\t\treturn fetch;\n\t}\n\t#getFetcherOptions() {\n\t\tif (this.#fetcherConfig?.type === \"options\") return this.#fetcherConfig.options;\n\t}\n\tcreateHook(path, options) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === \"GET\" && r.outputSchema !== void 0);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);\n\t\treturn this.#createRouteQueryHook(route, options);\n\t}\n\tcreateMutator(method, path, onInvalidate) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.method !== \"GET\" && r.path === path && r.method === method);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);\n\t\treturn this.#createRouteQueryMutator(route, onInvalidate);\n\t}\n\t#createRouteQueryHook(route, options = {}) {\n\t\tif (route.method !== \"GET\") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${route.method} route.`);\n\t\tif (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tasync function callServerSideHandler(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tconst normalizedPathParams = unwrapObject(pathParams);\n\t\t\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\t\t\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\t\t\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\t\t\treturn await route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tmethod: route.method,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: normalizedPathParams,\n\t\t\t\tsearchParams\n\t\t\t}), new RequestOutputContext(route.outputSchema));\n\t\t}\n\t\tasync function executeQuery(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tif (typeof window === \"undefined\") return task(async () => callServerSideHandler({\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t}));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\treturn {\n\t\t\troute,\n\t\t\tstore: (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst key = getCacheKey(route.method, route.path, {\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst store = this.#createFetcherStore(key, {\n\t\t\t\t\tfetcher: async () => {\n\t\t\t\t\t\tif (SSR_ENABLED) {\n\t\t\t\t\t\t\tconst initialData = getInitialData(key.map((d) => typeof d === \"string\" ? d : d.get()).join(\"\"));\n\t\t\t\t\t\t\tif (initialData) return initialData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\t\t\tpathParams: path,\n\t\t\t\t\t\t\tqueryParams: query\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\t\t\tif (!isStreaming) return response.json();\n\t\t\t\t\t\tif (typeof window === \"undefined\") return [];\n\t\t\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\t\t\t\tstore.set({\n\t\t\t\t\t\t\t\t\t\t...store.get(),\n\t\t\t\t\t\t\t\t\t\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\t\t\t\tstore.set({\n\t\t\t\t\t\t\t\t\t\t...store.get(),\n\t\t\t\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn [firstItem];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t\t\t},\n\t\t\t\t\tonErrorRetry: options?.onErrorRetry,\n\t\t\t\t\tdedupeTime: Infinity\n\t\t\t\t});\n\t\t\t\tif (typeof window === \"undefined\") addStore(store);\n\t\t\t\treturn store;\n\t\t\t},\n\t\t\tquery: async (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\tif (!isStreaming) return await response.json();\n\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\t\treturn await streamingPromise;\n\t\t\t\t}\n\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t},\n\t\t\t[GET_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#createRouteQueryMutator(route, onInvalidate = (invalidate, params) => invalidate(\"GET\", route.path, params)) {\n\t\tconst method = route.method;\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tasync function executeMutateQuery({ body, path, query }) {\n\t\t\tif (typeof window === \"undefined\") return task(async () => route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tinputSchema: route.inputSchema,\n\t\t\t\tmethod,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tsearchParams: new URLSearchParams(query),\n\t\t\t\tbody\n\t\t\t}), new RequestOutputContext(route.outputSchema)));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams: path,\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = await fetcher(url, {\n\t\t\t\t\t...fetcherOptions,\n\t\t\t\t\tmethod,\n\t\t\t\t\tbody: body !== void 0 ? JSON.stringify(body) : void 0\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\tconst mutatorStore = this.#createMutatorStore(async ({ data }) => {\n\t\t\tif (typeof window === \"undefined\") {}\n\t\t\tconst { body, path, query } = data;\n\t\t\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"Body is required.\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tonInvalidate(this.#invalidate.bind(this), {\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return response.json();\n\t\t\tif (typeof window === \"undefined\") return [];\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn [firstItem];\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t}, { onError: (error) => {\n\t\t\tconsole.error(\"Error in mutatorStore\", error);\n\t\t} });\n\t\tconst mutateQuery = (async (data) => {\n\t\t\tconst { body, path, query } = data;\n\t\t\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"Body is required for mutateQuery\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return response.json();\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\treturn await streamingPromise;\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported for mutations\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t});\n\t\treturn {\n\t\t\troute,\n\t\t\tmutateQuery,\n\t\t\tmutatorStore,\n\t\t\t[MUTATOR_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#invalidate(method, path, params) {\n\t\tconst prefix = getCacheKey(method, path, {\n\t\t\tpathParams: params?.pathParams,\n\t\t\tqueryParams: params?.queryParams\n\t\t}).map((k) => typeof k === \"string\" ? k : k.get()).join(\"\");\n\t\tthis.#invalidateKeys((key) => key.startsWith(prefix));\n\t}\n};\n/**\n* Create a client builder for fragments using the new fragment definition API.\n* This is the same as createClientBuilder but works with FragmentDefinition.\n*/\nfunction createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {\n\tconst routes = resolveRouteFactories({\n\t\tconfig: {},\n\t\tdeps: {},\n\t\tservices: {},\n\t\tserviceDeps: {}\n\t}, routesOrFactories);\n\tconst fragmentConfig = {\n\t\tname: definition.name,\n\t\troutes\n\t};\n\tconst mountRoute = publicConfig.mountRoute ?? `/${definition.name}`;\n\tconst mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);\n\treturn new ClientBuilder({\n\t\t...publicConfig,\n\t\tmountRoute,\n\t\tfetcherConfig: mergedFetcherConfig\n\t}, fragmentConfig);\n}\n\n//#endregion\nexport { ClientBuilder, FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError, buildUrl, createClientBuilder, getCacheKey, isGetHook, isMutatorHook, isStore };\n//# sourceMappingURL=client.js.map","import { defineFragment } from \"@fragno-dev/core\";\nimport { withDatabase } from \"@fragno-dev/db\";\nimport { formsSchema } from \"./schema\";\nimport type { FormsConfig } from \".\";\nimport type { JSONSchema, NewForm, UpdateForm, FormStatus, UIElementSchema } from \"./models\";\nimport { Validator, type Schema } from \"@cfworker/json-schema\";\n\nexport type ValidatedData<T = Record<string, unknown>> = T;\nexport type ValidationResult =\n | { success: true; data: ValidatedData }\n | {\n success: false;\n error: { message: string; errors: Array<{ path: string; message: string }> };\n };\n\n// External to this fragment\nconst asExternalForm = <\n T extends { id: { externalId: string }; status: string; dataSchema: unknown; uiSchema: unknown },\n>(\n form: T,\n) => ({\n ...form,\n id: form.id.externalId,\n status: form.status as FormStatus,\n dataSchema: form.dataSchema as JSONSchema,\n uiSchema: form.uiSchema as UIElementSchema,\n});\n\nconst asExternalResponse = <\n T extends {\n id: { externalId: string };\n formId: string | null;\n data: unknown;\n ip: string | null;\n userAgent: string | null;\n },\n>(\n response: T,\n) => ({\n ...response,\n id: response.id.externalId,\n data: response.data as Record<string, unknown>,\n});\n\nexport interface SubmissionSortOptions {\n field: \"submittedAt\";\n order: \"asc\" | \"desc\";\n}\n\nexport const formsFragmentDef = defineFragment<FormsConfig>(\"forms\")\n .extend(withDatabase(formsSchema))\n .withDependencies(({ db }) => ({ db }))\n .providesBaseService(({ deps }) => {\n return {\n createForm: async (input: NewForm) => {\n return (await deps.db.create(\"form\", input)).externalId;\n },\n\n getForm: async (id: string) => {\n const form = await deps.db.findFirst(\"form\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)),\n );\n return form ? asExternalForm(form) : null;\n },\n\n getFormBySlug: async (slug: string) => {\n const form = await deps.db.findFirst(\"form\", (b) =>\n b.whereIndex(\"idx_form_slug\", (eb) => eb(\"slug\", \"=\", slug)),\n );\n return form ? asExternalForm(form) : null;\n },\n\n updateForm: async (id: string, input: UpdateForm) => {\n const uow = deps.db\n .createUnitOfWork()\n .find(\"form\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)));\n\n const [currentForms] = await uow.executeRetrieve();\n\n if (currentForms.length === 0) {\n return { success: false };\n }\n // TODO: length > 1 ?\n\n const currentForm = currentForms[0];\n\n // Only increment version if changing data schema\n const newVersion = input.dataSchema ? currentForm.version + 1 : currentForm.version;\n\n uow.update(\"form\", currentForm.id, (b) => {\n b.set({ ...input, version: newVersion, updatedAt: new Date() }).check();\n });\n return uow.executeMutations();\n },\n\n listForms: async () => {\n const forms = await deps.db.find(\"form\", (b) => b.whereIndex(\"primary\"));\n return forms.map(asExternalForm);\n },\n\n deleteForm: async (id: string) => {\n await deps.db.delete(\"form\", id);\n },\n\n validateData: (schema: Schema, data: Record<string, unknown>): ValidationResult => {\n const validator = new Validator(schema);\n const result = validator.validate(data);\n\n if (result.valid) {\n return { success: true, data: data as ValidatedData };\n }\n console.error(\"ERROR\", JSON.stringify(result.errors));\n return {\n success: false,\n // TODO: better error type for validation errors?\n // see: https://jsonforms.io/docs/validation/#external-validation-errors\n error: {\n message: \"Validation failed\",\n errors: result.errors.map((e) => ({\n path: e.instanceLocation || \"\",\n message: e.error ?? \"Invalid value\",\n })),\n },\n };\n },\n\n createResponse: async (\n formId: string,\n formVersion: number,\n data: ValidatedData,\n metadata?: { ip?: string | null; userAgent?: string | null },\n ) => {\n return (\n await deps.db.create(\"response\", {\n formId,\n formVersion,\n data,\n ip: metadata?.ip ?? null,\n userAgent: metadata?.userAgent ?? null,\n })\n ).externalId;\n },\n\n getResponse: async (id: string) => {\n const response = await deps.db.findFirst(\"response\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)),\n );\n return response ? asExternalResponse(response) : null;\n },\n\n listResponses: async (\n formId: string,\n sort: SubmissionSortOptions = { field: \"submittedAt\", order: \"desc\" },\n ) => {\n const responses = await deps.db.find(\"response\", (b) =>\n b\n .whereIndex(\"idx_response_form\", (eb) => eb(\"formId\", \"=\", formId))\n .orderByIndex(\"idx_response_submitted_at\", sort.order),\n );\n return responses.map(asExternalResponse);\n },\n\n deleteResponse: async (id: string) => {\n return await deps.db.delete(\"response\", id);\n },\n };\n })\n .build();\n","import { z } from \"zod\";\n\nexport const JSONSchemaSchema = z.record(z.string(), z.unknown());\nexport const UISchemaElementSchema = z.record(z.string(), z.unknown());\n\nexport const FormStatusSchema = z.enum([\"draft\", \"open\", \"closed\", \"static\"]);\n\nexport const FormSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().nullable(),\n slug: z.string(),\n status: FormStatusSchema,\n dataSchema: JSONSchemaSchema,\n uiSchema: UISchemaElementSchema,\n version: z.number(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport const NewFormSchema = FormSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n version: true,\n});\n\nexport const UpdateFormSchema = NewFormSchema.partial();\n\nexport const ResponseMetadataSchema = z.object({\n ip: z.union([z.ipv4(), z.ipv6()]).nullable(),\n userAgent: z.string().max(4096).nullable(),\n});\n\nexport const ResponseSchema = z.object({\n id: z.string(),\n formId: z.string().nullable().describe(\"Form ID (static form ID or database form external ID)\"),\n formVersion: z.number(),\n data: z.record(z.string(), z.unknown()),\n submittedAt: z.date(),\n ip: z.string().max(45).nullable(),\n userAgent: z.string().max(512).nullable(),\n});\n\nexport const NewResponseSchema = ResponseSchema.omit({\n id: true,\n submittedAt: true,\n formId: true,\n formVersion: true,\n ip: true,\n userAgent: true,\n}).extend({\n securityToken: z.string().optional(),\n});\n\nexport type NewForm = z.infer<typeof NewFormSchema>;\nexport type UpdateForm = z.infer<typeof UpdateFormSchema>;\nexport type Form = z.infer<typeof FormSchema>;\nexport type NewResponse = z.infer<typeof NewResponseSchema>;\nexport type Response = z.infer<typeof ResponseSchema>;\nexport type ResponseMetadata = z.infer<typeof ResponseMetadataSchema>;\nexport type FormStatus = z.infer<typeof FormStatusSchema>;\nexport type JSONSchema = z.infer<typeof JSONSchemaSchema>;\nexport type UIElementSchema = z.infer<typeof UISchemaElementSchema>;\n","import { defineRoutes } from \"@fragno-dev/core\";\nimport type { Schema } from \"@cfworker/json-schema\";\nimport { z } from \"zod\";\nimport { formsFragmentDef } from \"./definition\";\nimport {\n FormSchema,\n NewFormSchema,\n NewResponseSchema,\n ResponseMetadataSchema,\n ResponseSchema,\n UpdateFormSchema,\n} from \"./models\";\nimport type { Form } from \"./models\";\nimport type { StaticForm } from \".\";\n\n/** Extract and validate request metadata from headers (untrusted input) */\nfunction extractRequestMetadata(headers: Headers) {\n const rawUserAgent = headers.get(\"User-Agent\");\n const rawIp =\n headers.get(\"CF-Connecting-IP\") ||\n headers.get(\"X-Forwarded-For\")?.split(\",\")[0].trim() ||\n headers.get(\"X-Real-IP\") ||\n null;\n const result = ResponseMetadataSchema.safeParse({\n ip: rawIp,\n userAgent: rawUserAgent,\n });\n\n // Return validated data or null values if validation fails\n return result.success ? result.data : { ip: null, userAgent: null };\n}\n\nconst staticAsRegularForm = (sf: StaticForm): Form => ({\n id: sf.id,\n title: sf.title,\n description: sf.description,\n slug: sf.slug,\n status: \"static\",\n dataSchema: sf.dataSchema,\n uiSchema: sf.uiSchema as unknown as Form[\"uiSchema\"],\n version: sf.version,\n createdAt: new Date(),\n updatedAt: new Date(),\n});\n\n// Public routes\nexport const publicRoutes = defineRoutes(formsFragmentDef).create(\n ({ services, defineRoute, config }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/:slug\",\n outputSchema: FormSchema,\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n // Check static forms first\n const staticForm = config.staticForms?.find((f) => f.slug === pathParams.slug);\n if (staticForm) {\n return json(staticAsRegularForm(staticForm));\n }\n\n const form = await services.getFormBySlug(pathParams.slug);\n if (!form) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n\n return json(form);\n },\n }),\n\n defineRoute({\n method: \"POST\",\n path: \"/:slug/submit\",\n inputSchema: NewResponseSchema,\n outputSchema: z.string(),\n errorCodes: [\"NOT_FOUND\", \"VALIDATION_ERROR\", \"FORM_NOT_OPEN\"] as const,\n handler: async ({ input, pathParams, headers }, { json, error }) => {\n const { data } = await input.valid();\n\n // Check static forms first\n const staticFormConfig = config.staticForms?.find((f) => f.slug === pathParams.slug);\n const form = staticFormConfig\n ? staticAsRegularForm(staticFormConfig)\n : await services.getFormBySlug(pathParams.slug);\n\n if (!form) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n\n // Static forms and open forms accept submissions\n if (form.status !== \"open\" && form.status !== \"static\") {\n return error(\n { message: \"Form is not open, has status \" + form.status, code: \"FORM_NOT_OPEN\" },\n 400,\n );\n }\n\n // Form validation\n const result = services.validateData(form.dataSchema as Schema, data);\n\n if (!result.success) {\n const message = result.error.errors.map((e) => e.message).join(\" \");\n return error({ message, code: \"VALIDATION_ERROR\" }, 400);\n }\n\n // Extract and validate request metadata from headers\n const metadata = extractRequestMetadata(headers);\n\n const responseId = await services.createResponse(\n form.id,\n form.version,\n result.data,\n metadata,\n );\n\n if (config.onResponseSubmitted) {\n await config.onResponseSubmitted({\n id: responseId,\n formId: form.id,\n formVersion: form.version,\n data,\n submittedAt: new Date(),\n ip: metadata?.ip,\n userAgent: metadata?.userAgent,\n });\n }\n\n return json(responseId);\n },\n }),\n ];\n },\n);\n\n// Admin routes\nexport const adminRoutes = defineRoutes(formsFragmentDef).create(\n ({ services, defineRoute, config }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/forms\",\n outputSchema: z.array(FormSchema),\n handler: async (_ctx, { json }) => {\n const dbForms = await services.listForms();\n const staticForms = (config.staticForms ?? []).map(staticAsRegularForm);\n return json([...staticForms, ...dbForms]);\n },\n }),\n\n defineRoute({\n method: \"POST\",\n path: \"/admin/forms\",\n inputSchema: NewFormSchema,\n outputSchema: z.string(),\n errorCodes: [\"CREATE_FAILED\"] as const,\n handler: async ({ input }, { json }) => {\n const data = await input.valid();\n const formId = await services.createForm(data);\n if (config.onFormCreated) {\n await config.onFormCreated({ ...data, id: formId });\n }\n return json(formId);\n },\n }),\n\n defineRoute({\n method: \"PUT\",\n path: \"/admin/forms/:id\",\n inputSchema: UpdateFormSchema,\n errorCodes: [\"NOT_FOUND\", \"STATIC_FORM_READ_ONLY\"] as const,\n handler: async ({ input, pathParams }, { json, error }) => {\n const isStatic = config.staticForms?.some((f) => f.id === pathParams.id);\n if (isStatic) {\n return error(\n { message: \"Static forms cannot be modified\", code: \"STATIC_FORM_READ_ONLY\" },\n 403,\n );\n }\n const data = await input.valid();\n const { success } = await services.updateForm(pathParams.id, data);\n if (!success) {\n return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n }\n return json(success);\n },\n }),\n\n defineRoute({\n method: \"DELETE\",\n path: \"/admin/forms/:id\",\n errorCodes: [\"NOT_FOUND\", \"STATIC_FORM_READ_ONLY\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n const isStatic = config.staticForms?.some((f) => f.id === pathParams.id);\n if (isStatic) {\n return error(\n { message: \"Static forms cannot be deleted\", code: \"STATIC_FORM_READ_ONLY\" },\n 403,\n );\n }\n await services.deleteForm(pathParams.id);\n // TODO: 404 when form not found\n // if (!deleted) {\n // return error({ message: \"Form not found\", code: \"NOT_FOUND\" }, 404);\n // }\n return json(true);\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/admin/forms/:id/submissions\",\n queryParameters: [\"sortOrder\"] as const,\n outputSchema: z.array(ResponseSchema),\n handler: async ({ pathParams, query }, { json }) => {\n const sortOrder = query.get(\"sortOrder\") === \"asc\" ? \"asc\" : \"desc\";\n const responses = await services.listResponses(pathParams.id, {\n field: \"submittedAt\",\n order: sortOrder,\n });\n return json(responses);\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/admin/submissions/:id\",\n outputSchema: ResponseSchema,\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json, error }) => {\n const response = await services.getResponse(pathParams.id);\n if (!response) {\n return error({ message: \"Submission not found\", code: \"NOT_FOUND\" }, 404);\n }\n return json(response);\n },\n }),\n\n defineRoute({\n method: \"DELETE\",\n path: \"/admin/submissions/:id\",\n errorCodes: [\"NOT_FOUND\"] as const,\n handler: async ({ pathParams }, { json }) => {\n await services.deleteResponse(pathParams.id);\n // TODO: 404 when response not found\n // if (!deleted) {\n // return error({ message: \"Submission not found\", code: \"NOT_FOUND\" }, 404);\n // }\n return json(true);\n },\n }),\n ];\n },\n);\n","import { createClientBuilder } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicClientConfig } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicConfigWithDatabase } from \"@fragno-dev/db\";\nimport { instantiate } from \"@fragno-dev/core\";\nimport { publicRoutes, adminRoutes } from \"./routes\";\nimport { formsFragmentDef } from \"./definition\";\nimport type { Form, JSONSchema, Response } from \"./models\";\nimport type { UISchemaElement } from \"@jsonforms/core\";\n\n// Forms that exist in code, but submissions are stored in the DB\n// Static forms always have status: \"static\" and accept submissions\nexport interface StaticForm {\n id: string;\n title: string;\n description: string | null;\n slug: string;\n dataSchema: JSONSchema;\n uiSchema: UISchemaElement;\n version: number;\n}\n\nexport interface FormsConfig {\n onFormCreated?: (form: Omit<Form, \"version\" | \"createdAt\" | \"updatedAt\">) => Promise<void>;\n onResponseSubmitted?: (response: Response) => Promise<void>;\n staticForms?: StaticForm[];\n}\n\nexport const routes = [publicRoutes, adminRoutes] as const;\n\nexport function createFormsFragment(\n config: FormsConfig = {},\n options: FragnoPublicConfigWithDatabase,\n) {\n return instantiate(formsFragmentDef)\n .withConfig(config)\n .withRoutes(routes)\n .withOptions(options)\n .build();\n}\n\nexport function createFormsClients(fragnoConfig: FragnoPublicClientConfig) {\n const b = createClientBuilder(formsFragmentDef, fragnoConfig, routes);\n\n return {\n // Public\n useForm: b.createHook(\"/:slug\"),\n useSubmitForm: b.createMutator(\"POST\", \"/:slug/submit\"),\n\n // Admin - Forms\n useForms: b.createHook(\"/admin/forms\"),\n useCreateForm: b.createMutator(\"POST\", \"/admin/forms\"),\n useUpdateForm: b.createMutator(\"PUT\", \"/admin/forms/:id\"),\n useDeleteForm: b.createMutator(\"DELETE\", \"/admin/forms/:id\"),\n\n // Admin - Submissions\n useSubmissions: b.createHook(\"/admin/forms/:id/submissions\"),\n useSubmission: b.createHook(\"/admin/submissions/:id\"),\n useDeleteSubmission: b.createMutator(\"DELETE\", \"/admin/submissions/:id\"),\n };\n}\n\nexport { formsFragmentDef } from \"./definition\";\nexport type { SubmissionSortOptions } from \"./definition\";\nexport type { FragnoRouteConfig } from \"@fragno-dev/core\";\n"],"x_google_ignoreList":[10,11,12,13,14,15,19,20],"mappings":";;;;;;;;AAKA,SAASA,sBAAsBC,SAASC,mBAAmB;CAC1D,MAAMC,WAAS,CAAE;AACjB,MAAK,MAAMC,QAAQF,kBAAmB,YAAWE,SAAS,YAAY;EACrE,MAAMC,gBAAgBD,KAAKH,QAAQ;AACnCE,WAAOG,KAAK,GAAGD,cAAc;CAC7B,MAAMF,UAAOG,KAAKF,KAAK;AACxB,QAAOD;AACR;;;;ACXA,SAASW,cAAcC,MAAM;CAC5B,MAAMC,aAAaD,KAAKC,eAAc,OAAQD,KAAKE,KAAI;AACvD,KAAID,WAAWE,SAAS,IAAI,CAAE,QAAOF,WAAWG,MAAM,GAAG,GAAG;AAC5D,QAAOH;AACR;;;;ACJA,IAAII,iBAAiB,cAAcC,MAAM;CACxC;CACA;CACAG,YAAY,EAAEC,SAASF,MAAM,EAAED,QAAQ;AACtC,QAAMG,QAAQ;AACd,OAAKC,OAAO;AACZ,OAAK,UAAUJ;AACf,OAAK,QAAQC;CACd;CACA,IAAID,SAAS;AACZ,SAAO,KAAK;CACb;CACA,IAAIC,OAAO;AACV,SAAO,KAAK;CACb;CACAI,aAAa;AACZ,SAAOC,SAASC,KAAK;GACpBJ,SAAS,KAAKA;GACdF,MAAM,KAAKA;EACX,GAAE,EAAED,QAAQ,KAAKA,OAAQ,EAAC;CAC5B;AACA;AACD,IAAIQ,2BAA2B,cAAcV,eAAe;CAC3D;CACAI,YAAYC,SAASM,QAAQ;AAC5B,QAAM;GACLN;GACAF,MAAM;EACN,GAAE,IAAI;AACP,OAAKG,OAAO;AACZ,OAAK,UAAUK;CAChB;CACA,IAAIA,SAAS;AACZ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