ignotum 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +6 -6
  2. package/dist/cli/bin.mjs +6111 -4448
  3. package/dist/cli/bin.mjs.map +1 -1
  4. package/dist/cli/emscripten-module-D5GzfUNv.mjs +533 -0
  5. package/dist/cli/emscripten-module-D5GzfUNv.mjs.map +1 -0
  6. package/dist/cli/ffi-7IElU4Co.mjs +148 -0
  7. package/dist/cli/ffi-7IElU4Co.mjs.map +1 -0
  8. package/dist/cli/managed-release-WHYLZwaS.mjs +10902 -0
  9. package/dist/cli/managed-release-WHYLZwaS.mjs.map +1 -0
  10. package/dist/cli/managed-release.d.mts +1 -0
  11. package/dist/cli/managed-release.mjs +14 -0
  12. package/dist/cli/managed-release.mjs.map +1 -0
  13. package/dist/cli/module-ES6BEMUI-D36I4NVn.mjs +1289 -0
  14. package/dist/cli/module-ES6BEMUI-D36I4NVn.mjs.map +1 -0
  15. package/dist/runtime/{api-Cv3hMbzo.d.ts → api-B4fwp5a2.d.ts} +4 -4
  16. package/dist/runtime/bootstrap-BISQSn_O.js +916 -0
  17. package/dist/runtime/bootstrap-BISQSn_O.js.map +1 -0
  18. package/dist/runtime/bootstrap-BTFScKAc.d.ts +545 -0
  19. package/dist/runtime/client.d.ts +50 -15
  20. package/dist/runtime/client.js +7 -1138
  21. package/dist/runtime/client.js.map +1 -1
  22. package/dist/runtime/descriptor-CTY4mtwS-cS43EbwS.js +269 -0
  23. package/dist/runtime/descriptor-CTY4mtwS-cS43EbwS.js.map +1 -0
  24. package/dist/runtime/{id-Bt9XWRGL.js → id--1m0NuUL.js} +4 -4
  25. package/dist/runtime/id--1m0NuUL.js.map +1 -0
  26. package/dist/runtime/{id-BzFHf3Wo-DGPCjgrf.d.ts → id-7an3nxTu-DZJSM5xh.d.ts} +2 -2
  27. package/dist/runtime/id-CBOt2kDo.d.ts +1 -0
  28. package/dist/runtime/identity-QjtJRxBD.d.ts +2 -0
  29. package/dist/runtime/image-Djtjy4Z8.js +19 -0
  30. package/dist/runtime/image-Djtjy4Z8.js.map +1 -0
  31. package/dist/runtime/index-D4seNHlX.d.ts +184 -0
  32. package/dist/runtime/internal/api.d.ts +1 -1
  33. package/dist/runtime/internal/api.js +30 -1
  34. package/dist/runtime/internal/api.js.map +1 -0
  35. package/dist/runtime/internal/bootstrap.d.ts +2 -0
  36. package/dist/runtime/internal/bootstrap.js +2 -0
  37. package/dist/runtime/internal/client.d.ts +2 -0
  38. package/dist/runtime/internal/client.js +75 -0
  39. package/dist/runtime/internal/client.js.map +1 -0
  40. package/dist/runtime/internal/host.d.ts +25 -8
  41. package/dist/runtime/internal/host.js +27 -6
  42. package/dist/runtime/internal/host.js.map +1 -1
  43. package/dist/runtime/internal/routes.d.ts +2 -0
  44. package/dist/runtime/internal/routes.js +2 -0
  45. package/dist/runtime/internal/server.d.ts +1 -1
  46. package/dist/runtime/internal/server.js +1 -1
  47. package/dist/runtime/internal/types.d.ts +2 -1
  48. package/dist/runtime/internal/types.js +1 -1
  49. package/dist/runtime/pagination-CBOt2kDo.d.ts +1 -0
  50. package/dist/runtime/pagination-D3qd6s9N.js +33 -0
  51. package/dist/runtime/pagination-D3qd6s9N.js.map +1 -0
  52. package/dist/runtime/result-BkziOG1L.d.ts +1 -0
  53. package/dist/runtime/router-BSBI1oN1.js +2377 -0
  54. package/dist/runtime/router-BSBI1oN1.js.map +1 -0
  55. package/dist/runtime/routes-Ce8TVP-T.js +690 -0
  56. package/dist/runtime/routes-Ce8TVP-T.js.map +1 -0
  57. package/dist/runtime/{schema-1Zs03-iS.js → schema-D1wOqiNH.js} +40 -12
  58. package/dist/runtime/schema-D1wOqiNH.js.map +1 -0
  59. package/dist/runtime/server.d.ts +5 -5
  60. package/dist/runtime/server.js +2 -2
  61. package/dist/runtime/{sync-Bs8J3fIr.d.ts → sync-D-GK2sv9.d.ts} +3 -2
  62. package/dist/runtime/{api-CAgKDij7.js → sync-DzUwA8W9.js} +22 -41
  63. package/dist/runtime/sync-DzUwA8W9.js.map +1 -0
  64. package/dist/runtime/types-DeCCyqLU-BIm7rU-0.d.ts +341 -0
  65. package/package.json +29 -4
  66. package/src/cli/agent-files.ts +14 -8
  67. package/src/cli/build/managed-client.ts +411 -0
  68. package/src/cli/build/managed-server.ts +294 -0
  69. package/src/cli/build/managed.ts +67 -0
  70. package/src/cli/build/output.ts +47 -0
  71. package/src/cli/build/server.ts +51 -220
  72. package/src/cli/client-config.ts +1 -140
  73. package/src/cli/client-styles.ts +1 -0
  74. package/src/cli/codegen.ts +9 -4
  75. package/src/cli/command.ts +28 -5
  76. package/src/cli/control-client.ts +84 -101
  77. package/src/cli/deploy.ts +133 -177
  78. package/src/cli/dev.ts +506 -107
  79. package/src/cli/image-assets.ts +499 -0
  80. package/src/cli/managed-client-boundaries.ts +103 -0
  81. package/src/cli/managed-dev-platform.ts +118 -0
  82. package/src/cli/managed-exports.ts +219 -0
  83. package/src/cli/managed-release-bin.ts +13 -0
  84. package/src/cli/managed-release.ts +260 -0
  85. package/src/cli/module-boundaries.ts +11 -1
  86. package/src/cli/new-app.ts +111 -87
  87. package/src/cli/route-codegen.ts +311 -0
  88. package/src/cli/route-static.ts +710 -0
  89. package/src/client/bootstrap.ts +110 -0
  90. package/src/client/errors.ts +13 -7
  91. package/src/client/files.ts +64 -0
  92. package/src/client/id.ts +9 -5
  93. package/src/client/image.ts +28 -0
  94. package/src/client/index.ts +25 -2
  95. package/src/client/managed-client.ts +729 -0
  96. package/src/client/managed-upgrade.ts +283 -0
  97. package/src/client/recovery-journal.ts +195 -0
  98. package/src/client/route-boundaries.ts +184 -0
  99. package/src/client/router-history.ts +152 -0
  100. package/src/client/router-store.ts +644 -0
  101. package/src/client/router.ts +324 -0
  102. package/src/client/routes.ts +28 -0
  103. package/src/client/sync.ts +66 -592
  104. package/src/dev-runtime/database.ts +77 -2
  105. package/src/dev-runtime/functions.ts +3 -3
  106. package/src/dev-runtime/id.ts +19 -4
  107. package/src/dev-runtime/managed-functions.ts +255 -0
  108. package/src/dev-runtime/managed-sync.ts +263 -0
  109. package/src/dev-runtime/managed-websocket.ts +71 -0
  110. package/src/dev-runtime/migrations.ts +20 -0
  111. package/src/dev-runtime/sync.ts +236 -236
  112. package/src/image-assets.d.ts +36 -0
  113. package/src/internal/client.ts +186 -0
  114. package/src/internal/host.ts +1 -1
  115. package/src/internal/http-paths.ts +0 -3
  116. package/src/internal/routes.ts +45 -0
  117. package/dist/runtime/api-CAgKDij7.js.map +0 -1
  118. package/dist/runtime/descriptor-Cyo9FP9n-C0SRVXNW.js +0 -154
  119. package/dist/runtime/descriptor-Cyo9FP9n-C0SRVXNW.js.map +0 -1
  120. package/dist/runtime/id-Bt9XWRGL.js.map +0 -1
  121. package/dist/runtime/id-Dz0apuB3.d.ts +0 -1
  122. package/dist/runtime/index-D54flWtH.d.ts +0 -402
  123. package/dist/runtime/pagination-DnKg3dkI-r5ZUxBBx.d.ts +0 -112
  124. package/dist/runtime/pagination-Dz0apuB3.d.ts +0 -1
  125. package/dist/runtime/result-DKAA4gpS.d.ts +0 -1
  126. package/dist/runtime/schema-1Zs03-iS.js.map +0 -1
  127. package/src/cli/build/client.ts +0 -119
  128. package/src/cli/build/public.ts +0 -186
  129. package/src/cli/client-entry.ts +0 -152
  130. package/src/cli/client-plugin.ts +0 -136
  131. package/src/client/app.ts +0 -15
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router-BSBI1oN1.js","names":["Array","String","Versioned.initial","Versioned.initial","Result","previous","invalid","Array"],"sources":["../../../contracts/dist/json.js","../../src/client/errors.ts","../../../shared/dist/id.js","../../src/client/files.ts","../../src/client/id.ts","../../../contracts/dist/runtime/index.js","../../../contracts/dist/runtime/hosted.js","../../../contracts/dist/managed-sync.js","../../src/client/managed-upgrade.ts","../../src/client/recovery-journal.ts","../../src/client/managed-client.ts","../../src/client/sync.ts","../../../shared/dist/routing/pattern.js","../../../shared/dist/routing/url.js","../../src/client/router.ts"],"sourcesContent":["import { Array, Predicate, Schema, String } from \"effect\";\n//#region src/json.ts\nconst encodeJson = (value) => {\n\tif (Array.isArray(value)) return `[${value.map(encodeJson).join(\",\")}]`;\n\tif (value === null || Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) return JSON.stringify(value);\n\treturn `{${Array.sortWith(Object.entries(value), ([key]) => key, String.Order).map(([key, field]) => `${JSON.stringify(key)}:${encodeJson(field)}`).join(\",\")}}`;\n};\nconst encodeCanonicalJson = (value) => encodeJson(Schema.decodeSync(Schema.Json)(value));\n//#endregion\nexport { encodeCanonicalJson };\n\n//# sourceMappingURL=json.js.map","/** @effect-diagnostics globalConsole:skip-file */\nimport { Cause, Effect, ErrorReporter, Schema } from \"effect\";\n\nimport { FunctionAddress } from \"@ignotum/contracts/runtime/sync\";\n\nexport class ConnectionUnavailable extends Schema.TaggedError<ConnectionUnavailable>()(\n \"ConnectionUnavailable\",\n {\n cause: Schema.optional(Schema.Defect()),\n message: Schema.String,\n },\n) {}\n\nexport class PlatformUpgrading extends Schema.TaggedError<PlatformUpgrading>()(\n \"PlatformUpgrading\",\n {\n message: Schema.String,\n },\n) {}\n\nexport class InvalidMutationArguments extends Schema.TaggedError<InvalidMutationArguments>()(\n \"InvalidMutationArguments\",\n {\n cause: Schema.Defect(),\n function: FunctionAddress,\n message: Schema.String,\n },\n) {}\n\nexport class InvalidServerMessage extends Schema.TaggedError<InvalidServerMessage>()(\n \"InvalidServerMessage\",\n {\n cause: Schema.Defect(),\n message: Schema.String,\n },\n) {}\n\nexport class ServerError extends Schema.TaggedError<ServerError>()(\"ServerError\", {\n code: Schema.Literals([\n \"PlatformUpgrading\",\n \"SessionExpired\",\n \"InvalidMessage\",\n \"Unavailable\",\n \"InvalidArguments\",\n \"InvocationIdConflict\",\n \"ResourceLimitExceeded\",\n ]),\n message: Schema.String,\n}) {}\n\nexport const ClientInfrastructureError = Schema.Union([\n PlatformUpgrading,\n ConnectionUnavailable,\n InvalidMutationArguments,\n InvalidServerMessage,\n ServerError,\n]);\nexport type ClientInfrastructureError = typeof ClientInfrastructureError.Type;\n\nconst browserErrorReporter = ErrorReporter.make(({ attributes, error }) => {\n globalThis.console.error(\"Ignotum infrastructure error\", error, attributes);\n});\n\nexport const clientErrorReporterLayer = ErrorReporter.layer([browserErrorReporter]);\n\nexport const reportClientError = Effect.fn(\"ClientErrorReporter.report\")(function* (\n error: ClientInfrastructureError,\n) {\n yield* ErrorReporter.report(Cause.fail(error));\n});\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { IdAlphabet, IdLength } from \"@ignotum/contracts/runtime/id\";\nimport { customAlphabet } from \"nanoid\";\n//#region src/id.ts\nconst decodeGenerated = (definition, payload) => Schema.decodeSync(definition)(definition.idPrefix === void 0 ? payload : `${definition.idPrefix}_${payload}`);\nvar IdGenerator = class IdGenerator extends Context.Service()(\"@ignotum/shared/id/IdGenerator\") {\n\tstatic layer = Layer.sync(IdGenerator, () => {\n\t\tconst generatePayload = customAlphabet(IdAlphabet, IdLength);\n\t\treturn IdGenerator.of({ generate: (definition) => Effect.sync(() => decodeGenerated(definition, generatePayload())) });\n\t});\n\tstatic deterministic = (startAt = 1) => Layer.sync(IdGenerator, () => {\n\t\tconst counters = /* @__PURE__ */ new Map();\n\t\treturn IdGenerator.of({ generate: (definition) => Effect.sync(() => {\n\t\t\tconst counter = (counters.get(definition.idPrefix) ?? startAt - 1) + 1;\n\t\t\tcounters.set(definition.idPrefix, counter);\n\t\t\treturn decodeGenerated(definition, counter.toString(36).padStart(IdLength, \"0\"));\n\t\t}) });\n\t});\n};\n//#endregion\nexport { IdGenerator };\n\n//# sourceMappingURL=id.js.map","import {\n FileId,\n fileGrantUrlOf,\n fileIdOf,\n fileFormats,\n fileLimits,\n fileMimeTypes,\n grantFileValue,\n isFileValue,\n makeFileValue,\n type FileFormat,\n type FileValue,\n} from \"@ignotum/contracts/schema/file\";\nimport type { FunctionAddress } from \"@ignotum/contracts/runtime/sync\";\nimport { InvalidServerMessage, ConnectionUnavailable, InvalidMutationArguments } from \"./errors.js\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport { Effect, Predicate, Schema } from \"effect\";\n\nexport const Files = {\n url: (file: FileValue): string => {\n const url = fileGrantUrlOf(file);\n if (url === undefined) {\n throw new Error(\"This FileValue has no active query grant.\");\n }\n return url;\n },\n} as const;\n\nconst formatByMime: Partial<Record<string, FileFormat>> = {};\nfor (const format of fileFormats) formatByMime[fileMimeTypes[format]] = format;\n\nconst MutationObject = Schema.ObjectKeyword.check(\n Schema.makeFilter((value) => Object.prototype.toString.call(value) === \"[object Object]\", {\n message: \"Mutation objects must contain ordinary fields; built-in collections are unsupported.\",\n }),\n);\n\nconst collectNativeFiles = (\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- This is the recursive parser for generated mutation arguments and native File values.\n value: unknown,\n files: Set<File>,\n): void => {\n if (value instanceof File) {\n files.add(value);\n return;\n }\n if (isFileValue(value) || Predicate.isDate(value)) return;\n if (globalThis.Array.isArray(value)) {\n for (const child of value) collectNativeFiles(child, files);\n return;\n }\n if (!Predicate.isObject(value)) return;\n for (const child of Object.values(Schema.decodeSync(MutationObject)(value))) {\n collectNativeFiles(child, files);\n }\n};\n\nconst replaceNativeFiles = (\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Each node is classified before it is copied into the transport value.\n value: unknown,\n replacements: ReadonlyMap<File, FileValue>,\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- The generated function schema validates the reconstructed argument value on the server.\n): unknown => {\n if (value instanceof File) return replacements.get(value);\n if (isFileValue(value) || Predicate.isDate(value)) return value;\n if (globalThis.Array.isArray(value))\n return value.map((child) => replaceNativeFiles(child, replacements));\n if (!Predicate.isObject(value)) return value;\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [key, replaceNativeFiles(child, replacements)]),\n );\n};\n\nexport interface PreparedMutationArguments {\n readonly value: unknown;\n readonly nativeFiles: ReadonlyMap<FileId, File>;\n readonly fileIds: ReadonlyArray<FileId>;\n}\n\nexport const prepareMutationArguments = Effect.fn(\"SyncClient.prepareMutationArguments\")(function* (\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Generated mutation argument types are erased only at this transport preparation boundary.\n input: unknown,\n) {\n const ids = yield* IdGenerator;\n const unique = yield* Effect.try(() => {\n const files = new Set<File>();\n collectNativeFiles(input, files);\n if (files.size > fileLimits.filesPerMutation) {\n throw new Error(`A mutation may upload at most ${fileLimits.filesPerMutation} files.`);\n }\n const totalBytes = [...files].reduce((total, file) => total + file.size, 0);\n if (totalBytes > fileLimits.mutationBytes) {\n throw new Error(`Mutation uploads may total at most ${fileLimits.mutationBytes} bytes.`);\n }\n return files;\n });\n const replacements = new Map<File, FileValue>();\n const nativeFiles = new Map<FileId, File>();\n for (const file of unique) {\n const format = yield* Effect.try(() => {\n const format = formatByMime[file.type.toLowerCase()];\n if (format === undefined) {\n throw new Error(\n `File '${file.name}' has unsupported media type '${file.type || \"unknown\"}'.`,\n );\n }\n if (file.size === 0 || file.size > fileLimits.fileBytes) {\n throw new Error(`File '${file.name}' must be between 1 and ${fileLimits.fileBytes} bytes.`);\n }\n if (new TextEncoder().encode(file.name).byteLength > fileLimits.filenameBytes) {\n throw new Error(`File '${file.name}' has a filename that is too long.`);\n }\n return format;\n });\n const id = yield* ids.generate(FileId);\n replacements.set(file, makeFileValue(id, { format, name: file.name, size: file.size }));\n nativeFiles.set(id, file);\n }\n const value =\n unique.size === 0 ? input : yield* Effect.try(() => replaceNativeFiles(input, replacements));\n return {\n value,\n nativeFiles,\n fileIds: Array.from(nativeFiles.keys()),\n } satisfies PreparedMutationArguments;\n});\n\ninterface FileGrant {\n readonly id: FileId;\n readonly url: string;\n}\n\n// @effect-diagnostics-next-line missingPipeableSignature:off File grant attachment naturally takes the decoded value first.\nexport const applyFileGrants = (\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Query result types are erased at the wire decoding boundary and checked against grant identities below.\n value: unknown,\n grants: ReadonlyArray<FileGrant>,\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- The traversal preserves the decoded query result shape while attaching private symbols.\n): unknown => {\n if (grants.length === 0) return value;\n\n const byId = new Map<FileId, string>();\n for (const grant of grants) {\n if (byId.has(grant.id)) throw new Error(\"A query file grant ID is duplicated.\");\n byId.set(grant.id, grant.url);\n }\n const matched = new Set<FileId>();\n const visit = (\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- This recursive visitor identifies file values before attaching grants.\n current: unknown,\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- Recursive branches preserve their input shape.\n ): unknown => {\n if (isFileValue(current)) {\n const id = fileIdOf(current);\n const url = byId.get(id);\n if (url === undefined) return current;\n matched.add(id);\n return grantFileValue(current, url);\n }\n if (globalThis.Array.isArray(current)) {\n return current.map(visit);\n }\n if (!Predicate.isObject(current) || Predicate.isDate(current)) {\n return current;\n }\n return Object.fromEntries(Object.entries(current).map(([key, child]) => [key, visit(child)]));\n };\n const granted = visit(value);\n if (matched.size !== byId.size) throw new Error(\"A query file grant has no result value.\");\n return granted;\n};\n\nexport const uploadPreparedFiles = Effect.fn(\"uploadPreparedFiles\")(function* (\n nativeFiles: ReadonlyMap<FileId, File>,\n uploads: ReadonlyArray<{ readonly id: FileId; readonly url?: string }>,\n functionAddress: FunctionAddress,\n) {\n const expected = new Set(nativeFiles.keys());\n const received = new Set<string>();\n const transfers: Array<{ readonly file: File; readonly url: string }> = [];\n for (const upload of uploads) {\n if (!expected.has(upload.id) || received.has(upload.id)) {\n return yield* InvalidServerMessage.make({\n cause: new Error(`Unexpected prepared file '${upload.id}'.`),\n message: \"The server returned invalid application file preparation data.\",\n });\n }\n received.add(upload.id);\n const file = nativeFiles.get(upload.id);\n if (file === undefined) {\n return yield* InvalidServerMessage.make({\n cause: new Error(`Missing native file '${upload.id}'.`),\n message: \"The server prepared an unknown application file.\",\n });\n }\n if (upload.url === undefined) continue;\n transfers.push({ file, url: upload.url });\n }\n if (received.size !== expected.size) {\n return yield* InvalidServerMessage.make({\n cause: new Error(\"The server omitted a prepared file.\"),\n message: \"The server returned incomplete application file preparation data.\",\n });\n }\n yield* Effect.forEach(\n transfers,\n Effect.fn(\"SyncClient.uploadFile\")(function* ({ file, url }) {\n const response = yield* Effect.tryPromise({\n try: (signal) =>\n fetch(url, {\n method: \"PUT\",\n body: file,\n headers: { \"content-type\": file.type },\n signal,\n }),\n catch: (cause) =>\n ConnectionUnavailable.make({\n cause,\n message: `File '${file.name}' could not be uploaded.`,\n }),\n });\n if (!response.ok) {\n const detail = yield* Effect.promise(() => response.text());\n return yield* InvalidMutationArguments.make({\n cause: new Error(detail),\n function: functionAddress,\n message: `File '${file.name}' was rejected by application storage.`,\n });\n }\n }),\n { concurrency: 3, discard: true },\n );\n});\n","import { Context, Effect, Layer, Option, Schema, Semaphore } from \"effect\";\nimport {\n FetchHttpClient,\n HttpClient,\n HttpClientRequest,\n HttpClientResponse,\n} from \"effect/unstable/http\";\nimport {\n DevelopmentSelection,\n developmentSelectionKey,\n SessionOutcome,\n SessionRedirect,\n SessionRequest,\n SessionResponse,\n sessionPath,\n sessionRequestsPath,\n type ProfileField,\n type SessionState,\n type User,\n} from \"@ignotum/contracts/id\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport { SessionEpoch } from \"@ignotum/contracts/runtime/id\";\n\nexport class IdRequestError extends Schema.TaggedError<IdRequestError>()(\"IdRequestError\", {\n message: Schema.String,\n}) {}\n\nexport type IdState =\n | { readonly status: \"pending\"; readonly outcome?: SessionOutcome }\n | { readonly status: \"error\"; readonly error: string; readonly outcome?: SessionOutcome }\n | { readonly status: \"signedOut\"; readonly outcome?: SessionOutcome }\n | { readonly status: \"signedIn\"; readonly user: User; readonly outcome?: SessionOutcome };\n\nconst outcomeKey = \"ignotum.id.outcome\";\nconst selectionJson = Schema.fromJsonString(DevelopmentSelection);\n\nexport class BrowserSession extends Context.Service<\n BrowserSession,\n {\n readonly snapshot: () => IdState;\n readonly current: () => SessionState | undefined;\n readonly subscribe: (listener: () => void) => () => void;\n readonly bootstrap: Effect.Effect<SessionState, IdRequestError>;\n readonly accept: (session: SessionState, serverTime: number) => void;\n readonly suspend: (error?: string) => void;\n readonly socketParameters: () => string;\n readonly start: (\n intent: \"signIn\" | \"requestProfile\",\n profile: ReadonlyArray<ProfileField>,\n returnTo?: string,\n ) => Effect.Effect<void, IdRequestError>;\n readonly signOut: Effect.Effect<void, IdRequestError>;\n }\n>()(\"ignotum/client/id/BrowserSession\") {\n static readonly layer = Layer.effect(\n BrowserSession,\n Effect.gen(function* () {\n const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);\n const ids = yield* IdGenerator;\n const bootstrapLock = yield* Semaphore.make(1);\n const listeners = new Set<() => void>();\n let state: IdState = { status: \"pending\" };\n let current: SessionState | undefined;\n let generation = 0;\n let deadline = Infinity;\n let development = false;\n let selection: DevelopmentSelection | undefined;\n let expiry: ReturnType<typeof setTimeout> | undefined;\n const notify = () => {\n for (const listener of listeners) listener();\n };\n const suspend = (error?: string) => {\n generation += 1;\n deadline = Infinity;\n if (expiry !== undefined) clearTimeout(expiry);\n current = undefined;\n state =\n error === undefined\n ? { status: \"pending\", outcome: state.outcome }\n : { status: \"error\", error, outcome: state.outcome };\n notify();\n };\n const accept = (session: SessionState, serverTime: number) => {\n generation += 1;\n if (expiry !== undefined) clearTimeout(expiry);\n current = session;\n state =\n session.user === null\n ? { status: \"signedOut\", outcome: state.outcome }\n : { status: \"signedIn\", user: session.user, outcome: state.outcome };\n const delay = Math.max(0, session.validUntil - serverTime);\n deadline = performance.now() + delay;\n if (delay < 2_147_483_647) expiry = setTimeout(() => suspend(), delay);\n notify();\n };\n const checkExpiry = () => {\n if (current !== undefined && performance.now() >= deadline) suspend();\n };\n globalThis.addEventListener?.(\"focus\", checkExpiry);\n globalThis.document?.addEventListener(\"visibilitychange\", checkExpiry);\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n if (expiry !== undefined) clearTimeout(expiry);\n listeners.clear();\n globalThis.removeEventListener?.(\"focus\", checkExpiry);\n globalThis.document?.removeEventListener(\"visibilitychange\", checkExpiry);\n }),\n );\n\n const readOutcome = () => {\n try {\n const raw = globalThis.sessionStorage.getItem(outcomeKey);\n if (raw !== null) {\n const decoded = Schema.decodeUnknownOption(SessionOutcome)(raw);\n if (Option.isSome(decoded)) state = { ...state, outcome: decoded.value };\n globalThis.sessionStorage.removeItem(outcomeKey);\n }\n } catch {\n // The authenticated session response remains valid when optional redirect storage is denied.\n }\n };\n const parameters = () => {\n if (!development || selection === undefined) return \"\";\n const params = new URLSearchParams({ epoch: selection.epoch });\n if (selection.username !== null) params.set(\"username\", selection.username);\n return `?${params}`;\n };\n const readSession = Effect.fn(\"BrowserSession.read\")(function* () {\n return yield* client\n .get(`${sessionPath}${parameters()}`, { headers: { \"x-ignotum-request\": \"1\" } })\n .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(SessionResponse)));\n });\n let bootstrapGeneration = 0;\n const bootstrap = bootstrapLock\n .withPermits(1)(\n Effect.gen(function* () {\n const admittedGeneration = generation;\n bootstrapGeneration = admittedGeneration;\n const startedAt = performance.now();\n let session = yield* readSession();\n development = session.development === true;\n if (development && selection === undefined) {\n const saved = globalThis.sessionStorage.getItem(developmentSelectionKey);\n const decoded =\n saved === null\n ? Option.none<DevelopmentSelection>()\n : Schema.decodeOption(selectionJson)(saved);\n selection = Option.getOrElse(decoded, () => ({\n formatVersion: 1 as const,\n username: null,\n epoch: \"\",\n }));\n if (selection.epoch === \"\")\n selection = { ...selection, epoch: yield* ids.generate(SessionEpoch) };\n globalThis.sessionStorage.setItem(\n developmentSelectionKey,\n Schema.encodeSync(selectionJson)(selection),\n );\n session = yield* readSession();\n }\n if (generation !== admittedGeneration) {\n if (current !== undefined) return current;\n return yield* IdRequestError.make({\n message: \"Your ID session changed while loading.\",\n });\n }\n readOutcome();\n if (session.outcome !== undefined) state = { ...state, outcome: session.outcome };\n accept(session, session.serverTime + performance.now() - startedAt);\n return session;\n }),\n )\n .pipe(\n Effect.mapError(() =>\n IdRequestError.make({ message: \"Could not load your ID session.\" }),\n ),\n Effect.tapError((error) =>\n Effect.sync(() => {\n if (generation === bootstrapGeneration) suspend(error.message);\n }),\n ),\n );\n\n const start = Effect.fn(\"BrowserSession.start\")(function* (\n intent: \"signIn\" | \"requestProfile\",\n profile: ReadonlyArray<ProfileField>,\n returnTo?: string,\n ) {\n const session = current ?? (yield* bootstrap);\n if (intent === \"requestProfile\" && session.user === null)\n return yield* IdRequestError.make({\n message: \"Sign in before requesting profile information.\",\n });\n const request = yield* Schema.decodeUnknownEffect(SessionRequest)({\n intent,\n profile,\n sessionEpoch: session.sessionEpoch,\n returnTo:\n returnTo ??\n `${globalThis.location.pathname}${globalThis.location.search}${globalThis.location.hash}`,\n }).pipe(\n Effect.mapError(() => IdRequestError.make({ message: \"The ID request is invalid.\" })),\n );\n const redirect = yield* HttpClientRequest.post(sessionRequestsPath).pipe(\n HttpClientRequest.setHeader(\"x-ignotum-request\", \"1\"),\n HttpClientRequest.bodyJsonUnsafe(request),\n client.execute,\n Effect.flatMap(HttpClientResponse.schemaBodyJson(SessionRedirect)),\n Effect.mapError(() =>\n IdRequestError.make({ message: \"Could not start the ID request.\" }),\n ),\n );\n if (current?.sessionEpoch !== session.sessionEpoch)\n return yield* IdRequestError.make({ message: \"Your ID session changed. Try again.\" });\n globalThis.location.assign(redirect.redirectUrl);\n });\n const signOut = Effect.gen(function* () {\n const session = current ?? (yield* bootstrap);\n yield* HttpClientRequest.delete(sessionPath).pipe(\n HttpClientRequest.setHeader(\"x-ignotum-request\", \"1\"),\n HttpClientRequest.bodyJsonUnsafe({ sessionEpoch: session.sessionEpoch }),\n client.execute,\n Effect.mapError(() => IdRequestError.make({ message: \"Could not sign out.\" })),\n );\n suspend();\n if (development) {\n selection = {\n formatVersion: 1,\n username: null,\n epoch: yield* ids.generate(SessionEpoch),\n };\n globalThis.sessionStorage.setItem(\n developmentSelectionKey,\n Schema.encodeSync(selectionJson)(selection),\n );\n }\n globalThis.location.reload();\n });\n return BrowserSession.of({\n snapshot: () => {\n checkExpiry();\n return state;\n },\n current: () => {\n checkExpiry();\n return current;\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n accept,\n suspend,\n bootstrap,\n start,\n signOut,\n socketParameters: parameters,\n });\n }),\n ).pipe(Layer.provide(FetchHttpClient.layer));\n}\n","import { encodeCanonicalJson } from \"../json.js\";\nimport { schemaIndexLimits } from \"../schema/values.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/index.ts\nconst IndexIdentity = Schema.String.pipe(Schema.brand(\"ignotum/runtime/IndexIdentity\"));\nconst EncodedIndexKey = Schema.String.check(Schema.isPattern(/^(?:[0-9a-f]{2})*$/)).pipe(Schema.brand(\"ignotum/runtime/EncodedIndexKey\"));\nconst IndexScalarValue = Schema.Union([\n\tSchema.Boolean,\n\tSchema.Finite,\n\tSchema.String\n]);\nconst scalarValueKind = (value) => Schema.is(Schema.Boolean)(value) ? \"boolean\" : Schema.is(Schema.Finite)(value) ? \"number\" : \"string\";\nconst encodeString = (value) => {\n\tconst bytes = [];\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst unit = value.charCodeAt(index);\n\t\tbytes.push(1, unit >>> 8, unit & 255);\n\t}\n\tbytes.push(0);\n\treturn Array.from(bytes);\n};\nconst encodeNumber = (input) => {\n\tconst value = Object.is(input, -0) ? 0 : input;\n\tif (!Number.isFinite(value)) throw new Error(\"Index numbers must be finite.\");\n\tconst bytes = /* @__PURE__ */ new Uint8Array(8);\n\tnew DataView(bytes.buffer).setFloat64(0, value, false);\n\tif ((bytes[0] ?? 0) >= 128) for (let index = 0; index < bytes.length; index += 1) bytes[index] = 255 - bytes[index];\n\telse bytes[0] = (bytes[0] ?? 0) ^ 128;\n\treturn Array.from(bytes);\n};\nconst scalarKind = (descriptor) => {\n\tswitch (descriptor.type) {\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"date\":\n\t\tcase \"integer\":\n\t\tcase \"number\": return \"number\";\n\t\tcase \"userId\":\n\t\tcase \"id\":\n\t\tcase \"string\": return \"string\";\n\t\tcase \"literal\": return scalarValueKind(descriptor.value);\n\t\tcase \"literals\": {\n\t\t\tconst first = descriptor.values[0];\n\t\t\tif (first === void 0) throw new Error(\"Indexed literal sets cannot be empty.\");\n\t\t\tconst kind = scalarValueKind(first);\n\t\t\tif (descriptor.values.some((value) => scalarValueKind(value) !== kind)) throw new Error(\"Indexed literal sets cannot mix value types.\");\n\t\t\treturn kind;\n\t\t}\n\t\tdefault: throw new Error(`Values of type '${descriptor.type}' cannot be indexed.`);\n\t}\n};\nconst encodeScalar = (descriptor, value) => {\n\tswitch (scalarKind(descriptor)) {\n\t\tcase \"boolean\":\n\t\t\tif (!Schema.is(Schema.Boolean)(value)) throw new Error(\"Expected an indexed boolean value.\");\n\t\t\treturn [value ? 1 : 0];\n\t\tcase \"number\":\n\t\t\tif (!Schema.is(Schema.Finite)(value)) throw new Error(\"Expected an indexed number value.\");\n\t\t\treturn encodeNumber(value);\n\t\tcase \"string\":\n\t\t\tif (!Schema.is(Schema.String)(value)) throw new Error(\"Expected an indexed string value.\");\n\t\t\treturn encodeString(value);\n\t}\n};\nconst encodeBytes = (bytes) => EncodedIndexKey.make(bytes.map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\"));\nconst encodeIndexPrefix = (descriptors, values) => {\n\tif (descriptors.length !== values.length) throw new Error(\"Index descriptors and values must have the same length.\");\n\tconst bytes = descriptors.flatMap((descriptor, index) => encodeScalar(descriptor, values[index]));\n\tif (bytes.length > schemaIndexLimits.keyBytes) throw new Error(`Index keys cannot exceed ${schemaIndexLimits.keyBytes} bytes.`);\n\treturn encodeBytes(bytes);\n};\nconst encodeIndexKey = (descriptors, values, createdAt, id) => {\n\tconst bytes = [\n\t\t...descriptors.flatMap((descriptor, index) => encodeScalar(descriptor, values[index])),\n\t\t...encodeNumber(createdAt),\n\t\t...encodeString(id)\n\t];\n\tif (bytes.length > schemaIndexLimits.keyBytes) throw new Error(`Index keys cannot exceed ${schemaIndexLimits.keyBytes} bytes.`);\n\treturn encodeBytes(bytes);\n};\nconst successorIndexPrefix = (prefix) => {\n\tconst bytes = Array.from({ length: prefix.length / 2 }, (_, index) => Number.parseInt(prefix.slice(index * 2, index * 2 + 2), 16));\n\tfor (let index = bytes.length - 1; index >= 0; index -= 1) {\n\t\tconst byte = bytes[index];\n\t\tif (byte === void 0 || byte === 255) continue;\n\t\tbytes[index] = byte + 1;\n\t\treturn encodeBytes(bytes.slice(0, index + 1));\n\t}\n};\nconst encodeIndexRange = (descriptors, equal, lower, upper) => {\n\tconst equalDescriptors = descriptors.slice(0, equal.length);\n\tconst prefix = encodeIndexPrefix(equalDescriptors, equal);\n\tconst rangeDescriptor = descriptors[equal.length];\n\tif ((lower !== void 0 || upper !== void 0) && rangeDescriptor === void 0) throw new Error(\"An index range exceeded the index fields.\");\n\tconst encodedLower = lower === void 0 ? prefix.length === 0 ? void 0 : prefix : EncodedIndexKey.make(`${prefix}${encodeIndexPrefix([rangeDescriptor], [lower.value])}`);\n\tconst encodedUpper = upper === void 0 ? prefix.length === 0 ? void 0 : successorIndexPrefix(prefix) : EncodedIndexKey.make(`${prefix}${encodeIndexPrefix([rangeDescriptor], [upper.value])}`);\n\tconst finalLower = encodedLower !== void 0 && lower !== void 0 && !lower.inclusive ? successorIndexPrefix(encodedLower) : encodedLower;\n\tconst finalUpper = encodedUpper !== void 0 && upper !== void 0 && upper.inclusive ? successorIndexPrefix(encodedUpper) : encodedUpper;\n\tif (finalLower === void 0 && finalUpper === void 0) return {};\n\tif (finalLower === void 0) return { upper: finalUpper };\n\tif (finalUpper === void 0) return { lower: finalLower };\n\treturn {\n\t\tlower: finalLower,\n\t\tupper: finalUpper\n\t};\n};\nconst indexIdentity = (tableId, name, fields) => IndexIdentity.make(encodeCanonicalJson([\n\ttableId,\n\tname,\n\tfields\n]));\n//#endregion\nexport { EncodedIndexKey, IndexIdentity, IndexScalarValue, encodeIndexKey, encodeIndexPrefix, encodeIndexRange, indexIdentity, successorIndexPrefix };\n\n//# sourceMappingURL=index.js.map","import { AppId, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, ConnectionId, DevDatabaseLockId, GeneratedId, InvocationId, PlatformPrincipalId, RequestId, RuntimeRequestNonce, SubscriptionId, TableId, TeamId, VersionId } from \"./id.js\";\nimport { ActivationGeneration, AppStateRevision, CapabilityId, ClientApiVersion, DataHistoryId, InvocationKey, PlatformGeneration, PlatformReleaseId, ProtocolVersion, ServerApiVersion, VersionNumber } from \"./identity.js\";\nimport { encodeCanonicalJson } from \"../json.js\";\nimport { FileId, RuntimeFileMetadata, RuntimeFileOccurrence } from \"../schema/file.js\";\nimport { SessionState } from \"../id.js\";\nimport { FunctionAddress, WireFailure, WireResult, WireSuccess } from \"./sync.js\";\nimport { ExecutionSelection, RecoveryIdentity, RecoverySessionId } from \"../platform.js\";\nimport { EncodedIndexKey, IndexIdentity } from \"./index.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/hosted.ts\nconst QueryKey = Schema.String.pipe(Schema.brand(\"ignotum/hosted/QueryKey\"));\nconst TableDependency = Schema.Struct({\n\ttype: Schema.Literal(\"Table\"),\n\ttableId: TableId\n});\nconst DocumentDependency = Schema.Struct({\n\ttype: Schema.Literal(\"Document\"),\n\ttableId: TableId,\n\tid: GeneratedId\n});\nconst IndexRangeDependency = Schema.Struct({\n\ttype: Schema.Literal(\"IndexRange\"),\n\ttableId: TableId,\n\tindex: IndexIdentity,\n\tlower: Schema.optional(EncodedIndexKey),\n\tupper: Schema.optional(EncodedIndexKey)\n});\nconst IndexPointInvalidation = Schema.Struct({\n\ttype: Schema.Literal(\"IndexPoint\"),\n\ttableId: TableId,\n\tindex: IndexIdentity,\n\tkey: EncodedIndexKey\n});\nconst IdDependency = Schema.Struct({ type: Schema.Literal(\"Id\") });\nconst ReadDependency = Schema.Union([\n\tIdDependency,\n\tTableDependency,\n\tDocumentDependency,\n\tIndexRangeDependency\n]);\nconst WriteInvalidation = Schema.Union([\n\tTableDependency,\n\tDocumentDependency,\n\tIndexPointInvalidation\n]);\nconst DependencyKey = Schema.Union([ReadDependency, IndexPointInvalidation]);\nconst DependencySet = Schema.Array(ReadDependency);\nconst InvalidationSet = Schema.Array(WriteInvalidation);\nconst RuntimeQueryResult = Schema.Struct({\n\ttype: Schema.Literal(\"Query\"),\n\tresult: WireResult,\n\tdependencies: DependencySet,\n\tobservedRevision: AppStateRevision,\n\tfiles: Schema.optional(Schema.Array(RuntimeFileOccurrence))\n});\nconst FileReferenceAdded = Schema.Struct({\n\ttype: Schema.Literal(\"AddReference\"),\n\tfile: RuntimeFileMetadata,\n\ttableId: TableId,\n\tdocumentId: GeneratedId\n});\nconst FileReferenceRemoved = Schema.Struct({\n\ttype: Schema.Literal(\"RemoveReference\"),\n\tfileId: FileId,\n\ttableId: TableId,\n\tdocumentId: GeneratedId\n});\nconst FileReferenceEffect = Schema.Union([FileReferenceAdded, FileReferenceRemoved]);\nconst FileEffectBatch = Schema.Struct({\n\tid: InvocationId,\n\tdataHistoryId: Schema.optional(DataHistoryId),\n\tcommittedRevision: AppStateRevision,\n\teffects: Schema.Array(FileReferenceEffect)\n});\nconst FileEffectsRequest = Schema.Struct({ appId: AppId });\nconst FileEffectsResult = Schema.Struct({ batches: Schema.Array(FileEffectBatch) });\nconst FileEffectsAcknowledgeRequest = Schema.Struct({\n\tappId: AppId,\n\tinvocationId: InvocationId,\n\tacknowledgedAt: Schema.Int,\n\tdataHistoryId: DataHistoryId\n});\nconst FileEffectsAcknowledgeResult = Schema.Struct({ completed: Schema.Literal(true) });\nconst RuntimeMutationSuccess = Schema.Struct({\n\ttype: Schema.Literal(\"Mutation\"),\n\tresult: WireSuccess,\n\tinvalidations: InvalidationSet,\n\tcommittedRevision: AppStateRevision,\n\tfileEffects: Schema.optional(FileEffectBatch)\n});\nconst RuntimeMutationFailure = Schema.Struct({\n\ttype: Schema.Literal(\"Mutation\"),\n\tresult: WireFailure\n});\nconst RuntimeMutationResult = Schema.Union([RuntimeMutationSuccess, RuntimeMutationFailure]);\nconst RuntimeInvocationResult = Schema.Union([RuntimeQueryResult, RuntimeMutationResult]);\nconst RuntimeRecoveryOwner = Schema.Struct({\n\tclientSessionId: RecoverySessionId,\n\tsessionEpoch: Schema.NullOr(Schema.String)\n});\nconst RuntimeMutationOutcomeRequest = Schema.Struct({\n\tappId: AppId,\n\tidentity: RecoveryIdentity,\n\towner: RuntimeRecoveryOwner\n});\nconst RuntimeMutationOutcome = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Settled\"),\n\t\tresult: RuntimeMutationResult\n\t}),\n\tSchema.Struct({ type: Schema.Literal(\"Interrupted\") }),\n\tSchema.Struct({ type: Schema.Literal(\"Pending\") }),\n\tSchema.Struct({ type: Schema.Literal(\"Uncertain\") })\n]);\nconst InvocationBase = {\n\tappId: AppId,\n\tversionId: VersionId,\n\tgeneration: ActivationGeneration,\n\tselection: Schema.optional(ExecutionSelection),\n\tinvocationKey: InvocationKey,\n\tfunction: FunctionAddress,\n\targs: Schema.Json,\n\tidentity: Schema.optional(SessionState)\n};\nconst QueryInvocation = Schema.Struct({\n\t...InvocationBase,\n\ttype: Schema.Literal(\"Query\")\n});\nconst MutationInvocation = Schema.Struct({\n\t...InvocationBase,\n\ttype: Schema.Literal(\"Mutation\"),\n\tinvocationId: InvocationId,\n\trecoveryOwner: Schema.optional(RuntimeRecoveryOwner),\n\tfiles: Schema.optional(Schema.Array(RuntimeFileOccurrence))\n});\nconst RuntimeInvocation = Schema.Union([QueryInvocation, MutationInvocation]);\nconst RevisionCheck = Schema.Struct({\n\tappId: AppId,\n\texpectedRevision: AppStateRevision\n});\nconst RevisionCheckResult = Schema.Struct({ currentRevision: AppStateRevision });\nvar RuntimeVersionUnavailable = class extends Schema.TaggedError()(\"RuntimeVersionUnavailable\", {\n\tversionId: VersionId,\n\tmessage: Schema.String\n}) {};\nconst RuntimeInvocationRejectionCode = Schema.Literals([\n\t\"SessionExpired\",\n\t\"FunctionUnavailable\",\n\t\"InvalidArguments\",\n\t\"InvocationIdConflict\",\n\t\"ResourceLimitExceeded\",\n\t\"UnknownFunction\",\n\t\"WrongFunctionKind\"\n]);\nvar RuntimeInvocationRejected = class extends Schema.TaggedError()(\"RuntimeInvocationRejected\", {\n\tcode: RuntimeInvocationRejectionCode,\n\tinvocationKey: InvocationKey,\n\tmessage: Schema.String\n}) {};\nvar RuntimeInvocationUnavailable = class extends Schema.TaggedError()(\"RuntimeInvocationUnavailable\", {\n\tinvocationKey: InvocationKey,\n\tmessage: Schema.String\n}) {};\nvar RuntimeRevisionRejected = class extends Schema.TaggedError()(\"RuntimeRevisionRejected\", {\n\tappId: AppId,\n\tmessage: Schema.String\n}) {};\nconst RuntimeTransportError = Schema.Union([\n\tRuntimeVersionUnavailable,\n\tRuntimeInvocationRejected,\n\tRuntimeInvocationUnavailable\n]);\nconst dependencyKey = (dependency) => dependency.type === \"Id\" ? \"Id\" : dependency.type === \"Table\" ? encodeCanonicalJson([dependency.type, dependency.tableId]) : dependency.type === \"Document\" ? encodeCanonicalJson([\n\tdependency.type,\n\tdependency.tableId,\n\tdependency.id\n]) : dependency.type === \"IndexPoint\" ? encodeCanonicalJson([\n\tdependency.type,\n\tdependency.index,\n\tdependency.key\n]) : encodeCanonicalJson([\n\tdependency.type,\n\tdependency.index,\n\tdependency.lower ?? null,\n\tdependency.upper ?? null\n]);\nconst canonicalQueryKey = (versionId, functionAddress, args) => QueryKey.make(encodeCanonicalJson([\n\tversionId,\n\tfunctionAddress,\n\targs\n]));\nconst canonicalInvocationInput = (versionId, functionKind, functionAddress, args, sessionEpoch) => encodeCanonicalJson(sessionEpoch === void 0 ? [\n\tversionId,\n\tfunctionKind,\n\tfunctionAddress,\n\targs\n] : [\n\tversionId,\n\tfunctionKind,\n\tfunctionAddress,\n\targs,\n\tsessionEpoch\n]);\nconst mutationInvocationKey = (appId, invocationId) => InvocationKey.make(encodeCanonicalJson([appId, invocationId]));\nconst tableDependency = (tableId) => ({\n\ttype: \"Table\",\n\ttableId\n});\nconst documentDependency = (tableId, id) => ({\n\ttype: \"Document\",\n\ttableId,\n\tid\n});\nconst indexRangeDependency = (tableId, index, lower, upper) => ({\n\ttype: \"IndexRange\",\n\ttableId,\n\tindex,\n\tlower,\n\tupper\n});\nconst indexPointInvalidation = (tableId, index, key) => ({\n\ttype: \"IndexPoint\",\n\ttableId,\n\tindex,\n\tkey\n});\n//#endregion\nexport { ActivationGeneration, AppId, AppStateRevision, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, CapabilityId, ClientApiVersion, ConnectionId, DataHistoryId, DependencyKey, DependencySet, DevDatabaseLockId, DocumentDependency, FileEffectBatch, FileEffectsAcknowledgeRequest, FileEffectsAcknowledgeResult, FileEffectsRequest, FileEffectsResult, FileReferenceAdded, FileReferenceEffect, FileReferenceRemoved, IdDependency, IndexPointInvalidation, IndexRangeDependency, InvalidationSet, InvocationId, InvocationKey, MutationInvocation, PlatformGeneration, PlatformPrincipalId, PlatformReleaseId, ProtocolVersion, QueryInvocation, QueryKey, ReadDependency, RequestId, RevisionCheck, RevisionCheckResult, RuntimeInvocation, RuntimeInvocationRejected, RuntimeInvocationRejectionCode, RuntimeInvocationResult, RuntimeInvocationUnavailable, RuntimeMutationFailure, RuntimeMutationOutcome, RuntimeMutationOutcomeRequest, RuntimeMutationResult, RuntimeMutationSuccess, RuntimeQueryResult, RuntimeRecoveryOwner, RuntimeRequestNonce, RuntimeRevisionRejected, RuntimeTransportError, RuntimeVersionUnavailable, ServerApiVersion, SubscriptionId, TableDependency, TableId, TeamId, VersionId, VersionNumber, WriteInvalidation, canonicalInvocationInput, canonicalQueryKey, dependencyKey, documentDependency, indexPointInvalidation, indexRangeDependency, mutationInvocationKey, tableDependency };\n\n//# sourceMappingURL=hosted.js.map","import { InvocationId, SubscriptionId } from \"./runtime/id.js\";\nimport { FileId, fileLimits } from \"./schema/file.js\";\nimport { SessionState } from \"./id.js\";\nimport { FunctionAddress } from \"./runtime/sync.js\";\nimport { ExecutionSelection, RecoveryIdentity, RecoverySessionId } from \"./platform.js\";\nimport { RuntimeMutationOutcome, RuntimeQueryResult } from \"./runtime/hosted.js\";\nimport { Schema } from \"effect\";\n//#region src/managed-sync.ts\nconst managedSyncPath = \"/_ignotum/v2/sync\";\nconst managedSelectionPath = \"/_ignotum/v2/selection\";\nconst managedProtocolVersion = 1;\nconst ManagedSelectionResponse = Schema.Struct({\n\tprotocolVersion: Schema.Literal(1),\n\tselection: ExecutionSelection\n});\nconst ManagedClientMessage = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Connect\"),\n\t\tprotocolVersion: Schema.Natural,\n\t\tselection: ExecutionSelection,\n\t\tclientSessionId: RecoverySessionId\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Prepare\"),\n\t\tinvocationId: InvocationId,\n\t\tfunction: FunctionAddress,\n\t\targs: Schema.Json,\n\t\tfiles: Schema.Array(FileId).check(Schema.isMaxLength(fileLimits.filesPerMutation))\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Invoke\"),\n\t\tinvocationId: InvocationId,\n\t\tfunction: FunctionAddress,\n\t\targs: Schema.Json\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"RecoverMutation\"),\n\t\tid: Schema.String.check(Schema.isMaxLength(128)),\n\t\tidentity: RecoveryIdentity\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Subscribe\"),\n\t\tid: SubscriptionId,\n\t\tfunction: FunctionAddress,\n\t\targs: Schema.Json\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Unsubscribe\"),\n\t\tid: SubscriptionId\n\t})\n]);\n/** Decode this envelope before the normal server protocol, including on unsupported versions. */\nconst ManagedUpgradeRequired = Schema.Struct({\n\ttype: Schema.Literal(\"UpgradeRequired\"),\n\tselection: ExecutionSelection\n});\nconst ManagedServerMessage = Schema.Union([\n\tManagedUpgradeRequired,\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Handshake\"),\n\t\tprotocolVersion: Schema.Literal(1),\n\t\tselection: ExecutionSelection,\n\t\tsession: SessionState,\n\t\tserverTime: Schema.Finite\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Preparation\"),\n\t\tinvocationId: InvocationId,\n\t\tuploads: Schema.Array(Schema.Struct({\n\t\t\tid: FileId,\n\t\t\turl: Schema.optional(Schema.String)\n\t\t}))\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"MutationOutcome\"),\n\t\tid: Schema.String,\n\t\tidentity: RecoveryIdentity,\n\t\toutcome: RuntimeMutationOutcome\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"QuerySnapshot\"),\n\t\tselection: ExecutionSelection,\n\t\tid: SubscriptionId,\n\t\tresult: RuntimeQueryResult,\n\t\tfiles: Schema.optional(Schema.Array(Schema.Struct({\n\t\t\tid: FileId,\n\t\t\turl: Schema.String\n\t\t})))\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"Error\"),\n\t\tid: Schema.optional(Schema.String),\n\t\tcode: Schema.Literals([\n\t\t\t\"PlatformUpgrading\",\n\t\t\t\"SessionExpired\",\n\t\t\t\"InvalidMessage\",\n\t\t\t\"Unavailable\",\n\t\t\t\"InvalidArguments\",\n\t\t\t\"InvocationIdConflict\",\n\t\t\t\"ResourceLimitExceeded\"\n\t\t]),\n\t\tmessage: Schema.String\n\t})\n]);\n//#endregion\nexport { ManagedClientMessage, ManagedSelectionResponse, ManagedServerMessage, ManagedUpgradeRequired, managedProtocolVersion, managedSelectionPath, managedSyncPath };\n\n//# sourceMappingURL=managed-sync.js.map","import {\n ExecutionSelection,\n RecoverySessionId,\n sameExecutionSelection,\n} from \"@ignotum/contracts/platform\";\nimport * as Versioned from \"@ignotum/contracts/versioned\";\nimport { AppId } from \"@ignotum/contracts/runtime/identity\";\nimport { Option, Schema } from \"effect\";\n\nconst TabStateV1 = Schema.Struct({\n formatVersion: Schema.Literal(1),\n appId: AppId,\n clientSessionId: RecoverySessionId,\n attempts: Schema.Natural.check(Schema.isLessThanOrEqualTo(3)),\n attemptedAt: Schema.Natural,\n target: Schema.NullOr(ExecutionSelection),\n uncertainStorage: Schema.Boolean,\n}).annotate({ parseOptions: { onExcessProperty: \"error\" } });\nconst TabState = Versioned.initial(TabStateV1);\nconst TabStateJson = Schema.fromJsonString(TabState);\n\nexport interface ManagedUpdateSnapshot {\n readonly phase: \"connecting\" | \"ready\" | \"settling\" | \"reloading\" | \"error\";\n readonly message?: string;\n readonly recovery: readonly string[];\n}\n\nexport interface ManagedUpgradeBrowser {\n readonly crypto: Pick<Crypto, \"randomUUID\">;\n readonly sessionStorage: Pick<Storage, \"getItem\" | \"setItem\">;\n readonly history: Pick<History, \"state\" | \"replaceState\">;\n readonly location: Pick<Location, \"href\">;\n readonly fetch: typeof fetch;\n}\n\n/** One attempt owns admission, the settling deadline, and the reload across target changes. */\nexport class ManagedUpgrade {\n readonly clientSessionId: RecoverySessionId;\n private readonly key: string;\n private tab: typeof TabState.Type;\n private snapshot: ManagedUpdateSnapshot = { phase: \"connecting\", recovery: [] };\n private readonly listeners = new Set<() => void>();\n private target: ExecutionSelection | undefined;\n private attempt: Promise<void> | undefined;\n private disposed = false;\n private storageAvailable = true;\n private readyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n readonly selection: ExecutionSelection,\n private readonly browser: ManagedUpgradeBrowser,\n private readonly callbacks: {\n readonly stopAdmission: () => void;\n readonly unresolved: () => number;\n readonly persist: () => readonly string[];\n readonly reload: () => void;\n readonly freshSelection: () => Promise<ExecutionSelection | undefined>;\n },\n ) {\n this.key = `ignotum.managed.tab.${selection.appId}`;\n this.tab = {\n formatVersion: 1,\n appId: selection.appId,\n clientSessionId: RecoverySessionId.make(\n `rec_${browser.crypto.randomUUID().replaceAll(\"-\", \"\").slice(0, 24)}`,\n ),\n attempts: 0,\n attemptedAt: 0,\n target: null,\n uncertainStorage: false,\n };\n try {\n const raw = browser.sessionStorage.getItem(this.key);\n if (raw !== null) {\n const decoded = Schema.decodeOption(TabStateJson)(raw);\n if (\n Option.isSome(decoded) &&\n decoded.value.appId === selection.appId &&\n (decoded.value.target === null || decoded.value.target.appId === selection.appId)\n ) {\n this.tab = decoded.value;\n } else {\n this.reportRecovery(\n \"Saved update information could not be read. Previous mutation outcomes may be unknown.\",\n );\n }\n }\n } catch {\n this.storageAvailable = false;\n }\n const history = Schema.decodeUnknownOption(Schema.Struct({ __ignotumUpdate: TabState }))(\n browser.history.state,\n );\n if (\n Option.isSome(history) &&\n history.value.__ignotumUpdate.appId === selection.appId &&\n history.value.__ignotumUpdate.attemptedAt >= this.tab.attemptedAt &&\n (history.value.__ignotumUpdate.target === null ||\n history.value.__ignotumUpdate.target.appId === selection.appId)\n )\n this.tab = history.value.__ignotumUpdate;\n if (this.tab.uncertainStorage)\n this.reportRecovery(\n \"Some previous mutation outcomes could not be saved in browser storage and remain unknown.\",\n );\n this.clientSessionId = this.tab.clientSessionId;\n this.save();\n }\n\n getSnapshot = (): ManagedUpdateSnapshot => this.snapshot;\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n private update(next: ManagedUpdateSnapshot): void {\n if (this.disposed) return;\n this.snapshot = next;\n for (const listener of this.listeners) listener();\n }\n reportRecovery(message: string): void {\n if (!this.snapshot.recovery.includes(message))\n this.update({ ...this.snapshot, recovery: [...this.snapshot.recovery, message].slice(-100) });\n }\n dismissRecovery = (): void => {\n this.tab = { ...this.tab, uncertainStorage: false };\n this.save();\n this.update({ ...this.snapshot, recovery: [] });\n };\n private save(): boolean {\n let saved = false;\n try {\n this.browser.sessionStorage.setItem(this.key, Schema.encodeSync(TabStateJson)(this.tab));\n this.storageAvailable = true;\n saved = true;\n } catch {\n this.storageAvailable = false;\n }\n try {\n const existing = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.Unknown))(\n this.browser.history.state,\n );\n this.browser.history.replaceState(\n {\n ...Option.getOrElse(existing, () => ({})),\n __ignotumUpdate: Schema.encodeSync(TabState)(this.tab),\n },\n \"\",\n );\n saved = true;\n } catch {\n /* The automatic retry budget must survive reload through at least one browser store. */\n }\n return saved;\n }\n get obsolete(): boolean {\n return this.target !== undefined || this.attempt !== undefined;\n }\n get ready(): boolean {\n return this.snapshot.phase === \"ready\" && !this.obsolete;\n }\n connecting(): void {\n if (this.readyTimer !== undefined) clearTimeout(this.readyTimer);\n if (!this.obsolete) this.update({ ...this.snapshot, phase: \"connecting\", message: undefined });\n }\n accepted(): void {\n if (this.obsolete) return;\n this.update({ ...this.snapshot, phase: \"ready\", message: undefined });\n if (this.readyTimer !== undefined) clearTimeout(this.readyTimer);\n // A repeatedly broken lazy asset must not reset the reload budget at every handshake.\n this.readyTimer = setTimeout(() => {\n this.tab = { ...this.tab, attempts: 0, attemptedAt: 0, target: null };\n this.save();\n }, 60_000);\n }\n unavailable(message = \"The app could not check for updates. Reconnect and try again.\"): void {\n if (this.readyTimer !== undefined) clearTimeout(this.readyTimer);\n if (!this.obsolete) this.update({ ...this.snapshot, phase: \"error\", message });\n }\n require(target?: ExecutionSelection): Promise<void> {\n if (this.disposed) return Promise.resolve();\n if (target !== undefined) this.target = target;\n this.callbacks.stopAdmission();\n if (this.attempt !== undefined && this.snapshot.phase !== \"error\") return this.attempt;\n if (this.readyTimer !== undefined) clearTimeout(this.readyTimer);\n this.update({\n ...this.snapshot,\n phase: \"settling\",\n message: \"Updating the app. Waiting briefly for pending changes…\",\n });\n this.attempt = this.run();\n return this.attempt;\n }\n private async run(): Promise<void> {\n const deadline = Date.now() + 2_000;\n while (!this.disposed && this.callbacks.unresolved() > 0 && Date.now() < deadline)\n await new Promise<void>((resolve) => setTimeout(resolve, 25));\n if (this.disposed) return;\n try {\n const issues = this.callbacks.persist();\n for (const issue of issues) this.reportRecovery(issue);\n if (issues.length > 0) {\n this.tab = { ...this.tab, uncertainStorage: true };\n await new Promise<void>((resolve) => setTimeout(resolve, 1_000));\n }\n const fresh = await this.callbacks.freshSelection();\n if (fresh !== undefined && fresh.appId !== this.selection.appId)\n throw new Error(\"The app address now refers to a different app.\");\n this.target = fresh ?? this.target;\n const response = await this.browser.fetch(this.browser.location.href, {\n cache: \"no-store\",\n credentials: \"same-origin\",\n headers: { accept: \"text/html\" },\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"The updated app document is temporarily unavailable.\");\n await response.body?.cancel();\n if (this.disposed) return;\n // A verified new selection starts a separate update budget.\n const attempts =\n fresh !== undefined &&\n this.tab.target !== null &&\n !sameExecutionSelection(this.tab.target, fresh)\n ? 0\n : this.tab.attempts;\n if (attempts >= 2)\n throw new Error(\n \"The app update could not load a consistent release. Try again when the connection or release is available.\",\n );\n this.tab = {\n ...this.tab,\n attempts: attempts + 1,\n attemptedAt: Date.now(),\n target: fresh ?? this.target ?? this.selection,\n };\n if (!this.save()) {\n throw new Error(\n \"Browser storage is unavailable. Pending changes may have unknown outcomes. Use Reload app to continue the update.\",\n );\n }\n this.update({ ...this.snapshot, phase: \"reloading\", message: \"Loading the updated app…\" });\n this.callbacks.reload();\n } catch (error) {\n this.update({\n ...this.snapshot,\n phase: \"error\",\n message:\n error instanceof Error ? error.message : \"The app update could not be loaded. Try again.\",\n });\n }\n }\n /** An explicit retry resets the automatic budget, while obsolete code remains fenced. */\n retry = (): void => {\n if (this.disposed) return;\n if (!this.storageAvailable) {\n this.callbacks.persist();\n this.callbacks.reload();\n return;\n }\n this.tab = { ...this.tab, attempts: 0, attemptedAt: 0 };\n this.save();\n this.attempt = undefined;\n void this.require(this.target);\n };\n async check(): Promise<boolean> {\n if (this.obsolete || this.disposed) return false;\n try {\n const fresh = await this.callbacks.freshSelection();\n if (fresh === undefined || !sameExecutionSelection(this.selection, fresh)) {\n void this.require(fresh);\n return false;\n }\n return !this.obsolete && !this.disposed;\n } catch {\n this.unavailable();\n return false;\n }\n }\n dispose(): void {\n this.disposed = true;\n if (this.readyTimer !== undefined) clearTimeout(this.readyTimer);\n this.listeners.clear();\n }\n}\n","import { RecoveryIdentity, RecoverySessionId } from \"@ignotum/contracts/platform\";\nimport { AppId } from \"@ignotum/contracts/runtime/identity\";\nimport * as Versioned from \"@ignotum/contracts/versioned\";\nimport { DateTime, Predicate, Schema } from \"effect\";\n\nexport const RecoveryJournalLimits = {\n maxEntries: 100,\n retentionMs: 24 * 60 * 60 * 1000,\n maxBytes: 64 * 1024,\n} as const;\nconst RecoveryEntry = Schema.Struct({\n identity: RecoveryIdentity,\n recordedAt: Schema.Natural,\n expiresAt: Schema.Natural,\n state: Schema.Literals([\"pending\", \"settled\", \"interrupted\", \"uncertain\"]),\n});\nexport type RecoveryJournalEntry = typeof RecoveryEntry.Type;\nconst RecoveryJournalV1 = Schema.Struct({\n formatVersion: Schema.Literal(1),\n appId: AppId,\n sessionEpoch: Schema.String,\n clientSessionId: RecoverySessionId,\n entries: Schema.Array(RecoveryEntry).check(Schema.isMaxLength(RecoveryJournalLimits.maxEntries)),\n})\n .check(\n Schema.makeFilter((record) => {\n const keys = record.entries.map((entry) => identityKey(entry.identity));\n return (\n new Set(keys).size === keys.length &&\n record.entries.every(\n (entry) =>\n entry.identity.originalSelection.appId === record.appId &&\n entry.expiresAt > entry.recordedAt &&\n entry.expiresAt - entry.recordedAt <= RecoveryJournalLimits.retentionMs,\n )\n );\n }),\n )\n .annotate({ parseOptions: { onExcessProperty: \"error\" } });\nexport const RecoveryJournalRecord = Versioned.initial(RecoveryJournalV1);\nexport type RecoveryJournalRecord = typeof RecoveryJournalRecord.Type;\nexport type RecoveryJournalIssue = \"denied\" | \"corrupt\" | \"full\" | \"expired\" | \"session-changed\";\nexport interface RecoveryJournalSnapshot {\n readonly clientSessionId: RecoverySessionId;\n readonly entries: ReadonlyArray<RecoveryJournalEntry>;\n readonly issues: ReadonlyArray<RecoveryJournalIssue>;\n}\ntype JournalStorage = Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\nexport interface RecoveryJournalOptions {\n readonly appId: AppId;\n readonly sessionEpoch: string;\n readonly clientSessionId: RecoverySessionId;\n readonly storage?: JournalStorage | (() => JournalStorage);\n readonly now?: () => number;\n}\nconst identityKey = (identity: RecoveryIdentity): string =>\n `${identity.originalSelection.dataHistoryId}/${identity.invocationId}`;\nconst bytes = (value: string): number => new TextEncoder().encode(value).byteLength;\n\n/** sessionStorage isolates tabs. A cloned tab may look up copied identities, never replay them. */\nexport class RecoveryJournal {\n readonly storageKey: string;\n private clientSessionId: RecoverySessionId;\n constructor(private readonly options: RecoveryJournalOptions) {\n this.storageKey = `ignotum:recovery:${options.appId}`;\n this.clientSessionId = options.clientSessionId;\n }\n private storage(): JournalStorage {\n const storage = this.options.storage;\n return storage === undefined\n ? globalThis.sessionStorage\n : Predicate.isFunction(storage)\n ? storage()\n : storage;\n }\n private now(): number {\n return this.options.now?.() ?? DateTime.toEpochMillis(DateTime.nowUnsafe());\n }\n private snapshot(\n entries: ReadonlyArray<RecoveryJournalEntry>,\n issues: ReadonlyArray<RecoveryJournalIssue>,\n ): RecoveryJournalSnapshot {\n return { clientSessionId: this.clientSessionId, entries, issues };\n }\n read(): RecoveryJournalSnapshot {\n let raw: string | null;\n try {\n raw = this.storage().getItem(this.storageKey);\n } catch {\n return this.snapshot([], [\"denied\"]);\n }\n if (raw === null) return this.snapshot([], []);\n if (bytes(raw) > RecoveryJournalLimits.maxBytes) return this.discard(\"full\");\n const parsed = Schema.decodeUnknownOption(Schema.fromJsonString(RecoveryJournalRecord))(raw);\n if (parsed._tag === \"None\" || parsed.value.appId !== this.options.appId)\n return this.discard(\"corrupt\");\n if (parsed.value.sessionEpoch !== this.options.sessionEpoch)\n return this.discard(\"session-changed\");\n this.clientSessionId = parsed.value.clientSessionId;\n const now = this.now();\n const entries = parsed.value.entries.filter(\n (entry) => entry.expiresAt > now && entry.recordedAt <= now,\n );\n const issues: RecoveryJournalIssue[] =\n entries.length === parsed.value.entries.length ? [] : [\"expired\"];\n return issues.length === 0 ? this.snapshot(entries, issues) : this.persist(entries, issues);\n }\n private discard(issue: RecoveryJournalIssue): RecoveryJournalSnapshot {\n try {\n this.storage().removeItem(this.storageKey);\n return this.snapshot([], [issue]);\n } catch {\n return this.snapshot([], [issue, \"denied\"]);\n }\n }\n private persist(\n entries: ReadonlyArray<RecoveryJournalEntry>,\n issues: ReadonlyArray<RecoveryJournalIssue>,\n ): RecoveryJournalSnapshot {\n const record: RecoveryJournalRecord = {\n formatVersion: 1,\n appId: this.options.appId,\n sessionEpoch: this.options.sessionEpoch,\n clientSessionId: this.clientSessionId,\n entries,\n };\n const encoded = Schema.encodeOption(Schema.fromJsonString(RecoveryJournalRecord))(record);\n if (encoded._tag === \"None\") return this.snapshot(entries, [...issues, \"corrupt\"]);\n if (bytes(encoded.value) > RecoveryJournalLimits.maxBytes)\n return this.snapshot(entries, [...issues, \"full\"]);\n try {\n this.storage().setItem(this.storageKey, encoded.value);\n return this.snapshot(entries, issues);\n } catch (error) {\n return this.snapshot(entries, [\n ...issues,\n error instanceof DOMException && error.name === \"QuotaExceededError\" ? \"full\" : \"denied\",\n ]);\n }\n }\n /** Call before abandoning the page; any issue means durable recovery is not proven. */\n write(identities: ReadonlyArray<RecoveryIdentity>): RecoveryJournalSnapshot {\n const current = this.read();\n if (current.issues.includes(\"denied\")) return current;\n const entries = new Map(current.entries.map((entry) => [identityKey(entry.identity), entry]));\n const now = this.now();\n for (const identity of identities) {\n if (identity.originalSelection.appId !== this.options.appId)\n return this.snapshot(current.entries, [...current.issues, \"corrupt\"]);\n const key = identityKey(identity);\n if (!entries.has(key))\n entries.set(key, {\n identity: {\n invocationId: identity.invocationId,\n originalSelection: identity.originalSelection,\n },\n recordedAt: now,\n expiresAt: now + RecoveryJournalLimits.retentionMs,\n state: \"pending\",\n });\n }\n if (entries.size > RecoveryJournalLimits.maxEntries)\n return this.snapshot(current.entries, [...current.issues, \"full\"]);\n return this.persist([...entries.values()], current.issues);\n }\n reconcile(\n identity: RecoveryIdentity,\n state: Exclude<RecoveryJournalEntry[\"state\"], \"pending\">,\n ): RecoveryJournalSnapshot {\n const current = this.read();\n if (current.issues.includes(\"denied\")) return current;\n return this.persist(\n current.entries.map((entry) =>\n identityKey(entry.identity) === identityKey(identity) ? { ...entry, state } : entry,\n ),\n current.issues,\n );\n }\n remove(identity: RecoveryIdentity): RecoveryJournalSnapshot {\n const current = this.read();\n if (current.issues.includes(\"denied\")) return current;\n return this.persist(\n current.entries.filter((entry) => identityKey(entry.identity) !== identityKey(identity)),\n current.issues,\n );\n }\n clear(): RecoveryJournalSnapshot {\n try {\n this.storage().removeItem(this.storageKey);\n return this.snapshot([], []);\n } catch {\n return this.snapshot([], [\"denied\"]);\n }\n }\n}\n","import { Effect, Deferred, Option, Schema } from \"effect\";\nimport {\n ManagedClientMessage,\n ManagedServerMessage,\n ManagedSelectionResponse,\n ManagedUpgradeRequired,\n managedSelectionPath,\n managedSyncPath,\n} from \"@ignotum/contracts/managed-sync\";\nimport {\n sameExecutionSelection,\n type ExecutionSelection,\n type RecoveryIdentity,\n type RecoverySessionId,\n} from \"@ignotum/contracts/platform\";\nimport { InvocationId, SubscriptionId } from \"@ignotum/contracts/runtime/sync\";\nimport type { RuntimeMutationOutcome } from \"@ignotum/contracts/runtime/hosted\";\nimport { encodeTransportObject } from \"@ignotum/contracts/runtime/sync\";\nimport type { Result, ErrorValue } from \"@ignotum/contracts/runtime/result\";\nimport {\n ClientInfrastructureError,\n ConnectionUnavailable,\n InvalidMutationArguments,\n PlatformUpgrading,\n ServerError,\n} from \"./errors.js\";\nimport { ManagedUpgrade } from \"./managed-upgrade.js\";\nimport { RecoveryJournal, type RecoveryJournalIssue } from \"./recovery-journal.js\";\nimport { RecoveryJournalLimits } from \"./recovery-journal.js\";\nimport { prepareMutationArguments, uploadPreparedFiles } from \"./files.js\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport type { BrowserSession } from \"./id.js\";\nimport type { SyncClientService, syncClientInternals } from \"./sync.js\";\n\ninterface PendingMutation {\n readonly identity: RecoveryIdentity;\n readonly sessionEpoch: string;\n readonly done: Deferred.Deferred<Result<unknown, ErrorValue>, ClientInfrastructureError>;\n readonly prepared: Deferred.Deferred<\n Extract<ManagedServerMessage, { type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >;\n readonly preparation?: Extract<ManagedClientMessage, { type: \"Prepare\" }>;\n}\nconst issueMessage = (issue: RecoveryJournalIssue): string => {\n switch (issue) {\n case \"denied\":\n return \"Browser storage is unavailable. Some previous mutation outcomes may be unknown.\";\n case \"full\":\n return \"Browser recovery storage is full. Some mutation outcomes could not be saved.\";\n case \"corrupt\":\n return \"Saved mutation information could not be read. Its outcomes remain unknown.\";\n case \"expired\":\n return \"Some saved mutation information expired. Its outcomes remain unknown.\";\n case \"session-changed\":\n return \"The browser session changed. Previous mutation outcomes cannot be retrieved in this session.\";\n }\n};\n\n/** The managed connection is mounted by bootstrap, independently of query observers. */\nexport class ManagedBrowserClient {\n readonly upgrade: ManagedUpgrade;\n private readonly queries;\n private socket: WebSocket | undefined;\n private acceptedSocket: WebSocket | undefined;\n private session: BrowserSession[\"Service\"] | undefined;\n private ids: IdGenerator[\"Service\"] | undefined;\n private sessionEpoch: string | undefined;\n private sessionViewRevision: number | undefined;\n private unsubscribeSession: (() => void) | undefined;\n private sessionDeadline = 0;\n private clientSessionId: RecoverySessionId;\n private journal: RecoveryJournal | undefined;\n private readonly pending = new Map<InvocationId, PendingMutation>();\n private readonly recovery = new Map<string, RecoveryIdentity>();\n private readonly recoveryDeadlines = new Map<string, number>();\n private readonly recoveryTimeouts = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly recoveryTimers = new Set<ReturnType<typeof setTimeout>>();\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n private handshakeTimer: ReturnType<typeof setTimeout> | undefined;\n private sessionTimer: ReturnType<typeof setTimeout> | undefined;\n private heartbeat: ReturnType<typeof setInterval> | undefined;\n private reconnectDelay = 250;\n private disposed = false;\n private readonly readyWaiters = new Set<(ready: boolean) => void>();\n private suspended = true;\n private lastActivity = Date.now();\n private validation: Promise<boolean> | undefined;\n private connectionGeneration = 0;\n\n constructor(\n readonly selection: ExecutionSelection,\n private readonly browser: Window,\n private readonly helpers: Pick<typeof syncClientInternals, \"makeQueryCache\" | \"resultFromWire\">,\n callbacks: { readonly stopAdmission: () => void; readonly reload: () => void },\n ) {\n this.upgrade = new ManagedUpgrade(selection, browser, {\n stopAdmission: () => {\n this.suspended = true;\n for (const pending of this.pending.values()) {\n if (pending.preparation !== undefined)\n Deferred.doneUnsafe(\n pending.prepared,\n Effect.fail(\n PlatformUpgrading.make({\n message:\n \"The app is updating. This upload was interrupted before its mutation ran.\",\n }),\n ),\n );\n }\n callbacks.stopAdmission();\n },\n unresolved: () => this.pending.size,\n persist: () => this.persistPending(),\n reload: callbacks.reload,\n freshSelection: this.freshSelection,\n });\n this.clientSessionId = this.upgrade.clientSessionId;\n this.queries = helpers.makeQueryCache(\n Effect.suspend(() =>\n this.ids === undefined\n ? Effect.die(\"The client identity service is not ready.\")\n : this.ids.generate(SubscriptionId),\n ),\n (message) =>\n Effect.sync(() => {\n if (this.canSend()) this.send(message);\n }),\n );\n }\n attachSession(session: BrowserSession[\"Service\"], ids: IdGenerator[\"Service\"]): void {\n if (this.disposed) return;\n this.unsubscribeSession?.();\n this.session = session;\n this.ids = ids;\n this.unsubscribeSession = session.subscribe(() => {\n const current = session.current();\n if (\n current === undefined ||\n (this.sessionEpoch !== undefined &&\n (current.sessionEpoch !== this.sessionEpoch ||\n current.viewRevision !== this.sessionViewRevision))\n ) {\n this.queries.invalidatePrivate();\n this.suspended = true;\n this.acceptedSocket = undefined;\n this.socket?.close();\n }\n });\n }\n whenReady(): Promise<boolean> {\n if (this.upgrade.ready) return Promise.resolve(true);\n if (this.upgrade.obsolete || this.disposed) return Promise.resolve(false);\n return new Promise((resolve) => {\n const finish = (ready: boolean) => {\n unsubscribe();\n this.readyWaiters.delete(finish);\n resolve(ready);\n };\n const unsubscribe = this.upgrade.subscribe(() => {\n if (this.upgrade.ready || this.upgrade.obsolete || this.disposed)\n finish(this.upgrade.ready);\n });\n this.readyWaiters.add(finish);\n });\n }\n retry = (): void => {\n if (this.upgrade.obsolete) this.upgrade.retry();\n else this.resume();\n };\n recoverLoad = async (): Promise<void> => {\n await this.upgrade.check();\n };\n private freshSelection = async (): Promise<ExecutionSelection | undefined> => {\n const response = await this.browser.fetch(managedSelectionPath, {\n cache: \"no-store\",\n credentials: \"same-origin\",\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(\"The current app selection is unavailable.\");\n const current = Schema.decodeUnknownOption(ManagedSelectionResponse)(await response.json());\n // A newer protocol may change selection's encoding. It can require reload without granting\n // old code admission or depending on that code decoding the new protocol.\n return Option.getOrUndefined(current)?.selection;\n };\n start(): void {\n if (this.disposed) return;\n this.browser.addEventListener(\"pageshow\", this.resume);\n this.browser.addEventListener(\"pagehide\", this.hide);\n this.browser.addEventListener(\"online\", this.resume);\n this.browser.addEventListener(\"offline\", this.offline);\n this.browser.addEventListener(\"focus\", this.resume);\n this.browser.document.addEventListener(\"visibilitychange\", this.visibility);\n this.heartbeat = setInterval(() => {\n const now = Date.now();\n if (now - this.lastActivity > 15_000) this.resume();\n this.lastActivity = now;\n }, 5_000);\n this.connect();\n }\n private canSend(): boolean {\n return (\n !this.disposed &&\n !this.suspended &&\n !this.upgrade.obsolete &&\n this.acceptedSocket !== undefined &&\n this.acceptedSocket === this.socket &&\n this.socket.readyState === 1 &&\n Date.now() < this.sessionDeadline\n );\n }\n private send(message: ManagedClientMessage): void {\n if (this.socket?.readyState !== 1) return;\n this.socket.send(Schema.encodeSync(Schema.fromJsonString(ManagedClientMessage))(message));\n }\n private connect(): void {\n if (this.disposed || this.upgrade.obsolete) return;\n this.suspended = true;\n this.upgrade.connecting();\n this.acceptedSocket = undefined;\n this.recovery.clear();\n for (const timer of this.recoveryTimers) clearTimeout(timer);\n this.recoveryTimers.clear();\n this.recoveryTimeouts.clear();\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n if (this.handshakeTimer !== undefined) clearTimeout(this.handshakeTimer);\n this.socket?.close();\n this.socket = undefined;\n const generation = ++this.connectionGeneration;\n if (this.session === undefined) return;\n void Effect.runPromise(this.session.bootstrap).then(\n () => {\n if (this.disposed || this.upgrade.obsolete || generation !== this.connectionGeneration)\n return;\n this.openSocket();\n },\n () => {\n if (this.disposed || this.upgrade.obsolete || generation !== this.connectionGeneration)\n return;\n this.upgrade.unavailable(\"The browser session could not be verified. Reconnecting…\");\n this.reconnectTimer = setTimeout(() => this.connect(), 1_000);\n },\n );\n }\n private openSocket(): void {\n const url = new URL(managedSyncPath, this.browser.location.href);\n url.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n const socket = new WebSocket(url);\n this.socket = socket;\n socket.onopen = () => {\n if (this.socket !== socket || this.disposed) return;\n this.send({\n type: \"Connect\",\n protocolVersion: 1,\n selection: this.selection,\n clientSessionId: this.clientSessionId,\n });\n };\n this.handshakeTimer = setTimeout(() => {\n if (this.socket === socket && this.acceptedSocket !== socket) socket.close();\n }, 10_000);\n socket.onmessage = (event: MessageEvent<string>) => {\n if (this.socket !== socket || this.disposed) return;\n const stable = Schema.decodeUnknownOption(Schema.fromJsonString(ManagedUpgradeRequired))(\n event.data,\n );\n if (Option.isSome(stable)) {\n void this.upgrade.require(stable.value.selection);\n return;\n }\n const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(ManagedServerMessage))(\n event.data,\n );\n if (Option.isNone(decoded)) {\n void this.upgrade.require();\n return;\n }\n this.message(socket, decoded.value);\n };\n socket.onerror = () => socket.close();\n socket.onclose = (event) => {\n if (this.socket !== socket || this.disposed) return;\n if (event.code === 1012 || event.code === 1008) this.queries.invalidatePrivate();\n this.acceptedSocket = undefined;\n this.suspended = true;\n if (this.handshakeTimer !== undefined) clearTimeout(this.handshakeTimer);\n if (this.upgrade.obsolete) return;\n this.upgrade.unavailable(\"The connection was lost. Checking for updates before resuming…\");\n this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectDelay);\n this.reconnectDelay = Math.min(this.reconnectDelay * 2, 5_000);\n };\n }\n private message(socket: WebSocket, message: ManagedServerMessage): void {\n if (message.type === \"UpgradeRequired\") {\n void this.upgrade.require(message.selection);\n return;\n }\n if (message.type === \"Handshake\") {\n if (!sameExecutionSelection(this.selection, message.selection)) {\n void this.upgrade.require(message.selection);\n return;\n }\n if (this.upgrade.obsolete) return;\n if (this.handshakeTimer !== undefined) clearTimeout(this.handshakeTimer);\n const previousEpoch = this.sessionEpoch;\n if (\n previousEpoch !== undefined &&\n (previousEpoch !== message.session.sessionEpoch ||\n this.sessionViewRevision !== message.session.viewRevision)\n )\n this.queries.invalidatePrivate();\n this.sessionEpoch = message.session.sessionEpoch;\n this.sessionViewRevision = message.session.viewRevision;\n this.sessionDeadline =\n Date.now() + Math.max(0, message.session.validUntil - message.serverTime);\n if (this.sessionTimer !== undefined) clearTimeout(this.sessionTimer);\n this.sessionTimer = setTimeout(\n () => {\n this.session?.suspend();\n this.queries.invalidatePrivate();\n this.resume();\n },\n Math.min(2_147_483_647, Math.max(0, this.sessionDeadline - Date.now())),\n );\n this.session?.accept(message.session, message.serverTime);\n this.journal = new RecoveryJournal({\n appId: this.selection.appId,\n sessionEpoch: message.session.sessionEpoch,\n clientSessionId: this.clientSessionId,\n storage: () => this.browser.sessionStorage,\n });\n const saved = this.journal.read();\n for (const issue of saved.issues) this.upgrade.reportRecovery(issueMessage(issue));\n if (saved.clientSessionId !== this.clientSessionId) {\n this.clientSessionId = saved.clientSessionId;\n this.connect();\n return;\n }\n if (previousEpoch !== undefined && previousEpoch !== this.sessionEpoch) {\n for (const [id, pending] of this.pending) {\n Deferred.doneUnsafe(\n pending.prepared,\n Effect.fail(\n ConnectionUnavailable.make({\n message: \"The session changed before file preparation completed.\",\n }),\n ),\n );\n this.upgrade.reportRecovery(\n `Mutation ${id} has an unknown outcome because the session changed.`,\n );\n Deferred.doneUnsafe(\n pending.done,\n Effect.fail(\n ConnectionUnavailable.make({\n message: \"The session changed. This mutation may already have completed.\",\n }),\n ),\n );\n }\n this.pending.clear();\n }\n this.acceptedSocket = socket;\n this.suspended = false;\n this.reconnectDelay = 250;\n this.upgrade.accepted();\n for (const entry of this.queries.entries())\n this.send({\n type: \"Subscribe\",\n id: entry.subscriptionId,\n function: entry.function,\n args: entry.args,\n });\n for (const entry of saved.entries) {\n if (entry.state === \"pending\") {\n if (!this.pending.has(entry.identity.invocationId)) this.recover(entry.identity);\n } else {\n this.upgrade.reportRecovery(`Mutation ${entry.identity.invocationId}: ${entry.state}.`);\n this.journal.remove(entry.identity);\n }\n }\n for (const pending of this.pending.values()) {\n if (pending.preparation !== undefined) this.send(pending.preparation);\n else this.recover(pending.identity);\n }\n this.journal.write([]);\n return;\n }\n if (this.acceptedSocket !== socket) {\n socket.close();\n return;\n }\n switch (message.type) {\n case \"Preparation\": {\n if (!this.canSend()) return;\n const pending = this.pending.get(message.invocationId);\n if (pending?.preparation !== undefined)\n Deferred.doneUnsafe(pending.prepared, Effect.succeed(message.uploads));\n return;\n }\n case \"QuerySnapshot\": {\n if (!this.canSend()) return;\n if (!sameExecutionSelection(this.selection, message.selection)) {\n void this.upgrade.require(message.selection);\n return;\n }\n const result = Effect.runSync(\n this.helpers\n .resultFromWire(message.result.result, message.files)\n .pipe(Effect.catchTags({ InvalidServerMessage: (error) => Effect.succeed(error) })),\n );\n this.queries.setResult(message.id, result, message.result.observedRevision);\n return;\n }\n case \"MutationOutcome\": {\n if (\n !sameExecutionSelection(message.identity.originalSelection, this.selection) &&\n !this.recovery.has(message.id)\n )\n return;\n this.outcome(message.id, message.identity, message.outcome);\n return;\n }\n case \"Error\": {\n if (message.code === \"PlatformUpgrading\") {\n void this.upgrade.require();\n return;\n }\n if (message.code === \"SessionExpired\") {\n this.suspended = true;\n this.session?.suspend();\n this.queries.invalidatePrivate();\n socket.close();\n return;\n }\n if (\n message.code === \"InvalidArguments\" ||\n message.code === \"InvocationIdConflict\" ||\n message.code === \"ResourceLimitExceeded\"\n ) {\n for (const [invocationId, pending] of this.pending) {\n if (invocationId !== message.id) continue;\n const failure = Effect.fail(\n ServerError.make({ code: message.code, message: message.message }),\n );\n Deferred.doneUnsafe(pending.prepared, failure);\n Deferred.doneUnsafe(pending.done, failure);\n this.pending.delete(invocationId);\n this.journal?.remove(pending.identity);\n return;\n }\n for (const query of this.queries.entries()) {\n if (query.subscriptionId !== message.id) continue;\n this.queries.setResult(\n query.subscriptionId,\n ServerError.make({ code: message.code, message: message.message }),\n );\n return;\n }\n return;\n }\n this.upgrade.unavailable(message.message);\n socket.close();\n return;\n }\n }\n }\n private recover(identity: RecoveryIdentity): void {\n if (!this.canSend()) return;\n const id = `recovery:${identity.originalSelection.dataHistoryId}:${identity.invocationId}`;\n if (this.recovery.has(id)) return;\n this.recovery.set(id, identity);\n const deadline = this.recoveryDeadlines.get(id) ?? Date.now() + 30_000;\n this.recoveryDeadlines.set(id, deadline);\n if (Date.now() >= deadline) {\n this.outcome(id, identity, { type: \"Uncertain\" });\n return;\n }\n this.send({ type: \"RecoverMutation\", id, identity });\n const timer = setTimeout(() => {\n this.recoveryTimers.delete(timer);\n this.recoveryTimeouts.delete(id);\n if (!this.recovery.has(id)) return;\n this.recovery.delete(id);\n this.recover(identity);\n }, 5_000);\n this.recoveryTimers.add(timer);\n this.recoveryTimeouts.set(id, timer);\n }\n private outcome(id: string, identity: RecoveryIdentity, outcome: RuntimeMutationOutcome): void {\n const recovery = this.recovery.get(id);\n const pending = this.pending.get(identity.invocationId);\n if (recovery === undefined && pending === undefined) return;\n const expected = recovery ?? pending!.identity;\n if (\n expected.invocationId !== identity.invocationId ||\n !sameExecutionSelection(expected.originalSelection, identity.originalSelection)\n )\n return;\n this.recovery.delete(id);\n const timeout = this.recoveryTimeouts.get(id);\n if (timeout !== undefined) {\n clearTimeout(timeout);\n this.recoveryTimers.delete(timeout);\n this.recoveryTimeouts.delete(id);\n }\n if (outcome.type === \"Pending\") {\n const timer = setTimeout(() => {\n this.recoveryTimers.delete(timer);\n this.recover(identity);\n }, 1_000);\n this.recoveryTimers.add(timer);\n return;\n }\n const recoveryId = `recovery:${identity.originalSelection.dataHistoryId}:${identity.invocationId}`;\n this.recovery.delete(recoveryId);\n this.recoveryDeadlines.delete(recoveryId);\n if (pending !== undefined) {\n this.pending.delete(identity.invocationId);\n if (outcome.type === \"Settled\")\n Deferred.doneUnsafe(pending.done, this.helpers.resultFromWire(outcome.result.result));\n else\n Deferred.doneUnsafe(\n pending.done,\n Effect.fail(\n ConnectionUnavailable.make({\n message:\n outcome.type === \"Interrupted\"\n ? \"The mutation was interrupted before it committed.\"\n : \"The mutation outcome is unknown. Check the app before trying it again.\",\n }),\n ),\n );\n }\n const state =\n outcome.type === \"Settled\"\n ? \"settled\"\n : outcome.type === \"Interrupted\"\n ? \"interrupted\"\n : \"uncertain\";\n if (recovery !== undefined || outcome.type !== \"Settled\") {\n const detail =\n outcome.type === \"Settled\"\n ? outcome.result.result.type === \"Success\"\n ? \"completed\"\n : \"completed with an error\"\n : state;\n this.upgrade.reportRecovery(`Mutation ${identity.invocationId}: ${detail}.`);\n }\n for (const issue of this.journal?.reconcile(identity, state).issues ?? [])\n this.upgrade.reportRecovery(issueMessage(issue));\n for (const issue of this.journal?.remove(identity).issues ?? [])\n this.upgrade.reportRecovery(issueMessage(issue));\n }\n private persistPending(): readonly string[] {\n if (this.pending.size === 0) return [];\n if (this.journal === undefined)\n return [\"Pending mutation outcomes could not be saved and remain unknown.\"];\n return this.journal\n .write([...this.pending.values()].map((entry) => entry.identity))\n .issues.map(issueMessage);\n }\n readonly observe: SyncClientService[\"observe\"] = Effect.fn(\"ManagedBrowserClient.observe\")(\n (address, args) => this.queries.observe(address, args),\n );\n readonly mutate: SyncClientService[\"mutate\"] = Effect.fn(\"ManagedBrowserClient.mutate\")(\n function* (this: ManagedBrowserClient, address, args) {\n if (this.upgrade.obsolete)\n return yield* PlatformUpgrading.make({\n message: \"The platform is updating. Try again after the app reloads.\",\n });\n const valid = yield* Effect.promise(() => this.validate());\n if (this.upgrade.obsolete)\n return yield* PlatformUpgrading.make({\n message: \"The platform is updating. Try again after the app reloads.\",\n });\n if (!valid || !this.canSend() || this.sessionEpoch === undefined)\n return yield* ConnectionUnavailable.make({\n message: \"The app must reconnect and verify its selection before accepting a mutation.\",\n });\n if (this.pending.size >= RecoveryJournalLimits.maxEntries)\n return yield* ConnectionUnavailable.make({\n message:\n \"Too many mutations are waiting for outcomes. Wait for them to settle before trying again.\",\n });\n const ids = this.ids;\n if (ids === undefined)\n return yield* ConnectionUnavailable.make({ message: \"The client is not ready.\" });\n const prepared = yield* prepareMutationArguments(args).pipe(\n Effect.provideService(IdGenerator, ids),\n Effect.mapError((cause) =>\n InvalidMutationArguments.make({\n cause,\n function: address,\n message: \"The mutation arguments cannot be sent.\",\n }),\n ),\n );\n const encoded = yield* Effect.try({\n try: () => encodeTransportObject(prepared.value),\n catch: (cause) =>\n InvalidMutationArguments.make({\n cause,\n function: address,\n message: \"The mutation arguments cannot be sent.\",\n }),\n });\n if (!this.canSend())\n return yield* PlatformUpgrading.make({\n message: \"The app is reconnecting or updating. Try again when it is ready.\",\n });\n const invocationId = yield* ids.generate(InvocationId);\n const done = yield* Deferred.make<Result<unknown, ErrorValue>, ClientInfrastructureError>();\n const identity: RecoveryIdentity = { invocationId, originalSelection: this.selection };\n const uploadsReady = yield* Deferred.make<\n Extract<ManagedServerMessage, { type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >();\n const preparation =\n prepared.fileIds.length === 0\n ? undefined\n : {\n type: \"Prepare\" as const,\n invocationId,\n function: address,\n args: encoded,\n files: prepared.fileIds,\n };\n this.pending.set(invocationId, {\n identity,\n sessionEpoch: this.sessionEpoch,\n done,\n prepared: uploadsReady,\n preparation,\n });\n for (const issue of this.persistPending()) this.upgrade.reportRecovery(issue);\n if (preparation !== undefined) {\n this.send(preparation);\n yield* Effect.gen({ self: this }, function* () {\n const uploads = yield* Deferred.await(uploadsReady);\n yield* uploadPreparedFiles(prepared.nativeFiles, uploads, address);\n if (!this.canSend())\n return yield* PlatformUpgrading.make({\n message: \"The app is reconnecting or updating. Try again when it is ready.\",\n });\n }).pipe(\n Effect.tapError(() =>\n Effect.sync(() => {\n this.pending.delete(invocationId);\n this.journal?.remove(identity);\n }),\n ),\n );\n const pending = this.pending.get(invocationId);\n if (pending === undefined) return yield* Deferred.await(done);\n this.pending.set(invocationId, { ...pending, preparation: undefined });\n }\n this.send({ type: \"Invoke\", invocationId, function: address, args: encoded });\n const timer = setTimeout(() => {\n this.recoveryTimers.delete(timer);\n if (this.pending.has(invocationId)) this.recover(identity);\n }, 5_000);\n this.recoveryTimers.add(timer);\n return yield* Deferred.await(done);\n },\n ).bind(this);\n validate = (): Promise<boolean> => {\n if (this.upgrade.obsolete || this.disposed) return Promise.resolve(false);\n if (this.validation !== undefined) return this.validation;\n this.validation = this.upgrade\n .check()\n .then((current) => {\n const ready = current && this.canSend();\n if (ready && this.upgrade.getSnapshot().phase !== \"ready\") this.upgrade.accepted();\n return ready;\n })\n .finally(() => {\n this.validation = undefined;\n });\n return this.validation;\n };\n private resume = (): void => {\n if (this.disposed || this.upgrade.obsolete) return;\n this.suspended = true;\n this.acceptedSocket = undefined;\n this.recovery.clear();\n this.queries.invalidate(undefined);\n this.connect();\n };\n private offline = (): void => {\n this.suspended = true;\n this.acceptedSocket = undefined;\n this.upgrade.unavailable(\n \"The app is offline. Reconnect to check for updates and mutation outcomes.\",\n );\n this.socket?.close();\n };\n private hide = (): void => {\n for (const issue of this.persistPending()) this.upgrade.reportRecovery(issue);\n this.suspended = true;\n this.acceptedSocket = undefined;\n this.socket?.close();\n };\n private visibility = (): void => {\n if (this.browser.document.visibilityState === \"visible\") this.resume();\n else this.hide();\n };\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const finish of this.readyWaiters) finish(false);\n this.unsubscribeSession?.();\n this.persistPending();\n this.socket?.close();\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n if (this.handshakeTimer !== undefined) clearTimeout(this.handshakeTimer);\n if (this.sessionTimer !== undefined) clearTimeout(this.sessionTimer);\n if (this.heartbeat !== undefined) clearInterval(this.heartbeat);\n for (const timer of this.recoveryTimers) clearTimeout(timer);\n this.browser.removeEventListener(\"pageshow\", this.resume);\n this.browser.removeEventListener(\"pagehide\", this.hide);\n this.browser.removeEventListener(\"online\", this.resume);\n this.browser.removeEventListener(\"offline\", this.offline);\n this.browser.removeEventListener(\"focus\", this.resume);\n this.browser.document.removeEventListener(\"visibilitychange\", this.visibility);\n this.upgrade.dispose();\n }\n}\n","import { BrowserSession } from \"./id.js\";\nimport { ManagedBrowserClient } from \"./managed-client.js\";\nimport type { ExecutionSelection } from \"@ignotum/contracts/platform\";\nimport { Context, Effect, Layer, ManagedRuntime, Schema } from \"effect\";\n\nimport { encodeCanonicalJson } from \"@ignotum/contracts/json\";\nimport { type AppStateRevision } from \"@ignotum/contracts/runtime/hosted\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport type { ManagedClientMessage, ManagedServerMessage } from \"@ignotum/contracts/managed-sync\";\n\nimport type {\n ErrorValue,\n QueryResult,\n Result as IgnotumResult,\n} from \"@ignotum/contracts/runtime/result\";\nimport { failureFromWire, pending, Result } from \"@ignotum/contracts/runtime/result\";\nimport {\n SubscriptionId,\n decodeTransportValue,\n type FunctionAddress,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport {\n ClientInfrastructureError,\n ConnectionUnavailable,\n InvalidServerMessage,\n clientErrorReporterLayer,\n} from \"./errors.js\";\nimport { applyFileGrants } from \"./files.js\";\n\ntype Listener = () => void;\n\ninterface QueryEntry {\n readonly args: Schema.Json;\n readonly function: FunctionAddress;\n readonly listeners: Set<Listener>;\n readonly subscriptionId: SubscriptionId;\n generation: number;\n dependsOnId?: boolean;\n revision: AppStateRevision | undefined;\n references: number;\n result: QueryResult<unknown, ErrorValue> | ClientInfrastructureError;\n}\n\nexport interface QueryObserver {\n readonly getSnapshot: () => QueryResult<unknown, ErrorValue> | ClientInfrastructureError;\n readonly release: Effect.Effect<void>;\n readonly subscribe: (listener: Listener) => () => void;\n}\n\ntype QueryLifecycleMessage = Extract<\n ManagedClientMessage,\n { readonly type: \"Subscribe\" | \"Unsubscribe\" }\n>;\n\ninterface QueryCache {\n readonly invalidate: (ids?: ReadonlyArray<SubscriptionId>) => void;\n readonly invalidatePrivate: () => void;\n readonly entries: () => Iterable<QueryEntry>;\n readonly getById: (id: SubscriptionId) => QueryEntry | undefined;\n readonly setResult: (\n id: SubscriptionId,\n result: QueryResult<unknown, ErrorValue> | ClientInfrastructureError,\n revision?: AppStateRevision,\n ) => void;\n readonly observe: (\n functionAddress: FunctionAddress,\n args: Schema.Json,\n ) => Effect.Effect<QueryObserver>;\n}\n\nconst queryKey = (functionAddress: FunctionAddress, args: Schema.Json): string =>\n encodeCanonicalJson([functionAddress, args]);\n\nconst subscribeMessage = (entry: QueryEntry): QueryLifecycleMessage => ({\n type: \"Subscribe\",\n id: entry.subscriptionId,\n function: entry.function,\n args: entry.args,\n});\n\nconst makeQueryCache = (\n allocateId: Effect.Effect<SubscriptionId>,\n sendLifecycleMessage: (message: QueryLifecycleMessage) => Effect.Effect<void>,\n) => {\n const queries = new Map<string, QueryEntry>();\n const queriesById = new Map<SubscriptionId, QueryEntry>();\n\n const observe = Effect.fn(\"SyncClient.QueryCache.observe\")(function* (\n functionAddress: FunctionAddress,\n args: Schema.Json,\n ) {\n const key = queryKey(functionAddress, args);\n let entry = queries.get(key);\n\n if (entry === undefined) {\n const created: QueryEntry = {\n args,\n function: functionAddress,\n generation: 0,\n listeners: new Set(),\n revision: undefined,\n references: 0,\n result: pending(),\n subscriptionId: yield* allocateId,\n };\n queries.set(key, created);\n queriesById.set(created.subscriptionId, created);\n yield* sendLifecycleMessage(subscribeMessage(created));\n entry = created;\n }\n\n const observed = entry;\n observed.references += 1;\n observed.generation += 1;\n let released = false;\n return {\n getSnapshot: () => observed.result,\n subscribe: (listener: Listener) => {\n observed.listeners.add(listener);\n return () => observed.listeners.delete(listener);\n },\n release: Effect.gen(function* () {\n if (released) return;\n released = true;\n observed.references -= 1;\n if (observed.references !== 0) return;\n const generation = ++observed.generation;\n\n // Preact and HMR may release and reacquire an observer during one render handoff.\n // Keep the server subscription alive long enough for that handoff to reuse it.\n yield* Effect.sleep(\"25 millis\");\n if (\n observed.references !== 0 ||\n observed.generation !== generation ||\n queries.get(key) !== observed\n ) {\n return;\n }\n\n queries.delete(key);\n queriesById.delete(observed.subscriptionId);\n yield* sendLifecycleMessage({\n type: \"Unsubscribe\",\n id: observed.subscriptionId,\n });\n }),\n } satisfies QueryObserver;\n });\n\n const clear = (entry: QueryEntry) => {\n entry.result = pending();\n entry.revision = undefined;\n for (const listener of entry.listeners) listener();\n };\n return {\n invalidate: (ids) => {\n for (const entry of queries.values())\n if (ids === undefined || ids.includes(entry.subscriptionId)) clear(entry);\n },\n invalidatePrivate: () => {\n for (const entry of queries.values()) if (entry.dependsOnId !== false) clear(entry);\n },\n entries: () => queries.values(),\n getById: (id: SubscriptionId) => queriesById.get(id),\n observe,\n setResult: (id, result, revision?: AppStateRevision) => {\n const entry = queriesById.get(id);\n if (entry === undefined) return;\n if (revision !== undefined) {\n if (entry.revision !== undefined && revision < entry.revision) return;\n entry.revision = revision;\n }\n entry.result = result;\n for (const listener of entry.listeners) {\n listener();\n }\n },\n } satisfies QueryCache;\n};\n\ntype SnapshotFiles = NonNullable<\n Extract<ManagedServerMessage, { readonly type: \"QuerySnapshot\" }>[\"files\"]\n>;\n\nconst resultFromWire = Effect.fn(\"SyncClient.resultFromWire\")(\n (wire: WireResult, files: SnapshotFiles = []) =>\n Effect.try({\n try: () =>\n wire.type === \"Success\"\n ? Result.succeed(\n wire.value === undefined\n ? undefined\n : applyFileGrants(decodeTransportValue(wire.value, wire.dates ?? []), files),\n )\n : failureFromWire(wire.error, wire.dates),\n catch: (cause) =>\n InvalidServerMessage.make({\n cause,\n message: \"The server returned an invalid function result.\",\n }),\n }),\n);\n\nexport const syncClientInternals = {\n makeQueryCache,\n queryIdentity: queryKey,\n resultFromWire,\n};\n\nexport interface SyncClientService {\n readonly mutate: (\n functionAddress: FunctionAddress,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Generated reference argument types are deliberately erased at the client transport boundary.\n args: unknown,\n ) => Effect.Effect<IgnotumResult<unknown, ErrorValue>, ClientInfrastructureError>;\n readonly observe: (\n functionAddress: FunctionAddress,\n args: Schema.Json,\n ) => Effect.Effect<QueryObserver, ClientInfrastructureError>;\n}\n\nexport class SyncClient extends Context.Service<SyncClient, SyncClientService>()(\n \"ignotum/client/sync/SyncClient\",\n) {}\n\nconst makeUnmountedSyncRuntime = () =>\n ManagedRuntime.make(\n Layer.succeed(SyncClient)({\n observe: () =>\n Effect.fail(ConnectionUnavailable.make({ message: \"The application has not mounted.\" })),\n mutate: () =>\n Effect.fail(ConnectionUnavailable.make({ message: \"The application has not mounted.\" })),\n }).pipe(\n Layer.provideMerge(BrowserSession.layer),\n Layer.provideMerge(clientErrorReporterLayer),\n Layer.provideMerge(IdGenerator.layer),\n ),\n );\nexport let syncRuntime = makeUnmountedSyncRuntime();\n\nexport const mountManagedSync = (\n selection: ExecutionSelection,\n browser: Window,\n callbacks: { readonly stopAdmission: () => void; readonly reload: () => void },\n) => {\n const client = new ManagedBrowserClient(selection, browser, syncClientInternals, callbacks);\n const previous = syncRuntime;\n void previous.dispose();\n syncRuntime = ManagedRuntime.make(\n Layer.effect(\n SyncClient,\n Effect.gen(function* () {\n client.attachSession(yield* BrowserSession, yield* IdGenerator);\n return SyncClient.of({ observe: client.observe, mutate: client.mutate });\n }),\n ).pipe(\n Layer.provideMerge(BrowserSession.layer),\n Layer.provideMerge(clientErrorReporterLayer),\n Layer.provideMerge(IdGenerator.layer),\n ),\n );\n const runtime = syncRuntime;\n void runtime.runPromise(SyncClient).then(\n () => client.start(),\n () => client.dispose(),\n );\n return {\n client,\n dispose: () => {\n client.dispose();\n void runtime.dispose();\n if (syncRuntime === runtime) syncRuntime = makeUnmountedSyncRuntime();\n },\n };\n};\n\n// SAFETY: Vite adds this optional property to browser development modules.\nconst hot = (\n import.meta as ImportMeta & {\n readonly hot?: { readonly dispose: (cleanup: () => void) => void };\n }\n).hot;\nif (hot !== undefined) {\n hot.dispose(() => void syncRuntime.dispose());\n}\n","import { Effect, Schema } from \"effect\";\nimport { LayoutDefinition, RouteDefinition, appDefinitionLimits } from \"@ignotum/contracts/app-definition\";\n//#region src/routing/pattern.ts\nvar RoutingDefinitionError = class extends Schema.TaggedError()(\"RoutingDefinitionError\", {\n\tmessage: Schema.String,\n\tpattern: Schema.optional(Schema.String)\n}) {};\nconst reservedIdentifiers = /* @__PURE__ */ new Set([\n\t\"await\",\n\t\"break\",\n\t\"case\",\n\t\"catch\",\n\t\"class\",\n\t\"const\",\n\t\"continue\",\n\t\"debugger\",\n\t\"default\",\n\t\"delete\",\n\t\"do\",\n\t\"else\",\n\t\"enum\",\n\t\"export\",\n\t\"extends\",\n\t\"false\",\n\t\"finally\",\n\t\"for\",\n\t\"function\",\n\t\"if\",\n\t\"implements\",\n\t\"import\",\n\t\"in\",\n\t\"instanceof\",\n\t\"interface\",\n\t\"let\",\n\t\"new\",\n\t\"null\",\n\t\"package\",\n\t\"private\",\n\t\"protected\",\n\t\"public\",\n\t\"return\",\n\t\"static\",\n\t\"super\",\n\t\"switch\",\n\t\"this\",\n\t\"throw\",\n\t\"true\",\n\t\"try\",\n\t\"typeof\",\n\t\"var\",\n\t\"void\",\n\t\"while\",\n\t\"with\",\n\t\"yield\"\n]);\nconst ParameterName = Schema.String.check(Schema.isPattern(/^[$_\\p{ID_Start}][$\\u200C\\u200D\\p{ID_Continue}]*$/u), Schema.makeFilter((name) => !reservedIdentifiers.has(name) || \"Parameter names must be TypeScript identifiers\"));\nconst CanonicalPattern = RouteDefinition.fields.pattern.check(Schema.makeFilter((pattern) => pattern === \"/\" || !pattern.endsWith(\"/\") && !pattern.includes(\"//\") || \"Patterns must not contain empty segments or trailing slashes\"), Schema.makeFilter((pattern) => !/[[\\]()\\u0000-\\u001F\\u007F\\uD800-\\uDFFF]/u.test(pattern) || \"Patterns must use decoded literal segments and supported parameter syntax\"));\nconst invalid = (message, pattern) => new RoutingDefinitionError({\n\tmessage,\n\tpattern\n});\nconst weight = (segment) => segment.kind === \"Literal\" ? 3 : segment.kind === \"Parameter\" ? 2 : 1;\nconst segmentText = (segment) => segment.kind === \"Literal\" ? segment.value : `${segment.kind === \"Parameter\" ? \":\" : \"*\"}${segment.name}`;\nconst makePattern = (segments) => ({\n\tpattern: `/${segments.map(segmentText).join(\"/\")}`,\n\tsegments,\n\tprecedence: segments.map(weight)\n});\nconst structuralKey = (pattern) => JSON.stringify(pattern.segments.map((segment) => segment.kind === \"Literal\" ? [segment.kind, segment.value] : [segment.kind]));\nconst compare = (left, right) => {\n\tfor (let index = 0; index < Math.max(left.precedence.length, right.precedence.length); index++) {\n\t\tconst difference = (right.precedence[index] ?? 0) - (left.precedence[index] ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn 0;\n};\nconst contains = (directory, pattern) => directory.segments.length <= pattern.segments.length && directory.segments.every((segment, index) => segmentText(segment) === segmentText(pattern.segments[index]));\nconst parsePattern = Effect.fn(\"Routing.parsePattern\")(function* (input) {\n\tconst pattern = yield* Schema.decodeUnknownEffect(CanonicalPattern)(input).pipe(Effect.mapError(() => invalid(\"Route patterns must be canonical absolute paths outside /_ignotum.\", input)));\n\tif (pattern === \"/\") return makePattern([]);\n\tconst parts = pattern.slice(1).split(\"/\");\n\tif (parts.length > 128) return yield* invalid(\"Route patterns exceed the segment limit.\", pattern);\n\tconst segments = [];\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const [index, part] of parts.entries()) if (part.startsWith(\":\") || part.startsWith(\"*\")) {\n\t\tconst name = yield* Schema.decodeUnknownEffect(ParameterName)(part.slice(1)).pipe(Effect.mapError(() => invalid(\"Route parameter names must be valid TypeScript identifiers.\", pattern)));\n\t\tif (names.has(name)) return yield* invalid(`Repeated route parameter '${name}'.`, pattern);\n\t\tnames.add(name);\n\t\tif (part.startsWith(\"*\")) {\n\t\t\tif (index !== parts.length - 1) return yield* invalid(\"A catch-all must be the final segment.\", pattern);\n\t\t\tsegments.push({\n\t\t\t\tkind: \"CatchAll\",\n\t\t\t\tname\n\t\t\t});\n\t\t} else segments.push({\n\t\t\tkind: \"Parameter\",\n\t\t\tname\n\t\t});\n\t} else {\n\t\tif (part === \".\" || part === \"..\" || /[:*]/.test(part)) return yield* invalid(\"Route literals must not contain dot segments or parameter syntax.\", pattern);\n\t\tsegments.push({\n\t\t\tkind: \"Literal\",\n\t\t\tvalue: part\n\t\t});\n\t}\n\treturn makePattern(segments);\n});\nconst compileRoute = Effect.fn(\"Routing.compileRoute\")(function* (input) {\n\tconst route = yield* Schema.decodeUnknownEffect(RouteDefinition)(input).pipe(Effect.mapError(() => invalid(\"The route definition is invalid.\")));\n\tconst parsed = yield* parsePattern(route.pattern);\n\tconst directory = yield* parsePattern(route.directoryScope ?? route.pattern);\n\tif (!contains(directory, parsed) || directory.segments.length < parsed.segments.length - 1) return yield* invalid(\"A route directory must be its full pattern for an index page or its immediate parent for a page file.\", route.pattern);\n\tif (route.precedence.length !== parsed.precedence.length || route.precedence.some((value, index) => value !== parsed.precedence[index])) return yield* invalid(\"Stored route precedence does not match its pattern.\", route.pattern);\n\tconst parameters = parsed.segments.filter((segment) => segment.kind !== \"Literal\");\n\tif (route.params.length !== parameters.length || new Set(route.params.map((field) => field.name)).size !== route.params.length) return yield* invalid(\"Route parameters must describe each dynamic name exactly once.\", route.pattern);\n\tfor (const parameter of parameters) {\n\t\tconst field = route.params.find((field) => field.name === parameter.name);\n\t\tif (field === void 0 || (parameter.kind === \"CatchAll\" ? field.value.type !== \"array\" : field.value.type === \"array\")) return yield* invalid(\"Single parameters require scalar values and catch-alls require string arrays.\", route.pattern);\n\t}\n\tif (new Set(route.searchParams.map((field) => field.name)).size !== route.searchParams.length) return yield* invalid(\"Search parameter names must be unique.\", route.pattern);\n\treturn {\n\t\tpattern: parsed,\n\t\tdirectory\n\t};\n});\nconst validateRoutePattern = Effect.fn(\"Routing.validateRoutePattern\")(function* (input) {\n\treturn (yield* compileRoute(input)).pattern;\n});\nconst compilePatterns = Effect.fn(\"Routing.compilePatterns\")(function* (routeInput, layoutInput) {\n\tconst routes = yield* Schema.decodeUnknownEffect(Schema.Array(RouteDefinition).check(Schema.isMaxLength(appDefinitionLimits.routes)))(routeInput).pipe(Effect.mapError(() => invalid(\"Route definitions are invalid or exceed the route limit.\")));\n\tconst layouts = yield* Schema.decodeUnknownEffect(Schema.Array(LayoutDefinition).check(Schema.isMaxLength(appDefinitionLimits.layouts)))(layoutInput).pipe(Effect.mapError(() => invalid(\"Layout definitions are invalid or exceed the layout limit.\")));\n\tif (new Set(routes.map((route) => route.id)).size !== routes.length) return yield* invalid(\"Route identities must be unique.\");\n\tif (new Set(layouts.map((layout) => layout.id)).size !== layouts.length) return yield* invalid(\"Layout identities must be unique.\");\n\tconst parsedRoutes = yield* Effect.forEach(routes, (route) => compileRoute(route));\n\tconst parsedLayouts = yield* Effect.forEach(layouts, (layout) => parsePattern(layout.scope));\n\tif (new Set(parsedRoutes.map((route) => structuralKey(route.pattern))).size !== routes.length) return yield* invalid(\"Duplicate or structurally ambiguous route patterns.\");\n\tif (new Set(parsedLayouts.map(structuralKey)).size !== layouts.length) return yield* invalid(\"Duplicate or structurally ambiguous layout scopes.\");\n\tconst layoutPatterns = layouts.map((layout, index) => ({\n\t\tlayout,\n\t\tpattern: parsedLayouts[index]\n\t}));\n\tconst applicable = (pattern) => layoutPatterns.filter((item) => contains(item.pattern, pattern)).sort((a, b) => a.pattern.segments.length - b.pattern.segments.length).map((item) => item.layout);\n\tfor (const { layout, pattern } of layoutPatterns) {\n\t\tconst ancestors = applicable(pattern).filter((candidate) => candidate.id !== layout.id);\n\t\tif (layout.parent !== ancestors.at(-1)?.id) return yield* invalid(`Layout '${layout.id}' must name its nearest directory layout as parent.`, layout.scope);\n\t}\n\tconst directories = /* @__PURE__ */ new Map();\n\tconst addDirectory = Effect.fn(\"Routing.addDirectory\")(function* (pattern) {\n\t\tconst key = structuralKey(pattern);\n\t\tconst existing = directories.get(key);\n\t\tif (existing !== void 0 && existing.pattern !== pattern.pattern) return yield* invalid(\"Dynamic directory parameter names are structurally ambiguous.\", pattern.pattern);\n\t\tdirectories.set(key, pattern);\n\t});\n\tyield* addDirectory(makePattern([]));\n\tfor (const pattern of parsedLayouts) for (let length = 1; length <= pattern.segments.length; length++) yield* addDirectory(makePattern(pattern.segments.slice(0, length)));\n\tconst compiledRoutes = [];\n\tfor (const [index, route] of routes.entries()) {\n\t\tconst { pattern, directory } = parsedRoutes[index];\n\t\tconst branch = applicable(directory);\n\t\tif (route.layouts.length !== branch.length || route.layouts.some((id, index) => id !== branch[index]?.id)) return yield* invalid(`Route '${route.id}' must include its complete directory layout branch.`, route.pattern);\n\t\tfor (let length = 1; length <= directory.segments.length; length++) yield* addDirectory(makePattern(directory.segments.slice(0, length)));\n\t\tcompiledRoutes.push({\n\t\t\troute,\n\t\t\tpattern,\n\t\t\tlayouts: branch\n\t\t});\n\t}\n\treturn {\n\t\troutes: compiledRoutes.sort((a, b) => compare(a.pattern, b.pattern)),\n\t\tdirectories: [...directories.values()].map((pattern) => ({\n\t\t\tpattern,\n\t\t\tlayouts: applicable(pattern)\n\t\t})).sort((a, b) => compare(a.pattern, b.pattern))\n\t};\n});\nconst captures = (pattern, segments, directory) => {\n\tconst values = [];\n\tfor (const [index, part] of pattern.segments.entries()) {\n\t\tconst value = segments[index];\n\t\tif (value === void 0 || value.length === 0) return void 0;\n\t\tif (part.kind === \"Literal\") {\n\t\t\tif (part.value !== value) return void 0;\n\t\t} else if (part.kind === \"Parameter\") values.push([part.name, value]);\n\t\telse {\n\t\t\tvalues.push([part.name, segments.slice(index)]);\n\t\t\treturn Object.fromEntries(values);\n\t\t}\n\t}\n\tif (!directory && segments.length !== pattern.segments.length) return void 0;\n\treturn Object.fromEntries(values);\n};\nconst matchDirectory = (compiled, decodedSegments) => {\n\tif (decodedSegments[0] === \"_ignotum\") return {\n\t\troute: void 0,\n\t\tlayouts: [],\n\t\tparams: {}\n\t};\n\tfor (const directory of compiled.directories) {\n\t\tconst params = captures(directory.pattern, decodedSegments, true);\n\t\tif (params !== void 0) return {\n\t\t\troute: void 0,\n\t\t\tlayouts: directory.layouts,\n\t\t\tparams\n\t\t};\n\t}\n\treturn {\n\t\troute: void 0,\n\t\tlayouts: [],\n\t\tparams: {}\n\t};\n};\nconst matchPattern = (compiled, decodedSegments) => {\n\tif (decodedSegments[0] === \"_ignotum\") return {\n\t\troute: void 0,\n\t\tlayouts: [],\n\t\tparams: {}\n\t};\n\tfor (const entry of compiled.routes) {\n\t\tconst params = captures(entry.pattern, decodedSegments, false);\n\t\tif (params !== void 0) return {\n\t\t\troute: entry.route,\n\t\t\tlayouts: entry.layouts,\n\t\t\tparams\n\t\t};\n\t}\n\treturn matchDirectory(compiled, decodedSegments);\n};\n//#endregion\nexport { RoutingDefinitionError, compilePatterns, matchDirectory, matchPattern, parsePattern, validateRoutePattern };\n\n//# sourceMappingURL=pattern.js.map","import { validateRoutePattern } from \"./pattern.js\";\nimport { Array, Effect, Schema } from \"effect\";\nimport { RouteDefinition } from \"@ignotum/contracts/app-definition\";\nimport { GeneratedId } from \"@ignotum/contracts/runtime/id\";\n//#region src/routing/url.ts\nconst UrlIssue = Schema.Struct({\n\tsource: Schema.Literals([\"params\", \"searchParams\"]),\n\tfield: Schema.optional(Schema.String),\n\tmessage: Schema.String\n});\nconst ParsedLocation = Schema.Struct({\n\tsegments: Schema.Array(Schema.String),\n\tpathname: Schema.String,\n\tsearch: Schema.String,\n\thash: Schema.String,\n\tcanonicalUrl: Schema.String\n});\nconst PartialLocation = Schema.Struct({\n\t...ParsedLocation.fields,\n\tpathComplete: Schema.Boolean\n});\nvar InvalidUrl = class extends Schema.TaggedError()(\"InvalidUrl\", {\n\tissues: Schema.Array(UrlIssue),\n\tpartial: Schema.optional(PartialLocation)\n}) {};\nconst invalid = (source, message, field, partial) => InvalidUrl.make({\n\tissues: [{\n\t\tsource,\n\t\tfield,\n\t\tmessage\n\t}],\n\tpartial\n});\nconst invalidField = (source, field) => invalid(source, `The URL field '${field}' does not match its declaration.`, field);\nconst SafeSegment = Schema.String.check(Schema.isMinLength(1), Schema.isPattern(/^[^/\\\\\\u0000-\\u001f\\u007f]+$/u), Schema.makeFilter((value) => value !== \".\" && value !== \"..\" || \"Dot segments are not allowed\"));\nconst DecimalText = Schema.String.check(Schema.isPattern(/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/));\nconst InputRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst BuildInput = Schema.Struct({\n\tparams: Schema.optional(Schema.Unknown),\n\tsearchParams: Schema.optional(Schema.Unknown),\n\thash: Schema.optional(Schema.String.check(Schema.makeFilter((value) => !value.startsWith(\"#\") || \"Hash input must omit the leading #\")))\n}).annotate({ parseOptions: { onExcessProperty: \"error\" } });\nconst decodeComponent = Effect.fn(\"Routing.decodeComponent\")(function* (value, source, field, partial) {\n\treturn yield* Effect.try({\n\t\ttry: () => {\n\t\t\treturn decodeURIComponent(value);\n\t\t},\n\t\tcatch: () => invalid(source, \"The URL contains malformed escapes or Unicode.\", field, partial)\n\t});\n});\nconst encodeComponent = Effect.fn(\"Routing.encodeComponent\")(function* (value, source, field) {\n\treturn yield* Effect.try({\n\t\ttry: () => encodeURIComponent(value),\n\t\tcatch: () => invalid(source, \"The URL contains malformed Unicode.\", field)\n\t});\n});\nconst searchEntries = Effect.fn(\"Routing.searchEntries\")(function* (search, partial) {\n\tyield* Schema.decodeUnknownEffect(Schema.String)(search).pipe(Effect.mapError(() => invalid(\"searchParams\", \"Search parameters must be URL query text.\", void 0, partial)));\n\tconst query = search.startsWith(\"?\") ? search.slice(1) : search;\n\tconst entries = [];\n\tfor (const item of query.split(\"&\")) {\n\t\tif (item === \"\") continue;\n\t\tconst equals = item.indexOf(\"=\");\n\t\tconst key = equals < 0 ? item : item.slice(0, equals);\n\t\tconst value = equals < 0 ? \"\" : item.slice(equals + 1);\n\t\tconst name = yield* decodeComponent(key.replaceAll(\"+\", \" \"), \"searchParams\", void 0, partial);\n\t\tentries.push([name, yield* decodeComponent(value.replaceAll(\"+\", \" \"), \"searchParams\", name, partial)]);\n\t}\n\treturn entries;\n});\n/** Parse a raw application-root-relative location before a URL implementation normalizes it. */\nconst parseLocation = Effect.fn(\"Routing.parseLocation\")(function* (input) {\n\tyield* Schema.decodeUnknownEffect(Schema.String)(input).pipe(Effect.mapError(() => invalid(\"params\", \"A location must be URL text.\")));\n\tconst fragmentAt = input.indexOf(\"#\");\n\tconst hash = fragmentAt < 0 ? \"\" : input.slice(fragmentAt);\n\tconst beforeHash = fragmentAt < 0 ? input : input.slice(0, fragmentAt);\n\tconst queryAt = beforeHash.indexOf(\"?\");\n\tconst search = queryAt < 0 ? \"\" : beforeHash.slice(queryAt);\n\tconst rawPathname = queryAt < 0 ? beforeHash : beforeHash.slice(0, queryAt);\n\tconst pathname = rawPathname.length > 1 && rawPathname.endsWith(\"/\") ? rawPathname.slice(0, -1) : rawPathname;\n\tconst segments = [];\n\tconst partial = (pathComplete) => ({\n\t\tsegments: [...segments],\n\t\tpathname,\n\t\tsearch,\n\t\thash,\n\t\tcanonicalUrl: `${pathname}${search}${hash}`,\n\t\tpathComplete\n\t});\n\tif (!rawPathname.startsWith(\"/\") || rawPathname.startsWith(\"//\")) return yield* invalid(\"params\", \"A location must start with exactly one application-root slash.\", void 0, partial(false));\n\tif (pathname !== \"/\") for (const raw of pathname.slice(1).split(\"/\")) {\n\t\tconst segment = yield* decodeComponent(raw, \"params\", void 0, partial(false));\n\t\tyield* Schema.decodeEffect(SafeSegment)(segment).pipe(Effect.mapError(() => invalid(\"params\", \"Path segments must be nonempty and cannot contain slashes, dot navigation or control characters.\", void 0, partial(false))));\n\t\tsegments.push(segment);\n\t}\n\tyield* searchEntries(search, partial(true));\n\tyield* decodeComponent(hash.slice(1), \"params\", void 0, partial(true));\n\treturn {\n\t\tsegments,\n\t\tpathname,\n\t\tsearch,\n\t\thash,\n\t\tcanonicalUrl: `${pathname}${search}${hash}`\n\t};\n});\nconst scalarSchema = (descriptor) => {\n\tswitch (descriptor.type) {\n\t\tcase \"string\": return Schema.String;\n\t\tcase \"id\": return GeneratedId;\n\t\tcase \"number\": return Schema.Finite;\n\t\tcase \"integer\": return Schema.Int;\n\t\tcase \"boolean\": return Schema.Boolean;\n\t\tcase \"literal\": return Schema.Literal(descriptor.value);\n\t\tcase \"literals\": return Schema.Literals(descriptor.values);\n\t}\n};\nconst scalarText = Effect.fn(\"Routing.scalarText\")(function* (descriptor, value, source, field) {\n\tswitch (descriptor.type) {\n\t\tcase \"number\":\n\t\tcase \"integer\":\n\t\t\tyield* Schema.decodeEffect(DecimalText)(value).pipe(Effect.mapError(() => invalidField(source, field)));\n\t\t\treturn yield* Schema.decodeUnknownEffect(scalarSchema(descriptor))(Number(value)).pipe(Effect.mapError(() => invalidField(source, field)));\n\t\tcase \"boolean\": return (yield* Schema.decodeUnknownEffect(Schema.Literals([\"true\", \"false\"]))(value).pipe(Effect.mapError(() => invalidField(source, field)))) === \"true\";\n\t\tcase \"literal\":\n\t\t\tyield* Schema.decodeEffect(Schema.Literal(String(descriptor.value)))(value).pipe(Effect.mapError(() => invalidField(source, field)));\n\t\t\treturn descriptor.value;\n\t\tcase \"literals\":\n\t\t\tyield* Schema.decodeEffect(Schema.Literals(descriptor.values.map(String)))(value).pipe(Effect.mapError(() => invalidField(source, field)));\n\t\t\treturn descriptor.values.find((literal) => String(literal) === value);\n\t\tdefault: return yield* Schema.decodeUnknownEffect(scalarSchema(descriptor))(value).pipe(Effect.mapError(() => invalidField(source, field)));\n\t}\n});\nconst suppliedValue = Effect.fn(\"Routing.suppliedValue\")(function* (descriptor, input, source, field) {\n\tconst schema = descriptor.type === \"array\" ? Schema.Array(scalarSchema(descriptor.value)) : scalarSchema(descriptor);\n\tconst value = yield* Schema.decodeUnknownEffect(schema)(input).pipe(Effect.mapError(() => invalidField(source, field)));\n\tfor (const item of Array.ensure(value)) yield* encodeComponent(String(item), source, field);\n\treturn value;\n});\nconst validateDefinition = Effect.fn(\"Routing.validateUrlDefinition\")(function* (input) {\n\tconst route = yield* Schema.decodeUnknownEffect(RouteDefinition)(input).pipe(Effect.mapError(() => invalid(\"params\", \"The route's URL declaration is invalid.\")));\n\tconst pattern = yield* validateRoutePattern(route).pipe(Effect.mapError((error) => invalid(\"params\", error.message)));\n\tfor (const field of route.searchParams) {\n\t\tyield* encodeComponent(field.name, \"searchParams\", field.name);\n\t\tif (field.value.type === \"default\") yield* suppliedValue(field.value.value, field.value.default, \"searchParams\", field.name);\n\t}\n\treturn {\n\t\troute,\n\t\tpattern\n\t};\n});\nconst inputRecord = Effect.fn(\"Routing.inputRecord\")(function* (input, fields, source) {\n\tconst values = yield* Schema.decodeUnknownEffect(InputRecord)(input === void 0 ? {} : input).pipe(Effect.mapError(() => invalid(source, `The ${source} input must be an object.`)));\n\tfor (const name of Object.keys(values)) if (!fields.some((field) => field.name === name)) return yield* invalid(source, `The URL field '${name}' is not declared.`, name);\n\treturn values;\n});\nconst own = (record, field) => Object.hasOwn(record, field) ? record[field] : void 0;\nconst pathValue = Effect.fn(\"Routing.pathValue\")(function* (value, name) {\n\tconst text = String(value);\n\tyield* Schema.decodeEffect(SafeSegment)(text).pipe(Effect.mapError(() => invalidField(\"params\", name)));\n\tyield* encodeComponent(text, \"params\", name);\n\treturn text;\n});\n/** rawParams already contains decoded segments from parseLocation and must not be decoded twice. */\nconst decodeRouteInputs = Effect.fn(\"Routing.decodeRouteInputs\")(function* (input, rawParams, search) {\n\tconst { route } = yield* validateDefinition(input);\n\tconst raw = yield* inputRecord(rawParams, route.params, \"params\");\n\tconst params = [];\n\tfor (const field of route.params) {\n\t\tconst value = own(raw, field.name);\n\t\tif (field.value.type === \"array\") {\n\t\t\tconst values = yield* Schema.decodeUnknownEffect(Schema.Array(Schema.String).check(Schema.isMinLength(1)))(value).pipe(Effect.mapError(() => invalidField(\"params\", field.name)));\n\t\t\tparams.push([field.name, yield* Effect.forEach(values, (item) => pathValue(item, field.name))]);\n\t\t} else {\n\t\t\tconst text = yield* Schema.decodeUnknownEffect(Schema.String)(value).pipe(Effect.mapError(() => invalidField(\"params\", field.name)));\n\t\t\tyield* pathValue(text, field.name);\n\t\t\tparams.push([field.name, yield* scalarText(field.value, text, \"params\", field.name)]);\n\t\t}\n\t}\n\tconst query = yield* searchEntries(search);\n\tconst searchParams = [];\n\tfor (const field of route.searchParams) {\n\t\tconst values = query.filter(([name]) => name === field.name).map(([, value]) => value);\n\t\tconst descriptor = field.value;\n\t\tif (values.length === 0) {\n\t\t\tif (descriptor.type === \"optional\") {\n\t\t\t\tsearchParams.push([field.name, void 0]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (descriptor.type === \"default\") {\n\t\t\t\tsearchParams.push([field.name, yield* suppliedValue(descriptor.value, descriptor.default, \"searchParams\", field.name)]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn yield* invalid(\"searchParams\", `The required URL field '${field.name}' is missing.`, field.name);\n\t\t}\n\t\tconst required = descriptor.type === \"optional\" || descriptor.type === \"default\" ? descriptor.value : descriptor;\n\t\tif (required.type === \"array\") searchParams.push([field.name, yield* Effect.forEach(values, (value) => scalarText(required.value, value, \"searchParams\", field.name))]);\n\t\telse {\n\t\t\tif (values.length !== 1) return yield* invalid(\"searchParams\", `The scalar URL field '${field.name}' occurs more than once.`, field.name);\n\t\t\tsearchParams.push([field.name, yield* scalarText(required, values[0], \"searchParams\", field.name)]);\n\t\t}\n\t}\n\treturn {\n\t\tparams: Object.fromEntries(params),\n\t\tsearchParams: Object.fromEntries(searchParams)\n\t};\n});\nconst sameValue = (left, right) => Array.isArray(left) && Array.isArray(right) ? left.length === right.length && left.every((value, index) => value === right[index]) : left === right;\nconst buildUrl = Effect.fn(\"Routing.buildUrl\")(function* (input, values = {}) {\n\tconst { route, pattern } = yield* validateDefinition(input);\n\tconst navigation = yield* Schema.decodeUnknownEffect(BuildInput)(values).pipe(Effect.mapError(() => invalid(\"params\", \"The URL navigation input is invalid.\")));\n\tconst params = yield* inputRecord(navigation.params, route.params, \"params\");\n\tconst searchParams = yield* inputRecord(navigation.searchParams, route.searchParams, \"searchParams\");\n\tconst segments = [];\n\tfor (const segment of pattern.segments) {\n\t\tif (segment.kind === \"Literal\") {\n\t\t\tsegments.push(yield* encodeComponent(segment.value, \"params\"));\n\t\t\tcontinue;\n\t\t}\n\t\tconst field = route.params.find((candidate) => candidate.name === segment.name);\n\t\tconst value = yield* suppliedValue(field.value, own(params, field.name), \"params\", field.name);\n\t\tconst parts = Array.ensure(value);\n\t\tif (parts.length === 0) return yield* invalid(\"params\", \"Catch-all parameters must contain at least one segment.\", field.name);\n\t\tfor (const part of parts) segments.push(yield* encodeComponent(yield* pathValue(part, field.name), \"params\", field.name));\n\t}\n\tif (segments[0] === \"_ignotum\") {\n\t\tconst first = pattern.segments[0];\n\t\treturn yield* invalid(\"params\", \"The /_ignotum path is reserved for the platform.\", first?.kind === \"Parameter\" || first?.kind === \"CatchAll\" ? first.name : void 0);\n\t}\n\tconst query = new URLSearchParams();\n\tfor (const field of route.searchParams) {\n\t\tconst raw = own(searchParams, field.name);\n\t\tconst descriptor = field.value;\n\t\tif (raw === void 0) {\n\t\t\tif (descriptor.type === \"optional\" || descriptor.type === \"default\") continue;\n\t\t\treturn yield* invalid(\"searchParams\", `The required URL field '${field.name}' is missing.`, field.name);\n\t\t}\n\t\tconst required = descriptor.type === \"optional\" || descriptor.type === \"default\" ? descriptor.value : descriptor;\n\t\tconst value = yield* suppliedValue(required, raw, \"searchParams\", field.name);\n\t\tif (descriptor.type === \"default\" && sameValue(value, descriptor.default)) continue;\n\t\tconst items = Array.ensure(value);\n\t\tif (items.length === 0 && descriptor.type !== \"optional\" && descriptor.type !== \"default\") return yield* invalid(\"searchParams\", \"A required array cannot serialize as an absent search key.\", field.name);\n\t\tfor (const item of items) query.append(field.name, String(item));\n\t}\n\tconst search = query.toString();\n\tconst hash = navigation.hash === void 0 || navigation.hash === \"\" ? \"\" : `#${yield* encodeComponent(navigation.hash, \"params\")}`;\n\treturn `/${segments.join(\"/\")}${search === \"\" ? \"\" : `?${search}`}${hash}`;\n});\n//#endregion\nexport { InvalidUrl, ParsedLocation, PartialLocation, UrlIssue, buildUrl, decodeRouteInputs, parseLocation };\n\n//# sourceMappingURL=url.js.map","import {\n buildUrl,\n compilePatterns,\n decodeRouteInputs,\n matchPattern,\n parseLocation,\n} from \"@ignotum/shared/routing\";\nimport { Effect, Predicate, Schema } from \"effect\";\nimport { createContext, createElement, type JSX } from \"preact\";\nimport { useContext, useEffect, useLayoutEffect, useRef, useState } from \"preact/hooks\";\nimport {\n getRouteDefinition,\n type RouteReference,\n type ReferenceTypes,\n} from \"../internal/routes.js\";\nimport type { RouteInputs, RouteMatch, RouteLocation, NavigationResult } from \"./routes.js\";\nimport type {\n RouterStore,\n RouterSnapshot,\n NavigationOptions,\n NavigationState,\n BlockerState,\n} from \"./router-store.js\";\n\nexport const RouterContext = createContext<RouterStore | undefined>(undefined);\nconst useRouter = (): RouterStore => {\n const router = useContext(RouterContext);\n if (router === undefined)\n throw new Error(\"Ignotum routing hooks require a managed client mount.\");\n return router;\n};\nexport const useRouterSnapshot = (router: RouterStore): RouterSnapshot => {\n const [snapshot, setSnapshot] = useState(router.getSnapshot);\n useLayoutEffect(() => {\n const update = () => setSnapshot(router.getSnapshot());\n const unsubscribe = router.subscribe(update);\n update();\n return unsubscribe;\n }, [router]);\n return snapshot;\n};\n\ntype OptionsArgs<Options> = {} extends Options ? [options?: Options] : [options: Options];\nexport type NavigateOptions<Reference extends RouteReference> = RouteInputs<Reference> &\n NavigationOptions;\nexport interface Navigate {\n <Reference extends RouteReference>(\n reference: Reference,\n ...args: OptionsArgs<NavigateOptions<NoInfer<Reference>>>\n ): Promise<NavigationResult>;\n back(): void;\n forward(): void;\n}\n\nexport function url<Reference extends RouteReference>(\n reference: Reference,\n ...args: OptionsArgs<RouteInputs<NoInfer<Reference>>>\n): string {\n return Effect.runSync(buildUrl(getRouteDefinition(reference), args[0]));\n}\n\n// Link and navigate own additional options; only URL fields belong to the shared URL codec.\nconst destinationHref = (\n reference: RouteReference,\n input: {\n readonly params?: unknown;\n readonly searchParams?: unknown;\n readonly hash?: string;\n } = {},\n): string =>\n Effect.runSync(\n buildUrl(getRouteDefinition(reference), {\n params: input.params,\n searchParams: input.searchParams,\n hash: input.hash,\n }),\n );\n\nconst NavigationInput = Schema.Struct({\n params: Schema.optional(Schema.Unknown),\n searchParams: Schema.optional(Schema.Unknown),\n hash: Schema.optional(Schema.String),\n replace: Schema.optional(Schema.Boolean),\n scroll: Schema.optional(Schema.Literals([\"auto\", \"preserve\"])),\n}).annotate({ parseOptions: { onExcessProperty: \"error\" } });\n\nexport const useNavigate = (): Navigate => {\n const router = useRouter();\n const [navigate] = useState<Navigate>(() =>\n Object.assign(\n <Reference extends RouteReference>(\n reference: Reference,\n ...args: OptionsArgs<NavigateOptions<NoInfer<Reference>>>\n ) => {\n const options = Schema.decodeUnknownSync(NavigationInput)(args[0] ?? {});\n return router.navigate(destinationHref(reference, options), options);\n },\n { back: router.back, forward: router.forward },\n ),\n );\n return navigate;\n};\nexport const useLocation = (): RouteLocation => {\n const snapshot = useRouterSnapshot(useRouter());\n if (snapshot.location === undefined)\n throw new Error(\"The initial Ignotum location has not committed.\");\n return snapshot.location;\n};\nexport const useNavigation = (): NavigationState => useRouterSnapshot(useRouter()).navigation;\n\nexport const useBlocker = ({ when }: { readonly when: boolean }): BlockerState => {\n const router = useRouter();\n const [id] = useState(() => Symbol(\"blocker\"));\n useRouterSnapshot(router);\n useLayoutEffect(() => {\n router.setBlocker(id, when);\n }, [router, id, when]);\n useLayoutEffect(() => () => router.setBlocker(id, false), [router, id]);\n return router.getBlocker(id);\n};\n\nconst matchReference = <Reference extends RouteReference>(\n reference: Reference,\n snapshot: RouterSnapshot,\n end: boolean,\n): RouteMatch<Reference> | undefined => {\n const location = snapshot.location;\n const outcome = snapshot.branch?.outcome;\n if (location === undefined || outcome === undefined) return;\n const definition = getRouteDefinition(reference);\n if (end && (outcome._tag !== \"Matched\" || outcome.route.id !== definition.id)) return;\n const parsed = Effect.runSync(\n parseLocation(`${location.pathname}${location.search}`).pipe(Effect.result),\n );\n if (parsed._tag === \"Failure\") return;\n const compiled = Effect.runSync(compilePatterns([{ ...definition, layouts: [] }], []));\n for (let length = parsed.success.segments.length; length >= 0; length--) {\n if (length === 0 && parsed.success.segments.length !== 0) break;\n const match = matchPattern(compiled, parsed.success.segments.slice(0, length));\n if (match.route !== undefined) {\n const decoded = Effect.runSync(\n decodeRouteInputs(definition, match.params, location.search).pipe(Effect.result),\n );\n if (decoded._tag === \"Failure\") return;\n // SAFETY: The reference's own validated descriptors determine these decoded generic input types.\n return { ...decoded.success, hash: location.hash } as RouteMatch<Reference>;\n }\n if (end) break;\n }\n return;\n};\nexport function useMatch<Reference extends RouteReference>(\n reference: Reference,\n options?: { readonly end?: boolean },\n): RouteMatch<Reference> | undefined {\n return matchReference(reference, useRouterSnapshot(useRouter()), options?.end ?? true);\n}\nexport type RouteState<Reference extends RouteReference> = RouteMatch<Reference> & {\n readonly setSearchParams: (\n next:\n | ReferenceTypes<Reference>[\"searchInputs\"]\n | ((\n current: ReferenceTypes<Reference>[\"searchParams\"],\n ) => ReferenceTypes<Reference>[\"searchInputs\"]),\n options?: NavigationOptions,\n ) => Promise<NavigationResult>;\n};\nexport function useRoute<Reference extends RouteReference>(\n reference: Reference,\n): RouteState<Reference> {\n const router = useRouter();\n const snapshot = useRouterSnapshot(router);\n const match = matchReference(reference, snapshot, true);\n if (match === undefined)\n throw new Error(`useRoute requires page '${getRouteDefinition(reference).id}' to be active.`);\n return {\n ...match,\n setSearchParams: (next, options) => {\n const latest = matchReference(reference, router.getSnapshot(), true);\n const location = router.getSnapshot().location;\n if (latest === undefined || location === undefined)\n throw new Error(\"Cannot update search parameters for an inactive route.\");\n // A function is the only callable alternative in the public search update union.\n const inputs = Predicate.isFunction(next) ? next(latest.searchParams) : next;\n const href = destinationHref(reference, {\n params: latest.params,\n searchParams: inputs,\n hash: latest.hash,\n });\n const destination = new URL(href, router.browser.location.origin);\n destination.pathname = location.pathname;\n const declared = new Set(\n getRouteDefinition(reference).searchParams.map((field) => field.name),\n );\n for (const [name, value] of new URLSearchParams(location.search)) {\n if (!declared.has(name)) destination.searchParams.append(name, value);\n }\n return router.navigate(`${destination.pathname}${destination.search}${destination.hash}`, {\n scroll: \"preserve\",\n ...options,\n });\n },\n };\n}\n\ntype AnchorProps = Omit<JSX.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\" | \"class\" | \"ref\">;\nexport type LinkProps<Reference extends RouteReference> = AnchorProps &\n NavigateOptions<Reference> & {\n readonly to: Reference;\n readonly class?: string;\n readonly preload?: \"intent\" | \"none\";\n };\nexport type NavLinkProps<Reference extends RouteReference> = Omit<LinkProps<Reference>, \"class\"> & {\n readonly end?: boolean;\n readonly class?: string | ((state: { readonly isActive: boolean }) => string);\n};\n\nconst activePath = (current: string, destination: string, end: boolean): boolean => {\n const source = Effect.runSync(parseLocation(current).pipe(Effect.result));\n const target = Effect.runSync(parseLocation(destination).pipe(Effect.result));\n if (source._tag === \"Failure\" || target._tag === \"Failure\") return false;\n const from = source.success.segments;\n const to = target.success.segments;\n if (from.length !== to.length && (end || to.length === 0 || from.length < to.length))\n return false;\n return to.every((segment, index) => from[index] === segment);\n};\n\ninterface AnchorRuntimeProps extends AnchorProps, NavigationOptions {\n readonly to: RouteReference;\n readonly params?: unknown;\n readonly searchParams?: unknown;\n readonly hash?: string;\n readonly preload?: \"intent\" | \"none\";\n readonly end?: boolean;\n readonly active?: boolean;\n readonly class?: string | ((state: { readonly isActive: boolean }) => string);\n}\nfunction Anchor(props: AnchorRuntimeProps): JSX.Element {\n const router = useRouter();\n const snapshot = useRouterSnapshot(router);\n const {\n to,\n params,\n searchParams,\n hash,\n replace,\n scroll,\n preload = \"intent\",\n end = true,\n active = false,\n class: className,\n onClick,\n onMouseEnter,\n onFocus,\n ...attributes\n } = props;\n const href = destinationHref(to, { params, searchParams, hash });\n const isActive =\n active &&\n snapshot.location !== undefined &&\n activePath(snapshot.location.pathname, href.split(/[?#]/)[0]!, end);\n const prepare = () => {\n if (preload !== \"none\") void router.preload(href).catch(() => {});\n };\n return createElement(\"a\", {\n ...attributes,\n href,\n class: Predicate.isFunction(className) ? className({ isActive }) : className,\n \"aria-current\": isActive ? \"page\" : attributes[\"aria-current\"],\n onClick: (event: JSX.TargetedMouseEvent<HTMLAnchorElement>): void => {\n onClick?.(event);\n const anchor = event.currentTarget;\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey ||\n (anchor.target !== \"\" && anchor.target.toLowerCase() !== \"_self\") ||\n anchor.hasAttribute(\"download\") ||\n anchor.relList.contains(\"external\") ||\n anchor.origin !== router.browser.location.origin ||\n `${anchor.pathname}${anchor.search}${anchor.hash}` !== href\n )\n return;\n event.preventDefault();\n void router.navigate(href, { replace, scroll });\n },\n onMouseEnter: (event: JSX.TargetedMouseEvent<HTMLAnchorElement>): void => {\n onMouseEnter?.(event);\n if (!event.defaultPrevented) prepare();\n },\n onFocus: (event: JSX.TargetedFocusEvent<HTMLAnchorElement>): void => {\n onFocus?.(event);\n if (!event.defaultPrevented) prepare();\n },\n });\n}\nexport function Link<Reference extends RouteReference>(props: LinkProps<Reference>): JSX.Element {\n return createElement(Anchor, props);\n}\nexport function NavLink<Reference extends RouteReference>(\n props: NavLinkProps<Reference>,\n): JSX.Element {\n return createElement(Anchor, { ...props, active: true });\n}\nexport type RedirectProps<Reference extends RouteReference> = NavigateOptions<Reference> & {\n readonly to: Reference;\n};\nexport function Redirect<Reference extends RouteReference>(props: RedirectProps<Reference>): null {\n const router = useRouter();\n const href = destinationHref(props.to, props);\n const previous = useRef<string>();\n const replace = props.replace ?? true;\n useEffect(() => {\n const identity = JSON.stringify([href, replace, props.scroll]);\n if (previous.current === identity) return;\n previous.current = identity;\n void router.navigate(href, { replace, scroll: props.scroll }, true);\n }, [router, href, replace, props.scroll]);\n return null;\n}\n"],"mappings":";;;;;;;;;AAEA,MAAM,cAAc,UAAU;CAC7B,IAAIA,QAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,EAAE;CACrE,IAAI,UAAU,QAAQ,UAAU,SAAS,KAAK,KAAK,UAAU,SAAS,KAAK,KAAK,UAAU,UAAU,KAAK,GAAG,OAAO,KAAK,UAAU,KAAK;CACvI,OAAO,IAAIA,QAAM,SAAS,OAAO,QAAQ,KAAK,IAAI,CAAC,SAAS,KAAKC,SAAO,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,WAAW,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;AAC/J;AACA,MAAM,uBAAuB,UAAU,WAAW,OAAO,WAAW,OAAO,IAAI,CAAC,CAAC,KAAK,CAAC;;;;ACFvF,IAAa,wBAAb,cAA2C,OAAO,YAAmC,CAAC,CACpF,yBACA;CACE,OAAO,OAAO,SAAS,OAAO,OAAO,CAAC;CACtC,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CA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