@fragno-dev/cloudflare-fragment 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +16 -0
- package/README.md +92 -0
- package/dist/browser/client/react.d.ts +290 -0
- package/dist/browser/client/react.d.ts.map +1 -0
- package/dist/browser/client/react.js +166 -0
- package/dist/browser/client/react.js.map +1 -0
- package/dist/browser/client/solid.d.ts +292 -0
- package/dist/browser/client/solid.d.ts.map +1 -0
- package/dist/browser/client/solid.js +136 -0
- package/dist/browser/client/solid.js.map +1 -0
- package/dist/browser/client/svelte.d.ts +287 -0
- package/dist/browser/client/svelte.d.ts.map +1 -0
- package/dist/browser/client/svelte.js +134 -0
- package/dist/browser/client/svelte.js.map +1 -0
- package/dist/browser/client/vanilla.d.ts +316 -0
- package/dist/browser/client/vanilla.d.ts.map +1 -0
- package/dist/browser/client/vanilla.js +160 -0
- package/dist/browser/client/vanilla.js.map +1 -0
- package/dist/browser/client/vue.d.ts +290 -0
- package/dist/browser/client/vue.d.ts.map +1 -0
- package/dist/browser/client/vue.js +133 -0
- package/dist/browser/client/vue.js.map +1 -0
- package/dist/browser/client-Bk-J98pf.d.ts +679 -0
- package/dist/browser/client-Bk-J98pf.d.ts.map +1 -0
- package/dist/browser/index.d.ts +2027 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +27 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/schema-Bt-h9kGf.js +2348 -0
- package/dist/browser/schema-Bt-h9kGf.js.map +1 -0
- package/dist/node/cloudflare-api.d.ts +106 -0
- package/dist/node/cloudflare-api.d.ts.map +1 -0
- package/dist/node/cloudflare-api.js +146 -0
- package/dist/node/cloudflare-api.js.map +1 -0
- package/dist/node/contracts.d.ts +288 -0
- package/dist/node/contracts.d.ts.map +1 -0
- package/dist/node/contracts.js +66 -0
- package/dist/node/contracts.js.map +1 -0
- package/dist/node/definition.d.ts +339 -0
- package/dist/node/definition.d.ts.map +1 -0
- package/dist/node/definition.js +417 -0
- package/dist/node/definition.js.map +1 -0
- package/dist/node/deployment-tag.d.ts +13 -0
- package/dist/node/deployment-tag.d.ts.map +1 -0
- package/dist/node/deployment-tag.js +73 -0
- package/dist/node/deployment-tag.js.map +1 -0
- package/dist/node/index.d.ts +786 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +35 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/routes.d.ts +520 -0
- package/dist/node/routes.d.ts.map +1 -0
- package/dist/node/routes.js +100 -0
- package/dist/node/routes.js.map +1 -0
- package/dist/node/schema.d.ts +11 -0
- package/dist/node/schema.d.ts.map +1 -0
- package/dist/node/schema.js +24 -0
- package/dist/node/schema.js.map +1 -0
- package/dist/node/script-name.d.ts +13 -0
- package/dist/node/script-name.d.ts.map +1 -0
- package/dist/node/script-name.js +35 -0
- package/dist/node/script-name.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +98 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-Bt-h9kGf.js","names":["resolveRouteFactories","context","routesOrFactories","routes","item","factoryRoutes","push","defineRoute","config","defineRoutes","_definition","create","fn","ctx","extractPathParams","pathPattern","segments","split","filter","s","length","names","segment","startsWith","push","slice","buildPath","params","patternSegments","builtSegments","name","value","Error","encodeURIComponent","join","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","formData","FormData","Error","isFormData","bodyStream","ReadableStream","isBodyStream","input","schema","valid","validateInput","#validateInput","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","parseContentType","contentType","trimmed","trim","parts","split","map","part","mediaType","typeParts","length","type","subtype","toLowerCase","parameters","i","param","equalIndex","indexOf","key","slice","value","startsWith","endsWith","unwrapAtom","value","get","unwrapObject","params","Object","fromEntries","entries","map","key","isReadableAtom","lc","notify","off","subscribe","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","FragnoClientError","Error","code","constructor","message","options","cause","name","FragnoClientFetchError","fromUnknownFetchError","error","FragnoClientFetchNetworkError","FragnoClientFetchAbortError","FragnoClientUnknownApiError","status","FragnoClientApiError","fromResponse","response","unknown","json","mergeFetcherConfigs","authorConfig","userConfig","type","authorOpts","options","userOpts","Object","keys","length","headers","mergeHeaders","author","user","merged","Headers","forEach","value","key","set","next","done","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","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","buildPath","extractPathParams","getMountRoute","RequestInputContext","RequestOutputContext","parseContentType","unwrapObject","SSR_ENABLED","addStore","getInitialData","FragnoClientApiError","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientFetchNetworkError","FragnoClientUnknownApiError","mergeFetcherConfigs","handleNdjsonStreamingFirstItem","computed","task","nanoquery","GET_HOOK_SYMBOL","Symbol","MUTATOR_HOOK_SYMBOL","STORE_SYMBOL","containsFiles","value","File","Blob","FormData","Object","values","some","v","toFormData","formData","key","val","entries","append","name","JSON","stringify","prepareRequestBody","body","contentType","ReadableStream","ArrayBuffer","Uint8Array","headers","Error","schemaAllowsUndefined","schema","validate","issues","assertBodyProvided","inputSchema","errorMessage","mergeRequestHeaders","headerSources","result","hasHeaders","source","Headers","Array","isArray","buildUrl","config","params","baseUrl","mountRoute","path","pathParams","queryParams","normalizedPathParams","normalizedQueryParams","filteredQueryParams","fromEntries","filter","_","searchParams","URLSearchParams","toString","getCacheKey","method","pathParamValues","map","queryParamValues","keys","sort","isStreamingResponse","response","get","subtype","isGetHook","hook","isMutatorHook","isStore","obj","ClientBuilder","publicConfig","fragmentConfig","fetcherConfig","cache","Map","createFetcherStore","createMutatorStore","invalidateKeys","constructor","cacheEntries","createStore","input","factory","query","getFetcher","fetcher","defaultOptions","getFetcherOptions","#getFetcher","type","globalThis","fetch","bind","#getFetcherOptions","options","createHook","route","routes","find","r","outputSchema","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","length","data","setError","onErrorRetry","dedupeTime","Infinity","streamingPromise","#createRouteQueryMutator","invalidate","executeMutateQuery","preparedBody","bodyHeaders","mergedHeaders","requestOptions","duplex","mutatorStore","status","onError","console","mutateQuery","#invalidate","prefix","k","startsWith","createClientBuilder","definition","routesOrFactories","authorFetcherConfig","deps","services","serviceDeps","mergedFetcherConfig","DEFAULT_DEPLOYMENT_TAG_PREFIX","MAX_TAG_LENGTH","APP_TAG_SEGMENT","DEPLOYMENT_TAG_SEGMENT","sanitizeCloudflareTag","value","toLowerCase","replace","normalizeCloudflareDeploymentTagPrefix","prefix","normalized","Error","trimTrailingHyphens","capCloudflareTagPrefix","kind","normalizedId","label","maxPrefixLength","length","cappedPrefix","slice","buildCloudflareScopedTag","id","normalizedPrefix","readCloudflareScopedTagId","tag","normalizedTag","marker","markerIndex","indexOf","expectedPrefix","tagPrefix","findCloudflareScopedTag","tags","includes","buildCloudflareAppTag","appId","buildCloudflareDeploymentTag","deploymentId","getCloudflareAppIdFromTag","getCloudflareDeploymentIdFromTag","findCloudflareAppTag","findCloudflareDeploymentTag","Cloudflare","NotFoundError","toFile","ClientOptions","CloudflareClientOptions","ScriptUpdateParams","ScriptUpdateResponse","buildCloudflareAppTag","buildCloudflareDeploymentTag","findCloudflareDeploymentTag","getCloudflareDeploymentIdFromTag","sanitizeCloudflareTag","CloudflareDispatchNamespaceBinding","get","name","args","Record","options","CloudflareDispatchNamespaceDescriptor","binding","namespace","CloudflareDispatcherConfig","CloudflareApiClientConfig","apiToken","fetchImplementation","maxRetries","CloudflareApiClient","CloudflareScriptUpdateParams","CloudflareScriptUpdateResponse","DeployCloudflareWorkerInput","accountId","dispatchNamespace","scriptName","entrypoint","moduleContent","compatibilityDate","compatibilityFlags","tags","ifMatch","ReconcileCloudflareWorkerDeploymentInput","appId","deploymentId","expectedLiveEtag","deploymentTagPrefix","scriptTags","CloudflareDeploymentReconciliationResult","action","deploymentTag","currentDeploymentTag","currentDeploymentId","currentEtag","currentModifiedOn","response","CloudflareCurrentDeployment","CloudflareScriptState","etag","modifiedOn","isRecord","value","readNamespaceCandidate","trimmed","trim","length","unique","items","T","Array","from","Set","hasBindingDescriptor","resolveCloudflareDispatchNamespaceName","dispatcher","Error","buildCloudflareScriptTags","dynamicTags","staticTags","normalizedDynamicTags","isArray","map","filter","tag","createCloudflareApiClient","fetch","listCloudflareScriptTags","client","input","workersForPlatforms","dispatch","namespaces","scripts","list","account_id","results","push","error","getCloudflareCurrentDeployment","Promise","remoteTags","getCloudflareScriptState","script","modified_on","deployCloudflareWorker","moduleFile","TextEncoder","encode","type","params","metadata","main_module","compatibility_date","compatibility_flags","undefined","files","update","headers","reconcileCloudflareWorkerDeployment","appTag","cloudflareError","getCloudflareApiError","status","currentDeployment","scriptState","all","APIError","firstError","errors","code","String","message","details","z","SUPPORTED_DEPLOYMENT_FORMAT","DEFAULT_DEPLOYMENT_ENTRYPOINT","cloudflareCompatibilityDateSchema","string","regex","cloudflareDeploymentStatusSchema","enum","cloudflareDeployScriptSchema","object","type","default","entrypoint","trim","min","content","cloudflareDeployRequestSchema","script","compatibilityDate","optional","compatibilityFlags","array","cloudflareTimestampSchema","datetime","offset","cloudflareProviderSummarySchema","etag","nullable","modifiedOn","cloudflareDeploymentSummarySchema","id","appId","scriptName","status","format","literal","sourceByteLength","number","int","nonnegative","attemptCount","queuedAt","startedAt","completedAt","errorCode","errorMessage","cloudflare","createdAt","updatedAt","cloudflareDeploymentDetailSchema","extend","sourceCode","cloudflareAppSummarySchema","latestDeployment","cloudflareAppStateSchema","liveDeployment","liveDeploymentError","deployments","cloudflareAppListSchema","apps","cloudflareDeploymentListSchema","CloudflareDeploymentStatus","infer","CloudflareDeployRequest","CloudflareDeploymentSummary","CloudflareDeploymentDetail","CloudflareAppSummary","CloudflareAppState","CloudflareAppList","CloudflareDeploymentList","CloudflareScriptNameConfig","scriptNamePrefix","scriptNameSuffix","scriptNameSeparator","maxScriptNameLength","DEFAULT_SCRIPT_NAME_SEPARATOR","DEFAULT_MAX_SCRIPT_NAME_LENGTH","normalizeSeparator","value","cleaned","replace","length","sanitizeSegment","toLowerCase","hashString","hash","char","charCodeAt","Math","imul","toString","padStart","resolveCloudflareScriptName","appId","config","separator","maxLength","max","segments","map","segment","filter","Boolean","base","join","budget","trimmedBase","slice","candidate","ClientOptions","CloudflareClientOptions","defineFragment","HookFn","reconcileCloudflareWorkerDeployment","CloudflareApiClient","CloudflareDispatcherConfig","CloudflareScriptUpdateResponse","CloudflareAppSummary","CloudflareDeployRequest","CloudflareDeploymentDetail","CloudflareDeploymentSummary","CloudflareScriptNameConfig","DeploymentRow","id","valueOf","status","format","entrypoint","scriptName","sourceByteLength","compatibilityDate","compatibilityFlags","attemptCount","startedAt","Date","completedAt","errorCode","errorMessage","cloudflareEtag","cloudflareModifiedOn","createdAt","updatedAt","AppRow","liveDeploymentId","liveCloudflareEtag","firstDeploymentLeaseId","CloudflareLiveDeploymentSnapshot","currentDeploymentTag","currentDeploymentId","currentEtag","currentModifiedOn","DeployWorkerRemoteResult","Awaited","ReturnType","action","FirstDeploymentPreparation","LivePointerGuard","kind","expectedLiveEtag","leaseDeploymentId","CloudflareFragmentSharedConfig","accountId","scriptTags","deploymentTagPrefix","CloudflareFragmentApiTokenConfig","apiToken","cloudflare","fetchImplementation","CloudflareFragmentClientConfig","CloudflareFragmentConfig","dispatcher","dispatchNamespace","DeployWorkerHookInput","deploymentId","appId","moduleContent","CloudflareHooksMap","deployWorker","cloudflareFragmentDefinition","extend","x","withDependencies","providesService","deps","getClient","providesBaseService","build","defineRoutes","cloudflareAppListSchema","cloudflareAppStateSchema","cloudflareDeployRequestSchema","cloudflareDeploymentDetailSchema","cloudflareDeploymentListSchema","cloudflareDeploymentSummarySchema","cloudflareFragmentDefinition","cloudflareRoutesFactory","create","services","defineRoute","method","path","outputSchema","handler","inputSchema","errorCodes","column","idColumn","referenceColumn","schema","cloudflareSchema","s","addTable","t","addColumn","nullable","defaultTo","b","now","createIndex","unique","addReference","type","from","table","to"],"sources":["../../../fragno/dist/api/route.js","../../../fragno/dist/api/internal/path.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/util/content-type.js","../../../fragno/dist/util/nanostores.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/client/client-error.js","../../../fragno/dist/client/internal/fetcher-merge.js","../../../fragno/dist/client/internal/ndjson-streaming.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/deployment-tag.ts","../../src/cloudflare-api.ts","../../src/contracts.ts","../../src/script-name.ts","../../src/definition.ts","../../src/routes.ts","../../src/schema.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/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/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* Access the request body as FormData.\n\t*\n\t* Use this method when handling file uploads or multipart form submissions.\n\t* The request must have been sent with Content-Type: multipart/form-data.\n\t*\n\t* @throws Error if the request body is not FormData\n\t*\n\t* @example\n\t* ```typescript\n\t* defineRoute({\n\t* method: \"POST\",\n\t* path: \"/upload\",\n\t* async handler(ctx, res) {\n\t* const formData = ctx.formData();\n\t* const file = formData.get(\"file\") as File;\n\t* const description = formData.get(\"description\") as string;\n\t* // ... process file\n\t* }\n\t* });\n\t* ```\n\t*/\n\tformData() {\n\t\tif (!(this.#parsedBody instanceof FormData)) throw new Error(\"Request body is not FormData. Ensure the request was sent with Content-Type: multipart/form-data.\");\n\t\treturn this.#parsedBody;\n\t}\n\t/**\n\t* Check if the request body is FormData.\n\t*\n\t* Useful for routes that accept both JSON and FormData payloads.\n\t*\n\t* @example\n\t* ```typescript\n\t* defineRoute({\n\t* method: \"POST\",\n\t* path: \"/upload\",\n\t* async handler(ctx, res) {\n\t* if (ctx.isFormData()) {\n\t* const formData = ctx.formData();\n\t* // handle file upload\n\t* } else {\n\t* const json = await ctx.input.valid();\n\t* // handle JSON payload\n\t* }\n\t* }\n\t* });\n\t* ```\n\t*/\n\tisFormData() {\n\t\treturn this.#parsedBody instanceof FormData;\n\t}\n\t/**\n\t* Access the request body as a ReadableStream (application/octet-stream).\n\t*\n\t* @throws Error if the request body is not a ReadableStream\n\t*/\n\tbodyStream() {\n\t\tif (!(this.#parsedBody instanceof ReadableStream)) throw new Error(\"Request body is not a ReadableStream. Ensure the request was sent with Content-Type: application/octet-stream.\");\n\t\treturn this.#parsedBody;\n\t}\n\t/**\n\t* Check if the request body is a ReadableStream.\n\t*/\n\tisBodyStream() {\n\t\treturn this.#parsedBody instanceof ReadableStream;\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\tif (this.#parsedBody instanceof ReadableStream) throw new Error(\"Schema validation is only supported for JSON data, not FormData, Blob, or ReadableStream\");\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/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","//#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","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/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/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","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","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 { buildPath, extractPathParams } from \"../api/internal/path.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 { parseContentType } from \"../util/content-type.js\";\nimport { unwrapObject } from \"../util/nanostores.js\";\nimport { SSR_ENABLED, addStore, getInitialData } from \"../util/ssr.js\";\nimport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError } from \"./client-error.js\";\nimport { mergeFetcherConfigs } from \"./internal/fetcher-merge.js\";\nimport { handleNdjsonStreamingFirstItem } from \"./internal/ndjson-streaming.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* Check if a value contains files that should be sent as FormData.\n* @internal\n*/\nfunction containsFiles(value) {\n\tif (value instanceof File || value instanceof Blob) return true;\n\tif (value instanceof FormData) return true;\n\tif (typeof value === \"object\" && value !== null) return Object.values(value).some((v) => v instanceof File || v instanceof Blob || v instanceof FormData);\n\treturn false;\n}\n/**\n* Convert an object containing files to FormData.\n* Handles nested File/Blob values by appending them directly.\n* Other values are JSON-stringified.\n* @internal\n*/\nfunction toFormData(value) {\n\tconst formData = new FormData();\n\tfor (const [key, val] of Object.entries(value)) if (val instanceof File) formData.append(key, val, val.name);\n\telse if (val instanceof Blob) formData.append(key, val);\n\telse if (val !== void 0 && val !== null) formData.append(key, typeof val === \"string\" ? val : JSON.stringify(val));\n\treturn formData;\n}\n/**\n* Prepare request body and headers for sending.\n* Handles FormData (file uploads) vs JSON data.\n* @internal\n*/\nfunction prepareRequestBody(body, contentType) {\n\tif (body === void 0) return { body: void 0 };\n\tif (contentType === \"application/octet-stream\") {\n\t\tif (body instanceof ReadableStream || body instanceof Blob || body instanceof File || body instanceof ArrayBuffer || body instanceof Uint8Array) return {\n\t\t\tbody,\n\t\t\theaders: { \"Content-Type\": \"application/octet-stream\" }\n\t\t};\n\t\tthrow new Error(\"Octet-stream routes only accept Blob, File, ArrayBuffer, Uint8Array, or ReadableStream bodies.\");\n\t}\n\tif (body instanceof FormData) return { body };\n\tif (body instanceof File) {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", body, body.name);\n\t\treturn { body: formData };\n\t}\n\tif (body instanceof Blob) {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", body);\n\t\treturn { body: formData };\n\t}\n\tif (typeof body === \"object\" && body !== null && containsFiles(body)) return { body: toFormData(body) };\n\treturn {\n\t\tbody: JSON.stringify(body),\n\t\theaders: { \"Content-Type\": \"application/json\" }\n\t};\n}\nasync function schemaAllowsUndefined(schema) {\n\ttry {\n\t\treturn !(await schema[\"~standard\"].validate(void 0)).issues;\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function assertBodyProvided(body, inputSchema, errorMessage) {\n\tif (typeof body !== \"undefined\" || inputSchema === void 0) return;\n\tif (await schemaAllowsUndefined(inputSchema)) return;\n\tthrow new Error(errorMessage);\n}\n/**\n* Merge request headers from multiple sources.\n* Returns undefined if there are no headers to merge.\n* @internal\n*/\nfunction mergeRequestHeaders(...headerSources) {\n\tconst result = {};\n\tlet hasHeaders = false;\n\tfor (const source of headerSources) {\n\t\tif (!source) continue;\n\t\tif (source instanceof Headers) for (const [key, value] of source.entries()) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t\telse if (Array.isArray(source)) for (const [key, value] of source) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t\telse for (const [key, value] of Object.entries(source)) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t}\n\treturn hasHeaders ? result : void 0;\n}\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(input) {\n\t\tif (typeof input === \"function\") return {\n\t\t\tfactory: input,\n\t\t\t[STORE_SYMBOL]: true\n\t\t};\n\t\treturn {\n\t\t\tobj: input,\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({\n\t\t\t\tname: this.#fragmentConfig.name,\n\t\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t\t}),\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 globalThis.fetch.bind(globalThis);\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({\n\t\t\tname: this.#fragmentConfig.name,\n\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t});\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({\n\t\t\tname: this.#fragmentConfig.name,\n\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t});\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\tconst { body: preparedBody, headers: bodyHeaders } = prepareRequestBody(body, route.contentType);\n\t\t\t\tconst mergedHeaders = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);\n\t\t\t\tconst requestOptions = {\n\t\t\t\t\t...fetcherOptions,\n\t\t\t\t\tmethod,\n\t\t\t\t\tbody: preparedBody,\n\t\t\t\t\t...mergedHeaders ? { headers: mergedHeaders } : {}\n\t\t\t\t};\n\t\t\t\tif (preparedBody instanceof ReadableStream) requestOptions.duplex = \"half\";\n\t\t\t\tresponse = await fetcher(url, requestOptions);\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\tawait assertBodyProvided(body, route.inputSchema, \"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\tawait assertBodyProvided(body, route.inputSchema, \"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 = getMountRoute({\n\t\tname: definition.name,\n\t\tmountRoute: publicConfig.mountRoute\n\t});\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","export const DEFAULT_DEPLOYMENT_TAG_PREFIX = \"fragno\";\n\nconst MAX_TAG_LENGTH = 63;\nconst APP_TAG_SEGMENT = \"app\";\nconst DEPLOYMENT_TAG_SEGMENT = \"dep\";\n\nexport const sanitizeCloudflareTag = (value: string) => {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+/, \"\")\n .replace(/-+$/, \"\")\n .replace(/--+/g, \"-\");\n};\n\nexport const normalizeCloudflareDeploymentTagPrefix = (prefix?: string) => {\n const normalized = sanitizeCloudflareTag(prefix ?? DEFAULT_DEPLOYMENT_TAG_PREFIX);\n if (!normalized) {\n throw new Error(\n \"Cloudflare deployment tag prefix must contain at least one alphanumeric character.\",\n );\n }\n\n return normalized;\n};\n\nconst trimTrailingHyphens = (value: string) => value.replace(/-+$/, \"\");\n\nconst capCloudflareTagPrefix = (\n prefix: string,\n kind: string,\n normalizedId: string,\n label: string,\n) => {\n const maxPrefixLength = MAX_TAG_LENGTH - `-${kind}-`.length - normalizedId.length;\n if (maxPrefixLength < 1) {\n throw new Error(\n `Cloudflare ${label} tag '${normalizedId}' exceeds the ${MAX_TAG_LENGTH} character limit even with the shortest possible prefix.`,\n );\n }\n\n const cappedPrefix = trimTrailingHyphens(prefix.slice(0, maxPrefixLength));\n if (!cappedPrefix) {\n throw new Error(\n `Cloudflare ${label} tag prefix must retain at least one alphanumeric character after capping.`,\n );\n }\n\n return cappedPrefix;\n};\n\nconst buildCloudflareScopedTag = (\n id: string,\n prefix: string | undefined,\n kind: string,\n label: string,\n) => {\n const normalizedPrefix = normalizeCloudflareDeploymentTagPrefix(prefix);\n const normalizedId = sanitizeCloudflareTag(id);\n\n if (!normalizedId) {\n throw new Error(`Cloudflare ${label} id must contain at least one alphanumeric character.`);\n }\n\n const cappedPrefix = capCloudflareTagPrefix(normalizedPrefix, kind, normalizedId, label);\n return `${cappedPrefix}-${kind}-${normalizedId}`;\n};\n\nconst readCloudflareScopedTagId = (\n tag: string,\n prefix: string | undefined,\n kind: string,\n label: string,\n) => {\n const normalizedTag = sanitizeCloudflareTag(tag);\n const marker = `-${kind}-`;\n const normalizedPrefix = normalizeCloudflareDeploymentTagPrefix(prefix);\n let markerIndex = normalizedTag.indexOf(marker);\n\n while (markerIndex >= 1) {\n const normalizedId = normalizedTag.slice(markerIndex + marker.length);\n if (normalizedId) {\n try {\n const expectedPrefix = capCloudflareTagPrefix(normalizedPrefix, kind, normalizedId, label);\n const tagPrefix = normalizedTag.slice(0, markerIndex);\n if (tagPrefix === expectedPrefix) {\n return normalizedId;\n }\n } catch {\n // Ignore unrelated tags that happen to contain the same marker.\n }\n }\n\n markerIndex = normalizedTag.indexOf(marker, markerIndex + 1);\n }\n\n return null;\n};\n\nconst findCloudflareScopedTag = (\n tags: string[],\n prefix: string | undefined,\n kind: string,\n label: string,\n) => {\n const marker = `-${kind}-`;\n\n for (const tag of tags) {\n const normalizedTag = sanitizeCloudflareTag(tag);\n if (!normalizedTag.includes(marker)) {\n continue;\n }\n\n const id = readCloudflareScopedTagId(normalizedTag, prefix, kind, label);\n if (id !== null) {\n return normalizedTag;\n }\n }\n\n return null;\n};\n\nexport const buildCloudflareAppTag = (appId: string, prefix?: string) => {\n return buildCloudflareScopedTag(appId, prefix, APP_TAG_SEGMENT, \"app\");\n};\n\nexport const buildCloudflareDeploymentTag = (deploymentId: string, prefix?: string) => {\n return buildCloudflareScopedTag(deploymentId, prefix, DEPLOYMENT_TAG_SEGMENT, \"deployment\");\n};\n\nexport const getCloudflareAppIdFromTag = (tag: string, prefix?: string) => {\n return readCloudflareScopedTagId(tag, prefix, APP_TAG_SEGMENT, \"app\");\n};\n\nexport const getCloudflareDeploymentIdFromTag = (tag: string, prefix?: string) => {\n return readCloudflareScopedTagId(tag, prefix, DEPLOYMENT_TAG_SEGMENT, \"deployment\");\n};\n\nexport const findCloudflareAppTag = (tags: string[], prefix?: string) => {\n return findCloudflareScopedTag(tags, prefix, APP_TAG_SEGMENT, \"app\");\n};\n\nexport const findCloudflareDeploymentTag = (tags: string[], prefix?: string) => {\n return findCloudflareScopedTag(tags, prefix, DEPLOYMENT_TAG_SEGMENT, \"deployment\");\n};\n","import Cloudflare, {\n NotFoundError,\n toFile,\n type ClientOptions as CloudflareClientOptions,\n} from \"cloudflare\";\nimport type {\n ScriptUpdateParams,\n ScriptUpdateResponse,\n} from \"cloudflare/resources/workers-for-platforms/dispatch/namespaces/scripts/scripts\";\n\nimport {\n buildCloudflareAppTag,\n buildCloudflareDeploymentTag,\n findCloudflareDeploymentTag,\n getCloudflareDeploymentIdFromTag,\n sanitizeCloudflareTag,\n} from \"./deployment-tag\";\n\nexport type CloudflareDispatchNamespaceBinding = {\n get(name: string, args?: Record<string, unknown>, options?: unknown): unknown;\n};\n\nexport type CloudflareDispatchNamespaceDescriptor = {\n binding: CloudflareDispatchNamespaceBinding;\n namespace: string;\n};\n\nexport type CloudflareDispatcherConfig = string | CloudflareDispatchNamespaceDescriptor;\n\ntype CloudflareApiClientConfig = {\n apiToken: string;\n fetchImplementation?: CloudflareClientOptions[\"fetch\"];\n maxRetries?: number;\n};\n\nexport type CloudflareApiClient = Cloudflare;\nexport type CloudflareScriptUpdateParams = ScriptUpdateParams;\nexport type CloudflareScriptUpdateResponse = ScriptUpdateResponse;\n\nexport type DeployCloudflareWorkerInput = {\n accountId: string;\n dispatchNamespace: string;\n scriptName: string;\n entrypoint: string;\n moduleContent: string;\n compatibilityDate: string;\n compatibilityFlags: string[];\n tags?: string[];\n ifMatch?: string | null;\n};\n\nexport type ReconcileCloudflareWorkerDeploymentInput = {\n accountId: string;\n dispatchNamespace: string;\n appId: string;\n deploymentId: string;\n expectedLiveEtag: string | null;\n deploymentTagPrefix?: string;\n scriptName: string;\n entrypoint: string;\n moduleContent: string;\n compatibilityDate: string;\n compatibilityFlags: string[];\n scriptTags?: string[];\n};\n\nexport type CloudflareDeploymentReconciliationResult =\n | {\n action: \"already-deployed\";\n deploymentTag: string;\n currentDeploymentTag: string;\n currentDeploymentId: string | null;\n currentEtag: string | null;\n currentModifiedOn: string | null;\n }\n | {\n action: \"uploaded\";\n deploymentTag: string;\n response: CloudflareScriptUpdateResponse;\n }\n | {\n action: \"superseded\";\n deploymentTag: string;\n currentDeploymentTag: string;\n currentDeploymentId: string | null;\n currentEtag: string | null;\n currentModifiedOn: string | null;\n };\n\nexport type CloudflareCurrentDeployment = {\n deploymentTag: string;\n deploymentId: string | null;\n} | null;\n\nexport type CloudflareScriptState = {\n etag: string | null;\n modifiedOn: string | null;\n} | null;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst readNamespaceCandidate = (value: unknown) => {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n};\n\nconst unique = <T>(items: T[]) => {\n return Array.from(new Set(items));\n};\n\nconst hasBindingDescriptor = (\n value: CloudflareDispatcherConfig,\n): value is CloudflareDispatchNamespaceDescriptor => {\n return typeof value === \"object\" && value !== null && \"binding\" in value;\n};\n\nexport const resolveCloudflareDispatchNamespaceName = (dispatcher: CloudflareDispatcherConfig) => {\n if (typeof dispatcher === \"string\") {\n const namespace = readNamespaceCandidate(dispatcher);\n if (namespace) {\n return namespace;\n }\n } else if (hasBindingDescriptor(dispatcher)) {\n const namespace = readNamespaceCandidate(dispatcher.namespace);\n if (namespace) {\n return namespace;\n }\n }\n\n throw new Error(\n 'Cloudflare fragment requires a dispatch namespace name. Pass `dispatcher: \"my-namespace\"` or `dispatcher: { binding: env.DISPATCHER, namespace: \"my-namespace\" }`.',\n );\n};\n\nexport const buildCloudflareScriptTags = (\n dynamicTags: string | string[],\n staticTags: string[] = [],\n) => {\n const normalizedDynamicTags = Array.isArray(dynamicTags) ? dynamicTags : [dynamicTags];\n\n return unique(\n [...staticTags, ...normalizedDynamicTags]\n .map(sanitizeCloudflareTag)\n .filter((tag) => tag.length > 0),\n );\n};\n\nexport const createCloudflareApiClient = ({\n apiToken,\n fetchImplementation,\n maxRetries = 0,\n}: CloudflareApiClientConfig): CloudflareApiClient => {\n return new Cloudflare({\n apiToken,\n fetch: fetchImplementation,\n maxRetries,\n });\n};\n\nexport const listCloudflareScriptTags = async (\n client: CloudflareApiClient,\n input: {\n accountId: string;\n dispatchNamespace: string;\n scriptName: string;\n },\n) => {\n try {\n const tags = await client.workersForPlatforms.dispatch.namespaces.scripts.tags.list(\n input.dispatchNamespace,\n input.scriptName,\n {\n account_id: input.accountId,\n },\n );\n const results: string[] = [];\n\n for await (const tag of tags) {\n results.push(tag);\n }\n\n return results;\n } catch (error) {\n if (error instanceof NotFoundError) {\n return [];\n }\n\n throw error;\n }\n};\n\nexport const getCloudflareCurrentDeployment = async (\n client: CloudflareApiClient,\n input: {\n accountId: string;\n dispatchNamespace: string;\n scriptName: string;\n deploymentTagPrefix?: string;\n },\n): Promise<CloudflareCurrentDeployment> => {\n const remoteTags = await listCloudflareScriptTags(client, input);\n const deploymentTag = findCloudflareDeploymentTag(remoteTags, input.deploymentTagPrefix);\n\n if (deploymentTag === null) {\n return null;\n }\n\n return {\n deploymentTag,\n deploymentId: getCloudflareDeploymentIdFromTag(deploymentTag, input.deploymentTagPrefix),\n };\n};\n\nexport const getCloudflareScriptState = async (\n client: CloudflareApiClient,\n input: {\n accountId: string;\n dispatchNamespace: string;\n scriptName: string;\n },\n): Promise<CloudflareScriptState> => {\n try {\n const script = await client.workersForPlatforms.dispatch.namespaces.scripts.get(\n input.dispatchNamespace,\n input.scriptName,\n {\n account_id: input.accountId,\n },\n );\n\n return {\n etag: script.script?.etag ?? null,\n modifiedOn: script.modified_on ?? null,\n };\n } catch (error) {\n if (error instanceof NotFoundError) {\n return null;\n }\n\n throw error;\n }\n};\n\nexport const deployCloudflareWorker = async (\n client: CloudflareApiClient,\n input: DeployCloudflareWorkerInput,\n) => {\n const moduleFile = await toFile(new TextEncoder().encode(input.moduleContent), input.entrypoint, {\n type: \"application/javascript+module\",\n });\n const params: CloudflareScriptUpdateParams = {\n account_id: input.accountId,\n metadata: {\n main_module: input.entrypoint,\n compatibility_date: input.compatibilityDate,\n compatibility_flags:\n input.compatibilityFlags.length > 0 ? input.compatibilityFlags : undefined,\n tags: input.tags && input.tags.length > 0 ? input.tags : undefined,\n },\n files: [moduleFile],\n };\n\n return await client.workersForPlatforms.dispatch.namespaces.scripts.update(\n input.dispatchNamespace,\n input.scriptName,\n params,\n input.ifMatch\n ? {\n headers: {\n \"If-Match\": input.ifMatch,\n },\n }\n : undefined,\n );\n};\n\nexport const reconcileCloudflareWorkerDeployment = async (\n client: CloudflareApiClient,\n input: ReconcileCloudflareWorkerDeploymentInput,\n): Promise<CloudflareDeploymentReconciliationResult> => {\n const appTag = buildCloudflareAppTag(input.appId, input.deploymentTagPrefix);\n const deploymentTag = buildCloudflareDeploymentTag(input.deploymentId, input.deploymentTagPrefix);\n try {\n const response = await deployCloudflareWorker(client, {\n accountId: input.accountId,\n dispatchNamespace: input.dispatchNamespace,\n scriptName: input.scriptName,\n entrypoint: input.entrypoint,\n moduleContent: input.moduleContent,\n compatibilityDate: input.compatibilityDate,\n compatibilityFlags: input.compatibilityFlags,\n tags: buildCloudflareScriptTags([appTag, deploymentTag], input.scriptTags),\n ifMatch: input.expectedLiveEtag,\n });\n\n return {\n action: \"uploaded\",\n deploymentTag,\n response,\n };\n } catch (error) {\n const cloudflareError = getCloudflareApiError(error);\n if (cloudflareError?.status !== 412) {\n throw error;\n }\n\n const [currentDeployment, scriptState] = await Promise.all([\n getCloudflareCurrentDeployment(client, {\n accountId: input.accountId,\n dispatchNamespace: input.dispatchNamespace,\n scriptName: input.scriptName,\n deploymentTagPrefix: input.deploymentTagPrefix,\n }),\n getCloudflareScriptState(client, {\n accountId: input.accountId,\n dispatchNamespace: input.dispatchNamespace,\n scriptName: input.scriptName,\n }),\n ]);\n\n if (currentDeployment?.deploymentTag === deploymentTag) {\n return {\n action: \"already-deployed\",\n deploymentTag,\n currentDeploymentTag: currentDeployment.deploymentTag,\n currentDeploymentId: currentDeployment.deploymentId,\n currentEtag: scriptState?.etag ?? null,\n currentModifiedOn: scriptState?.modifiedOn ?? null,\n };\n }\n\n if (currentDeployment !== null) {\n return {\n action: \"superseded\",\n deploymentTag,\n currentDeploymentTag: currentDeployment.deploymentTag,\n currentDeploymentId: currentDeployment.deploymentId,\n currentEtag: scriptState?.etag ?? null,\n currentModifiedOn: scriptState?.modifiedOn ?? null,\n };\n }\n\n throw error;\n }\n};\n\nexport const getCloudflareApiError = (error: unknown) => {\n if (!(error instanceof Cloudflare.APIError)) {\n return null;\n }\n\n const [firstError] = error.errors;\n return {\n status: error.status,\n code:\n firstError?.code === undefined || firstError?.code === null\n ? error.name\n : String(firstError.code),\n message: firstError?.message ?? error.message,\n details: isRecord(error.error) ? error.error : undefined,\n };\n};\n","import { z } from \"zod\";\n\nexport const SUPPORTED_DEPLOYMENT_FORMAT = \"esmodule\";\nexport const DEFAULT_DEPLOYMENT_ENTRYPOINT = \"index.mjs\";\n\nexport const cloudflareCompatibilityDateSchema = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, \"compatibilityDate must use YYYY-MM-DD.\");\n\nexport const cloudflareDeploymentStatusSchema = z.enum([\n \"queued\",\n \"deploying\",\n \"succeeded\",\n \"failed\",\n]);\n\nexport const cloudflareDeployScriptSchema = z.object({\n type: z.enum([SUPPORTED_DEPLOYMENT_FORMAT]).default(SUPPORTED_DEPLOYMENT_FORMAT),\n entrypoint: z.string().trim().min(1).default(DEFAULT_DEPLOYMENT_ENTRYPOINT),\n content: z.string(),\n});\n\nexport const cloudflareDeployRequestSchema = z.object({\n script: cloudflareDeployScriptSchema,\n compatibilityDate: cloudflareCompatibilityDateSchema.optional(),\n compatibilityFlags: z.array(z.string().min(1)).optional(),\n});\n\nconst cloudflareTimestampSchema = z.string().datetime({ offset: true });\n\nexport const cloudflareProviderSummarySchema = z.object({\n etag: z.string().nullable(),\n modifiedOn: cloudflareTimestampSchema.nullable(),\n});\n\nexport const cloudflareDeploymentSummarySchema = z.object({\n id: z.string(),\n appId: z.string(),\n scriptName: z.string(),\n status: cloudflareDeploymentStatusSchema,\n format: z.literal(SUPPORTED_DEPLOYMENT_FORMAT),\n entrypoint: z.string(),\n sourceByteLength: z.number().int().nonnegative(),\n compatibilityDate: cloudflareCompatibilityDateSchema,\n compatibilityFlags: z.array(z.string()),\n attemptCount: z.number().int().nonnegative(),\n queuedAt: cloudflareTimestampSchema,\n startedAt: cloudflareTimestampSchema.nullable(),\n completedAt: cloudflareTimestampSchema.nullable(),\n errorCode: z.string().nullable(),\n errorMessage: z.string().nullable(),\n cloudflare: cloudflareProviderSummarySchema.nullable(),\n createdAt: cloudflareTimestampSchema,\n updatedAt: cloudflareTimestampSchema,\n});\n\nexport const cloudflareDeploymentDetailSchema = cloudflareDeploymentSummarySchema.extend({\n sourceCode: z.string(),\n});\n\nexport const cloudflareAppSummarySchema = z.object({\n id: z.string(),\n scriptName: z.string(),\n latestDeployment: cloudflareDeploymentSummarySchema.nullable(),\n createdAt: cloudflareTimestampSchema,\n updatedAt: cloudflareTimestampSchema,\n});\n\nexport const cloudflareAppStateSchema = cloudflareAppSummarySchema.extend({\n liveDeployment: cloudflareDeploymentSummarySchema.nullable(),\n liveDeploymentError: z.string().nullable(),\n deployments: z.array(cloudflareDeploymentSummarySchema),\n});\n\nexport const cloudflareAppListSchema = z.object({\n apps: z.array(cloudflareAppSummarySchema),\n});\n\nexport const cloudflareDeploymentListSchema = z.object({\n deployments: z.array(cloudflareDeploymentSummarySchema),\n});\n\nexport type CloudflareDeploymentStatus = z.infer<typeof cloudflareDeploymentStatusSchema>;\nexport type CloudflareDeployRequest = z.infer<typeof cloudflareDeployRequestSchema>;\nexport type CloudflareDeploymentSummary = z.infer<typeof cloudflareDeploymentSummarySchema>;\nexport type CloudflareDeploymentDetail = z.infer<typeof cloudflareDeploymentDetailSchema>;\nexport type CloudflareAppSummary = z.infer<typeof cloudflareAppSummarySchema>;\nexport type CloudflareAppState = z.infer<typeof cloudflareAppStateSchema>;\nexport type CloudflareAppList = z.infer<typeof cloudflareAppListSchema>;\nexport type CloudflareDeploymentList = z.infer<typeof cloudflareDeploymentListSchema>;\n","export interface CloudflareScriptNameConfig {\n scriptNamePrefix?: string;\n scriptNameSuffix?: string;\n scriptNameSeparator?: string;\n maxScriptNameLength?: number;\n}\n\nexport const DEFAULT_SCRIPT_NAME_SEPARATOR = \"-\";\nexport const DEFAULT_MAX_SCRIPT_NAME_LENGTH = 63;\n\nconst normalizeSeparator = (value?: string) => {\n const cleaned = (value ?? DEFAULT_SCRIPT_NAME_SEPARATOR).replace(/[^a-z0-9-]+/gi, \"-\");\n return cleaned.length > 0 ? cleaned : DEFAULT_SCRIPT_NAME_SEPARATOR;\n};\n\nconst sanitizeSegment = (value: string) => {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+/, \"\")\n .replace(/-+$/, \"\")\n .replace(/-{2,}/g, \"-\");\n};\n\nconst hashString = (value: string) => {\n let hash = 2166136261;\n\n for (const char of value) {\n hash ^= char.charCodeAt(0);\n hash = Math.imul(hash, 16777619);\n }\n\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n};\n\nexport const resolveCloudflareScriptName = (\n appId: string,\n config: CloudflareScriptNameConfig = {},\n) => {\n const separator = normalizeSeparator(config.scriptNameSeparator);\n const maxLength = Math.max(16, config.maxScriptNameLength ?? DEFAULT_MAX_SCRIPT_NAME_LENGTH);\n const segments = [config.scriptNamePrefix, appId, config.scriptNameSuffix]\n .map((segment) => sanitizeSegment(segment ?? \"\"))\n .filter(Boolean);\n const base = segments.join(separator) || \"app\";\n\n if (base.length <= maxLength) {\n return base;\n }\n\n const hash = hashString(base);\n const budget = Math.max(1, maxLength - hash.length - separator.length);\n const trimmedBase = base.slice(0, budget).replace(/-+$/, \"\") || \"app\";\n const candidate = `${trimmedBase}${separator}${hash}`;\n\n return candidate.slice(0, maxLength).replace(/-+$/, \"\");\n};\n","import type { ClientOptions as CloudflareClientOptions } from \"cloudflare\";\n\nimport { defineFragment } from \"@fragno-dev/core\";\nimport { ExponentialBackoffRetryPolicy, withDatabase, type HookFn } from \"@fragno-dev/db\";\n\nimport {\n createCloudflareApiClient,\n getCloudflareApiError,\n reconcileCloudflareWorkerDeployment,\n resolveCloudflareDispatchNamespaceName,\n type CloudflareApiClient,\n type CloudflareDispatcherConfig,\n type CloudflareScriptUpdateResponse,\n} from \"./cloudflare-api\";\nimport {\n SUPPORTED_DEPLOYMENT_FORMAT,\n type CloudflareAppSummary,\n type CloudflareDeployRequest,\n type CloudflareDeploymentDetail,\n type CloudflareDeploymentSummary,\n} from \"./contracts\";\nimport { cloudflareSchema } from \"./schema\";\nimport { resolveCloudflareScriptName, type CloudflareScriptNameConfig } from \"./script-name\";\n\ntype DeploymentRow = {\n id: { valueOf(): string };\n status: string;\n format: string;\n entrypoint: string;\n scriptName: string;\n sourceByteLength: number;\n compatibilityDate: string;\n compatibilityFlags: unknown;\n attemptCount: number;\n startedAt: Date | null;\n completedAt: Date | null;\n errorCode: string | null;\n errorMessage: string | null;\n cloudflareEtag: string | null;\n cloudflareModifiedOn: string | null;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype AppRow = {\n id: { valueOf(): string };\n scriptName: string;\n liveDeploymentId: string | null;\n liveCloudflareEtag: string | null;\n firstDeploymentLeaseId: string | null;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype CloudflareLiveDeploymentSnapshot = {\n currentDeploymentTag: string;\n currentDeploymentId: string | null;\n currentEtag: string | null;\n currentModifiedOn: string | null;\n};\n\ntype DeployWorkerRemoteResult =\n | Awaited<ReturnType<typeof reconcileCloudflareWorkerDeployment>>\n | ({ action: \"superseded\" } & CloudflareLiveDeploymentSnapshot);\n\ntype FirstDeploymentPreparation =\n | { action: \"missing\" }\n | { action: \"retry\" }\n | { action: \"continue\" }\n | ({ action: \"superseded\" } & CloudflareLiveDeploymentSnapshot);\n\ntype LivePointerGuard =\n | {\n kind: \"etag\";\n expectedLiveEtag: string;\n }\n | {\n kind: \"first-deploy\";\n leaseDeploymentId: string;\n };\n\nconst textEncoder = new TextEncoder();\nconst hookWriteRetryPolicy = new ExponentialBackoffRetryPolicy({\n maxRetries: 5,\n initialDelayMs: 10,\n maxDelayMs: 250,\n});\n\ntype CloudflareFragmentSharedConfig = CloudflareScriptNameConfig & {\n accountId: string;\n compatibilityDate: string;\n compatibilityFlags?: string[];\n scriptTags?: string[];\n deploymentTagPrefix?: string;\n};\n\ntype CloudflareFragmentApiTokenConfig = {\n apiToken: string;\n cloudflare?: never;\n fetchImplementation?: CloudflareClientOptions[\"fetch\"];\n};\n\ntype CloudflareFragmentClientConfig = {\n cloudflare: CloudflareApiClient;\n apiToken?: never;\n fetchImplementation?: never;\n};\n\nexport type CloudflareFragmentConfig = CloudflareFragmentSharedConfig &\n (CloudflareFragmentApiTokenConfig | CloudflareFragmentClientConfig) &\n (\n | {\n dispatcher: CloudflareDispatcherConfig;\n dispatchNamespace?: never;\n }\n | {\n dispatchNamespace: string;\n dispatcher?: never;\n }\n );\n\nexport type DeployWorkerHookInput = {\n deploymentId: string;\n appId: string;\n expectedLiveEtag: string | null;\n scriptName: string;\n entrypoint: string;\n moduleContent: string;\n compatibilityDate: string;\n compatibilityFlags: string[];\n};\n\nexport type CloudflareHooksMap = {\n deployWorker: HookFn<DeployWorkerHookInput>;\n};\n\nconst resolveDispatcherConfig = (config: CloudflareFragmentConfig): CloudflareDispatcherConfig => {\n if (\"dispatcher\" in config && config.dispatcher !== undefined) {\n return config.dispatcher;\n }\n\n if (\"dispatchNamespace\" in config && config.dispatchNamespace !== undefined) {\n return config.dispatchNamespace;\n }\n\n throw new Error(\n \"Cloudflare fragment requires `dispatcher` or `dispatchNamespace` to resolve the dispatch namespace name.\",\n );\n};\n\nconst normalizeStringList = (value: unknown) => {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0);\n};\n\nconst toIsoDateTime = (value: Date | null) => {\n return value ? value.toISOString() : null;\n};\n\nconst buildDeploymentSummary = (\n deployment: DeploymentRow,\n appId: string,\n): CloudflareDeploymentSummary => {\n const cloudflare =\n deployment.cloudflareEtag || deployment.cloudflareModifiedOn\n ? {\n etag: deployment.cloudflareEtag,\n modifiedOn: deployment.cloudflareModifiedOn,\n }\n : null;\n\n return {\n id: deployment.id.valueOf(),\n appId,\n scriptName: deployment.scriptName,\n status:\n deployment.status === \"queued\" ||\n deployment.status === \"deploying\" ||\n deployment.status === \"succeeded\" ||\n deployment.status === \"failed\"\n ? deployment.status\n : \"failed\",\n format:\n deployment.format === SUPPORTED_DEPLOYMENT_FORMAT ? SUPPORTED_DEPLOYMENT_FORMAT : \"esmodule\",\n entrypoint: deployment.entrypoint,\n sourceByteLength: deployment.sourceByteLength,\n compatibilityDate: deployment.compatibilityDate,\n compatibilityFlags: normalizeStringList(deployment.compatibilityFlags),\n attemptCount: deployment.attemptCount,\n queuedAt: deployment.createdAt.toISOString(),\n startedAt: toIsoDateTime(deployment.startedAt),\n completedAt: toIsoDateTime(deployment.completedAt),\n errorCode: deployment.errorCode,\n errorMessage: deployment.errorMessage,\n cloudflare,\n createdAt: deployment.createdAt.toISOString(),\n updatedAt: deployment.updatedAt.toISOString(),\n };\n};\n\nconst buildDeploymentDetail = (\n deployment: DeploymentRow & { sourceCode?: string },\n appId: string,\n): CloudflareDeploymentDetail => {\n return {\n ...buildDeploymentSummary(deployment, appId),\n sourceCode: deployment.sourceCode ?? \"\",\n };\n};\n\nconst buildAppSummary = (\n app: AppRow,\n latestDeployment: DeploymentRow | null,\n): CloudflareAppSummary => {\n return {\n id: app.id.valueOf(),\n scriptName: app.scriptName,\n latestDeployment: latestDeployment\n ? buildDeploymentSummary(latestDeployment, app.id.valueOf())\n : null,\n createdAt: app.createdAt.toISOString(),\n updatedAt: app.updatedAt.toISOString(),\n };\n};\n\nconst formatDeployError = (error: unknown) => {\n const cloudflareError = getCloudflareApiError(error);\n if (cloudflareError) {\n return {\n code: cloudflareError.code,\n message: cloudflareError.message,\n };\n }\n\n if (error instanceof Error) {\n return {\n code: error.name || \"Error\",\n message: error.message,\n };\n }\n\n return {\n code: \"unknown\",\n message: String(error),\n };\n};\n\nconst readCloudflareSummary = (response: CloudflareScriptUpdateResponse) => {\n return {\n etag: response.etag ?? null,\n modifiedOn: response.modified_on ?? null,\n raw: response,\n };\n};\n\nconst createLivePointerGuard = (input: DeployWorkerHookInput): LivePointerGuard => {\n if (input.expectedLiveEtag !== null) {\n return {\n kind: \"etag\",\n expectedLiveEtag: input.expectedLiveEtag,\n };\n }\n\n return {\n kind: \"first-deploy\",\n leaseDeploymentId: input.deploymentId,\n };\n};\n\nconst canPromoteDeploymentToLive = (\n app: AppRow,\n deploymentId: string,\n livePointerGuard: LivePointerGuard,\n) => {\n if (livePointerGuard.kind === \"first-deploy\") {\n return (\n app.liveCloudflareEtag === null &&\n app.firstDeploymentLeaseId === livePointerGuard.leaseDeploymentId\n );\n }\n\n return (\n app.liveCloudflareEtag === livePointerGuard.expectedLiveEtag ||\n app.liveDeploymentId === deploymentId\n );\n};\n\nexport const cloudflareFragmentDefinition = defineFragment<CloudflareFragmentConfig>(\n \"cloudflare-fragment\",\n)\n .extend(withDatabase(cloudflareSchema))\n .withDependencies(({ config }) => {\n const dispatchNamespace = resolveCloudflareDispatchNamespaceName(\n resolveDispatcherConfig(config),\n );\n const cloudflare =\n \"cloudflare\" in config && config.cloudflare\n ? config.cloudflare\n : createCloudflareApiClient({\n apiToken: config.apiToken,\n fetchImplementation: config.fetchImplementation,\n });\n\n return {\n cloudflare,\n dispatchNamespace,\n };\n })\n .providesService(\"cloudflare\", ({ deps }) => ({\n getClient: () => deps.cloudflare,\n }))\n .provideHooks<CloudflareHooksMap>(({ defineHook, deps, config }) => ({\n deployWorker: defineHook(async function (input) {\n // Cloudflare CAS starts once the app has a live etag. The first deploy uses a local\n // lease so we still get compare-and-swap semantics before that point.\n const livePointerGuard = createLivePointerGuard(input);\n let remoteResult: DeployWorkerRemoteResult | null = null;\n let remoteError: unknown = null;\n let remoteUploadAttempted = false;\n\n const prepareFirstDeployment = async (): Promise<FirstDeploymentPreparation | null> => {\n if (livePointerGuard.kind !== \"first-deploy\") {\n return null;\n }\n\n return await this.handlerTx({ retryPolicy: hookWriteRetryPolicy })\n .retrieve(({ forSchema }) =>\n forSchema(cloudflareSchema).findFirst(\"deployment\", (b) =>\n b\n .whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", input.deploymentId))\n .join((j) => j.app()),\n ),\n )\n .mutate(({ forSchema, retrieveResult: [deployment] }) => {\n if (!deployment?.app) {\n return { action: \"missing\" as const };\n }\n\n const uow = forSchema(cloudflareSchema);\n const now = uow.now();\n const deploymentId = deployment.id.valueOf();\n const app = deployment.app;\n\n if (app.liveCloudflareEtag !== null) {\n if (app.firstDeploymentLeaseId === deploymentId) {\n uow.update(\"app\", app.id, (b) =>\n b\n .set({\n updatedAt: now,\n firstDeploymentLeaseId: null,\n })\n .check(),\n );\n }\n\n return {\n action: \"superseded\" as const,\n currentDeploymentId: app.liveDeploymentId,\n currentDeploymentTag: app.liveDeploymentId ?? \"current-live-deployment\",\n currentEtag: app.liveCloudflareEtag,\n currentModifiedOn: null,\n };\n }\n\n if (\n app.firstDeploymentLeaseId !== null &&\n app.firstDeploymentLeaseId !== deploymentId\n ) {\n return { action: \"retry\" as const };\n }\n\n if (app.firstDeploymentLeaseId !== deploymentId) {\n uow.update(\"app\", app.id, (b) =>\n b\n .set({\n updatedAt: now,\n firstDeploymentLeaseId: deploymentId,\n })\n .check(),\n );\n }\n\n return { action: \"continue\" as const };\n })\n .execute();\n };\n\n const firstDeploymentPreparation = await prepareFirstDeployment();\n if (firstDeploymentPreparation?.action === \"missing\") {\n return;\n }\n\n if (firstDeploymentPreparation?.action === \"retry\") {\n throw new Error(\n `Initial Cloudflare deploy for '${input.scriptName}' is already in progress.`,\n );\n }\n\n if (firstDeploymentPreparation?.action === \"superseded\") {\n remoteResult = firstDeploymentPreparation;\n }\n\n if (!remoteResult) {\n remoteUploadAttempted = true;\n\n try {\n remoteResult = await reconcileCloudflareWorkerDeployment(deps.cloudflare, {\n accountId: config.accountId,\n dispatchNamespace: deps.dispatchNamespace,\n appId: input.appId,\n deploymentId: input.deploymentId,\n expectedLiveEtag: input.expectedLiveEtag,\n deploymentTagPrefix: config.deploymentTagPrefix,\n scriptName: input.scriptName,\n entrypoint: input.entrypoint,\n moduleContent: input.moduleContent,\n compatibilityDate: input.compatibilityDate,\n compatibilityFlags: input.compatibilityFlags,\n scriptTags: config.scriptTags,\n });\n } catch (error) {\n remoteError = error;\n }\n }\n\n const remoteDeploymentId =\n remoteResult?.action === \"superseded\" || remoteResult?.action === \"already-deployed\"\n ? remoteResult.currentDeploymentId\n : null;\n const finalizeDeploymentStateTx =\n remoteDeploymentId && remoteDeploymentId !== input.deploymentId\n ? this.handlerTx({ retryPolicy: hookWriteRetryPolicy })\n .retrieve(({ forSchema }) =>\n forSchema(cloudflareSchema)\n .findFirst(\"deployment\", (b) =>\n b\n .whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", input.deploymentId))\n .join((j) => j.app()),\n )\n .findFirst(\"deployment\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", remoteDeploymentId)),\n ),\n )\n .transformRetrieve(([deployment, remoteDeployment]) => ({\n deployment,\n remoteDeployment: remoteDeployment ?? null,\n }))\n : this.handlerTx({ retryPolicy: hookWriteRetryPolicy })\n .retrieve(({ forSchema }) =>\n forSchema(cloudflareSchema).findFirst(\"deployment\", (b) =>\n b\n .whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", input.deploymentId))\n .join((j) => j.app()),\n ),\n )\n .transformRetrieve(([deployment]) => ({\n deployment,\n remoteDeployment: null,\n }));\n\n await finalizeDeploymentStateTx\n .mutate(({ forSchema, retrieveResult: { deployment, remoteDeployment } }) => {\n if (!deployment || !deployment.app) {\n return;\n }\n\n const uow = forSchema(cloudflareSchema);\n const now = uow.now();\n const appId = deployment.app.id;\n const deploymentId = deployment.id.valueOf();\n const ownsFirstDeploymentLease = deployment.app.firstDeploymentLeaseId === deploymentId;\n const updateApp = (\n changes: Partial<{\n liveDeploymentId: string | null;\n liveCloudflareEtag: string | null;\n }> = {},\n ) => {\n uow.update(\"app\", appId, (b) =>\n b\n .set({\n updatedAt: now,\n ...changes,\n ...(ownsFirstDeploymentLease ? { firstDeploymentLeaseId: null } : {}),\n })\n .check(),\n );\n };\n\n if (remoteResult?.action === \"already-deployed\") {\n const etag =\n remoteResult.currentEtag ??\n deployment.cloudflareEtag ??\n (deployment.app.liveDeploymentId === deploymentId\n ? deployment.app.liveCloudflareEtag\n : null);\n const modifiedOn = remoteResult.currentModifiedOn ?? deployment.cloudflareModifiedOn;\n\n uow.update(\"deployment\", deployment.id, (b) =>\n b\n .set({\n status: \"succeeded\",\n updatedAt: now,\n startedAt: deployment.startedAt ?? now,\n completedAt: deployment.completedAt ?? now,\n attemptCount: Math.max(deployment.attemptCount, 1),\n errorCode: null,\n errorMessage: null,\n cloudflareEtag: etag,\n cloudflareModifiedOn: modifiedOn,\n })\n .check(),\n );\n updateApp({\n liveDeploymentId: deploymentId,\n liveCloudflareEtag: etag,\n });\n return;\n }\n\n if (remoteResult?.action === \"uploaded\") {\n const cloudflare = readCloudflareSummary(remoteResult.response);\n const canMoveLivePointer = canPromoteDeploymentToLive(\n deployment.app,\n deploymentId,\n livePointerGuard,\n );\n\n uow.update(\"deployment\", deployment.id, (b) =>\n b\n .set({\n status: \"succeeded\",\n updatedAt: now,\n startedAt: deployment.startedAt ?? now,\n completedAt: now,\n attemptCount: deployment.attemptCount + 1,\n errorCode: null,\n errorMessage: null,\n cloudflareEtag: cloudflare.etag,\n cloudflareModifiedOn: cloudflare.modifiedOn,\n cloudflareResponse: cloudflare.raw,\n })\n .check(),\n );\n updateApp(\n canMoveLivePointer\n ? {\n liveDeploymentId: deploymentId,\n liveCloudflareEtag: cloudflare.etag,\n }\n : {},\n );\n return;\n }\n\n if (remoteResult?.action === \"superseded\") {\n const supersededBy =\n remoteDeployment?.id.valueOf() ??\n remoteResult.currentDeploymentId ??\n remoteResult.currentDeploymentTag;\n const winnerEtag =\n remoteResult.currentEtag ??\n remoteDeployment?.cloudflareEtag ??\n (deployment.app.liveDeploymentId === remoteResult.currentDeploymentId\n ? deployment.app.liveCloudflareEtag\n : null);\n const winnerModifiedOn =\n remoteResult.currentModifiedOn ?? remoteDeployment?.cloudflareModifiedOn ?? null;\n\n if (remoteDeployment) {\n uow.update(\"deployment\", remoteDeployment.id, (b) =>\n b\n .set({\n status: \"succeeded\",\n updatedAt: now,\n startedAt: remoteDeployment.startedAt ?? now,\n completedAt: remoteDeployment.completedAt ?? now,\n attemptCount: Math.max(remoteDeployment.attemptCount, 1),\n errorCode: null,\n errorMessage: null,\n cloudflareEtag: winnerEtag,\n cloudflareModifiedOn: winnerModifiedOn,\n })\n .check(),\n );\n }\n\n updateApp({\n liveDeploymentId: remoteResult.currentDeploymentId,\n liveCloudflareEtag: winnerEtag,\n });\n\n if (deployment.status === \"succeeded\") {\n return;\n }\n\n uow.update(\"deployment\", deployment.id, (b) =>\n b\n .set({\n status: \"failed\",\n updatedAt: now,\n startedAt: deployment.startedAt ?? now,\n completedAt: now,\n attemptCount: deployment.attemptCount + (remoteUploadAttempted ? 1 : 0),\n errorCode: \"DEPLOYMENT_SUPERSEDED\",\n errorMessage: `Deployment was superseded by '${supersededBy}'.`,\n })\n .check(),\n );\n return;\n }\n\n if (deployment.status === \"succeeded\") {\n updateApp();\n return;\n }\n\n const formatted = formatDeployError(remoteError);\n\n uow.update(\"deployment\", deployment.id, (b) =>\n b\n .set({\n status: \"failed\",\n updatedAt: now,\n startedAt: deployment.startedAt ?? now,\n completedAt: now,\n attemptCount: deployment.attemptCount + (remoteUploadAttempted ? 1 : 0),\n errorCode: formatted.code,\n errorMessage: formatted.message,\n })\n .check(),\n );\n updateApp();\n })\n .execute();\n }),\n }))\n .providesBaseService(({ defineService, config }) => {\n return defineService({\n upsertApp: function (appId: string) {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow.findFirst(\"app\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", appId))),\n )\n .mutate(({ uow, retrieveResult: [existingApp] }) => {\n if (existingApp) {\n return buildAppSummary(existingApp, null);\n }\n\n const createdAt = new Date();\n const scriptName = resolveCloudflareScriptName(appId, config);\n const createdId = uow.create(\"app\", {\n id: appId,\n scriptName,\n liveDeploymentId: null,\n liveCloudflareEtag: null,\n firstDeploymentLeaseId: null,\n createdAt,\n updatedAt: createdAt,\n });\n\n return {\n id: createdId.valueOf(),\n scriptName,\n latestDeployment: null,\n createdAt: createdAt.toISOString(),\n updatedAt: createdAt.toISOString(),\n };\n })\n .build();\n },\n queueDeployment: function (appId: string, request: CloudflareDeployRequest) {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow.findFirst(\"app\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", appId))),\n )\n .mutate(({ uow, retrieveResult: [existingApp] }) => {\n const now = new Date();\n const compatibilityDate = request.compatibilityDate ?? config.compatibilityDate;\n const compatibilityFlags = normalizeStringList(\n request.compatibilityFlags ?? config.compatibilityFlags,\n );\n const scriptName =\n existingApp?.scriptName ?? resolveCloudflareScriptName(appId, config);\n const sourceByteLength = textEncoder.encode(request.script.content).byteLength;\n const ensuredAppId =\n existingApp?.id ??\n uow.create(\"app\", {\n id: appId,\n scriptName,\n liveDeploymentId: null,\n liveCloudflareEtag: null,\n firstDeploymentLeaseId: null,\n createdAt: now,\n updatedAt: now,\n });\n\n if (existingApp) {\n uow.update(\"app\", existingApp.id, (b) => b.set({ updatedAt: now }).check());\n }\n\n const deploymentId = uow.create(\"deployment\", {\n appId: ensuredAppId,\n status: \"queued\",\n format: SUPPORTED_DEPLOYMENT_FORMAT,\n entrypoint: request.script.entrypoint,\n scriptName,\n sourceCode: request.script.content,\n sourceByteLength,\n compatibilityDate,\n compatibilityFlags,\n attemptCount: 0,\n startedAt: null,\n completedAt: null,\n errorCode: null,\n errorMessage: null,\n cloudflareEtag: null,\n cloudflareModifiedOn: null,\n cloudflareResponse: null,\n createdAt: now,\n updatedAt: now,\n });\n const deploymentIdValue = deploymentId.valueOf();\n const expectedLiveEtag = existingApp?.liveCloudflareEtag ?? null;\n\n // The hook payload carries the immutable deploy snapshot plus the live etag it was\n // queued against so Cloudflare can enforce compare-and-swap updates for us.\n uow.triggerHook(\"deployWorker\", {\n deploymentId: deploymentIdValue,\n appId: ensuredAppId.valueOf(),\n expectedLiveEtag,\n scriptName,\n entrypoint: request.script.entrypoint,\n moduleContent: request.script.content,\n compatibilityDate,\n compatibilityFlags,\n });\n\n return {\n id: deploymentIdValue,\n appId: ensuredAppId.valueOf(),\n scriptName,\n status: \"queued\" as const,\n format: SUPPORTED_DEPLOYMENT_FORMAT as \"esmodule\",\n entrypoint: request.script.entrypoint,\n sourceByteLength,\n compatibilityDate,\n compatibilityFlags,\n attemptCount: 0,\n queuedAt: now.toISOString(),\n startedAt: null,\n completedAt: null,\n errorCode: null,\n errorMessage: null,\n cloudflare: null,\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n };\n })\n .build();\n },\n getDeployment: function (deploymentId: string) {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow.findFirst(\"deployment\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", deploymentId)).join((j) => j.app()),\n ),\n )\n .transformRetrieve(([deployment]) => {\n return deployment?.app\n ? buildDeploymentDetail(deployment, deployment.app.id.valueOf())\n : null;\n })\n .build();\n },\n getAppState: function (appId: string) {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow\n .findFirst(\"app\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", appId)))\n .findFirst(\"deployment\", (b) =>\n b\n .whereIndex(\"idx_deployment_app_createdAt\", (eb) => eb(\"appId\", \"=\", appId))\n .orderByIndex(\"idx_deployment_app_createdAt\", \"desc\"),\n ),\n )\n .transformRetrieve(([app, latestDeployment]) => {\n return app\n ? {\n ...buildAppSummary(app, latestDeployment),\n liveDeploymentId: app.liveDeploymentId,\n liveCloudflareEtag: app.liveCloudflareEtag,\n }\n : null;\n })\n .build();\n },\n listApps: function () {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow\n .find(\"app\", (b) => b.whereIndex(\"primary\"))\n .find(\"deployment\", (b) => b.whereIndex(\"primary\").join((j) => j.app())),\n )\n .transformRetrieve(([apps, deployments]) => {\n const latestDeploymentsByAppId = new Map<string, (typeof deployments)[number]>();\n\n for (const deployment of deployments) {\n if (!deployment.app) {\n continue;\n }\n\n const deploymentAppId = deployment.app.id.valueOf();\n const existingDeployment = latestDeploymentsByAppId.get(deploymentAppId);\n\n if (\n !existingDeployment ||\n deployment.createdAt.getTime() > existingDeployment.createdAt.getTime()\n ) {\n latestDeploymentsByAppId.set(deploymentAppId, deployment);\n }\n }\n\n return apps\n .map((app) =>\n buildAppSummary(app, latestDeploymentsByAppId.get(app.id.valueOf()) ?? null),\n )\n .sort((left, right) => {\n const updatedAtCompare = right.updatedAt.localeCompare(left.updatedAt);\n if (updatedAtCompare !== 0) {\n return updatedAtCompare;\n }\n\n return left.id.localeCompare(right.id);\n });\n })\n .build();\n },\n listAppDeployments: function (appId: string) {\n return this.serviceTx(cloudflareSchema)\n .retrieve((uow) =>\n uow\n .findFirst(\"app\", (b) => b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", appId)))\n .find(\"deployment\", (b) =>\n b\n .whereIndex(\"idx_deployment_app_createdAt\", (eb) => eb(\"appId\", \"=\", appId))\n .orderByIndex(\"idx_deployment_app_createdAt\", \"desc\"),\n ),\n )\n .transformRetrieve(([app, deployments]) => {\n if (!app) {\n return null;\n }\n\n return deployments.map((deployment) =>\n buildDeploymentSummary(deployment, app.id.valueOf()),\n );\n })\n .build();\n },\n });\n })\n .build();\n","import { defineRoutes } from \"@fragno-dev/core\";\nimport { ExponentialBackoffRetryPolicy } from \"@fragno-dev/db\";\n\nimport {\n SUPPORTED_DEPLOYMENT_FORMAT,\n cloudflareAppListSchema,\n cloudflareAppStateSchema,\n cloudflareDeployRequestSchema,\n cloudflareDeploymentDetailSchema,\n cloudflareDeploymentListSchema,\n cloudflareDeploymentSummarySchema,\n} from \"./contracts\";\nimport { cloudflareFragmentDefinition } from \"./definition\";\n\nconst writeRetryPolicy = new ExponentialBackoffRetryPolicy({\n maxRetries: 5,\n initialDelayMs: 10,\n maxDelayMs: 250,\n});\n\nexport const cloudflareRoutesFactory = defineRoutes(cloudflareFragmentDefinition).create(\n ({ services, defineRoute }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/apps\",\n outputSchema: cloudflareAppListSchema,\n handler: async function (_input, { json }) {\n const [apps] = await this.handlerTx()\n .withServiceCalls(() => [services.listApps()])\n .execute();\n\n return json({ apps });\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/apps/:appId/deployments\",\n inputSchema: cloudflareDeployRequestSchema,\n outputSchema: cloudflareDeploymentSummarySchema,\n errorCodes: [\"INVALID_DEPLOY_INPUT\", \"UNSUPPORTED_DEPLOY_REQUEST\"],\n handler: async function ({ input, pathParams }, { json, error }) {\n const payload = await input.valid();\n\n if (payload.script.type !== SUPPORTED_DEPLOYMENT_FORMAT) {\n return error(\n {\n message:\n \"Only single-module ES module deployments are supported in the first slice.\",\n code: \"UNSUPPORTED_DEPLOY_REQUEST\",\n },\n 400,\n );\n }\n\n if (payload.script.entrypoint.trim().length === 0) {\n return error(\n {\n message: \"Deployment entrypoint cannot be empty.\",\n code: \"INVALID_DEPLOY_INPUT\",\n },\n 400,\n );\n }\n\n if (payload.script.content.trim().length === 0) {\n return error(\n {\n message: \"Deployment source cannot be empty.\",\n code: \"INVALID_DEPLOY_INPUT\",\n },\n 400,\n );\n }\n\n const [deployment] = await this.handlerTx({ retryPolicy: writeRetryPolicy })\n .withServiceCalls(() => [services.queueDeployment(pathParams.appId, payload)])\n .execute();\n\n return json(deployment);\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/apps/:appId/deployments\",\n outputSchema: cloudflareDeploymentListSchema,\n errorCodes: [\"APP_NOT_FOUND\"],\n handler: async function ({ pathParams }, { json, error }) {\n const [deployments] = await this.handlerTx()\n .withServiceCalls(() => [services.listAppDeployments(pathParams.appId)])\n .execute();\n\n if (!deployments) {\n return error(\n {\n message: `App '${pathParams.appId}' was not found.`,\n code: \"APP_NOT_FOUND\",\n },\n 404,\n );\n }\n\n return json({ deployments });\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/deployments/:deploymentId\",\n outputSchema: cloudflareDeploymentDetailSchema,\n errorCodes: [\"DEPLOYMENT_NOT_FOUND\"],\n handler: async function ({ pathParams }, { json, error }) {\n const [deployment] = await this.handlerTx()\n .withServiceCalls(() => [services.getDeployment(pathParams.deploymentId)])\n .execute();\n\n if (!deployment) {\n return error(\n {\n message: `Deployment '${pathParams.deploymentId}' was not found.`,\n code: \"DEPLOYMENT_NOT_FOUND\",\n },\n 404,\n );\n }\n\n return json(deployment);\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/apps/:appId\",\n outputSchema: cloudflareAppStateSchema,\n errorCodes: [\"APP_NOT_FOUND\"],\n handler: async function ({ pathParams }, { json, error }) {\n const [app, deployments] = await this.handlerTx()\n .withServiceCalls(\n () =>\n [\n services.getAppState(pathParams.appId),\n services.listAppDeployments(pathParams.appId),\n ] as const,\n )\n .execute();\n\n if (!app || !deployments) {\n return error(\n {\n message: `App '${pathParams.appId}' was not found.`,\n code: \"APP_NOT_FOUND\",\n },\n 404,\n );\n }\n\n const liveDeployment = app.liveDeploymentId\n ? (deployments.find((deployment) => deployment.id === app.liveDeploymentId) ?? null)\n : null;\n\n return json({\n ...app,\n liveDeployment,\n liveDeploymentError: null,\n deployments,\n });\n },\n }),\n ];\n },\n);\n","import { column, idColumn, referenceColumn, schema } from \"@fragno-dev/db/schema\";\n\nexport const cloudflareSchema = schema(\"cloudflare-fragment\", (s) => {\n return s\n .addTable(\"app\", (t) => {\n return t\n .addColumn(\"id\", idColumn())\n .addColumn(\"scriptName\", column(\"string\"))\n .addColumn(\"liveDeploymentId\", column(\"string\").nullable())\n .addColumn(\"liveCloudflareEtag\", column(\"string\").nullable())\n .addColumn(\"firstDeploymentLeaseId\", column(\"string\").nullable())\n .addColumn(\n \"createdAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .addColumn(\n \"updatedAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .createIndex(\"idx_app_scriptName\", [\"scriptName\"], { unique: true });\n })\n .addTable(\"deployment\", (t) => {\n return t\n .addColumn(\"id\", idColumn())\n .addColumn(\"appId\", referenceColumn())\n .addColumn(\"status\", column(\"string\"))\n .addColumn(\"format\", column(\"string\"))\n .addColumn(\"entrypoint\", column(\"string\"))\n .addColumn(\"scriptName\", column(\"string\"))\n .addColumn(\"sourceCode\", column(\"string\"))\n .addColumn(\"sourceByteLength\", column(\"integer\"))\n .addColumn(\"compatibilityDate\", column(\"string\"))\n .addColumn(\"compatibilityFlags\", column(\"json\"))\n .addColumn(\"attemptCount\", column(\"integer\").defaultTo(0))\n .addColumn(\"startedAt\", column(\"timestamp\").nullable())\n .addColumn(\"completedAt\", column(\"timestamp\").nullable())\n .addColumn(\"errorCode\", column(\"string\").nullable())\n .addColumn(\"errorMessage\", column(\"string\").nullable())\n .addColumn(\"cloudflareEtag\", column(\"string\").nullable())\n .addColumn(\"cloudflareModifiedOn\", column(\"string\").nullable())\n .addColumn(\"cloudflareResponse\", column(\"json\").nullable())\n .addColumn(\n \"createdAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .addColumn(\n \"updatedAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .createIndex(\"idx_deployment_app_createdAt\", [\"appId\", \"createdAt\"])\n .createIndex(\"idx_deployment_status_createdAt\", [\"status\", \"createdAt\"]);\n })\n .addReference(\"app\", {\n type: \"one\",\n from: { table: \"deployment\", column: \"appId\" },\n to: { table: \"app\", column: \"id\" },\n });\n});\n"],"x_google_ignoreList":[9,10,11,12,13,14,19,20],"mappings":";;;;;;;;;;AAKA,SAASA,sBAAsBC,SAASC,mBAAmB;CAC1D,MAAMC,SAAS,EAAE;AACjB,MAAK,MAAMC,QAAQF,kBAA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