ignotum 0.0.13 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/bin.mjs +369 -55
- package/dist/cli/bin.mjs.map +1 -1
- package/dist/runtime/client.d.ts +3 -3
- package/dist/runtime/client.js +24 -4
- package/dist/runtime/client.js.map +1 -1
- package/dist/runtime/descriptor-DCCz5AHd-_nhlnu8U.js +298 -0
- package/dist/runtime/descriptor-DCCz5AHd-_nhlnu8U.js.map +1 -0
- package/dist/runtime/id-E7JKqQ9r.d.ts +1 -0
- package/dist/runtime/index-DWU-7TIh.d.ts +185 -0
- package/dist/runtime/internal/host.d.ts +23 -5
- package/dist/runtime/internal/host.js +24 -4
- package/dist/runtime/internal/host.js.map +1 -1
- package/dist/runtime/internal/server.d.ts +1 -1
- package/dist/runtime/internal/server.js +1 -1
- package/dist/runtime/internal/types.d.ts +2 -1
- package/dist/runtime/internal/types.js +1 -1
- package/dist/runtime/{pagination-DnKg3dkI-r5ZUxBBx.d.ts → pagination-CpYCaRYD-C2Rpp4Cw.d.ts} +14 -4
- package/dist/runtime/pagination-E7JKqQ9r.d.ts +1 -0
- package/dist/runtime/{schema-1Zs03-iS.js → schema-DqogEydG.js} +38 -11
- package/dist/runtime/schema-DqogEydG.js.map +1 -0
- package/dist/runtime/server.d.ts +4 -3
- package/dist/runtime/server.js +1 -1
- package/dist/runtime/types-C1iDP2Yf-BnkfBOQf.d.ts +224 -0
- package/package.json +2 -2
- package/src/cli/agent-files.ts +4 -0
- package/src/cli/build/server.ts +35 -6
- package/src/cli/command.ts +25 -2
- package/src/cli/deploy.ts +34 -11
- package/src/client/sync.ts +1 -1
- package/src/dev-runtime/database.ts +77 -2
- package/src/dev-runtime/id.ts +19 -4
- package/src/dev-runtime/migrations.ts +9 -0
- package/src/internal/host.ts +1 -1
- package/dist/runtime/descriptor-Cyo9FP9n-C0SRVXNW.js +0 -154
- package/dist/runtime/descriptor-Cyo9FP9n-C0SRVXNW.js.map +0 -1
- package/dist/runtime/id-Dz0apuB3.d.ts +0 -1
- package/dist/runtime/index-D54flWtH.d.ts +0 -402
- package/dist/runtime/pagination-Dz0apuB3.d.ts +0 -1
- package/dist/runtime/schema-1Zs03-iS.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["Array","Result","useState","useCallback","useMemo","RuntimeResult","contractResult"],"sources":["../../../shared/dist/id.js","../../src/client/files.ts","../../../contracts/dist/json.js","../../src/client/id.ts","../../src/client/errors.ts","../../src/client/query.ts","../../../contracts/dist/runtime/index.js","../../../contracts/dist/runtime/hosted.js","../../../contracts/dist/runtime/functions.js","../../../contracts/dist/deployment.js","../../../contracts/dist/runtime/transport.js","../../src/internal/http-paths.ts","../../src/client/sync.ts","../../src/client/page-observers.ts","../../src/client/hooks.ts","../../src/client/app.ts","../../src/client/index.ts"],"sourcesContent":["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 { 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","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","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 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 };\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","/** @effect-diagnostics globalConsole:skip-file */\nimport { Cause, Effect, ErrorReporter, Schema } from \"effect\";\n\nimport { ErrorCode, FunctionAddress, Operation } 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 InvalidClientMessage extends Schema.TaggedError<InvalidClientMessage>()(\n \"InvalidClientMessage\",\n {\n cause: Schema.Defect(),\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: ErrorCode,\n message: Schema.String,\n operation: Schema.optional(Operation),\n}) {}\n\nexport const ClientInfrastructureError = Schema.Union([\n ConnectionUnavailable,\n InvalidClientMessage,\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","const QuerySkipTypeId: unique symbol = Symbol.for(\"ignotum/client/QuerySkip\");\n\nexport interface QuerySkip {\n readonly [QuerySkipTypeId]: typeof QuerySkipTypeId;\n}\n\nclass QuerySkipToken implements QuerySkip {\n readonly [QuerySkipTypeId]: typeof QuerySkipTypeId = QuerySkipTypeId;\n}\n\nconst skip: QuerySkip = Object.freeze(new QuerySkipToken());\n\nexport const Query = { skip };\n\nexport const isQuerySkip = <Value extends object | undefined>(\n value: Value,\n): value is Value & QuerySkip => value === skip;\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 { encodeCanonicalJson } from \"../json.js\";\nimport { AppId, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, ConnectionId, DeploymentId, DevDatabaseLockId, GeneratedId, InvocationId, PlatformPrincipalId, RequestId, RuntimeRequestNonce, SubscriptionId, TableId, TeamId } from \"./id.js\";\nimport { FileId, RuntimeFileMetadata, RuntimeFileOccurrence } from \"../schema/file.js\";\nimport { SessionState } from \"../id.js\";\nimport { AppStateRevision, DeploymentGeneration, InvocationKey } from \"./identity.js\";\nimport { FunctionAddress, WireFailure, WireResult, WireSuccess } from \"./sync.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\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});\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 InvocationBase = {\n\tappId: AppId,\n\tdeploymentId: DeploymentId,\n\tgeneration: DeploymentGeneration,\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\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 RuntimeDeploymentUnavailable = class extends Schema.TaggedError()(\"RuntimeDeploymentUnavailable\", {\n\tdeploymentId: DeploymentId,\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\tRuntimeDeploymentUnavailable,\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 = (deploymentId, functionAddress, args) => QueryKey.make(encodeCanonicalJson([\n\tdeploymentId,\n\tfunctionAddress,\n\targs\n]));\nconst canonicalInvocationInput = (deploymentId, functionKind, functionAddress, args, sessionEpoch) => encodeCanonicalJson(sessionEpoch === void 0 ? [\n\tdeploymentId,\n\tfunctionKind,\n\tfunctionAddress,\n\targs\n] : [\n\tdeploymentId,\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 { AppId, AppStateRevision, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, ConnectionId, DependencyKey, DependencySet, DeploymentGeneration, DeploymentId, DevDatabaseLockId, DocumentDependency, FileEffectBatch, FileEffectsAcknowledgeRequest, FileEffectsAcknowledgeResult, FileEffectsRequest, FileEffectsResult, FileReferenceAdded, FileReferenceEffect, FileReferenceRemoved, IdDependency, IndexPointInvalidation, IndexRangeDependency, InvalidationSet, InvocationId, InvocationKey, MutationInvocation, PlatformPrincipalId, QueryInvocation, QueryKey, ReadDependency, RequestId, RevisionCheck, RevisionCheckResult, RuntimeDeploymentUnavailable, RuntimeInvocation, RuntimeInvocationRejected, RuntimeInvocationRejectionCode, RuntimeInvocationResult, RuntimeInvocationUnavailable, RuntimeMutationFailure, RuntimeMutationResult, RuntimeMutationSuccess, RuntimeQueryResult, RuntimeRequestNonce, RuntimeRevisionRejected, RuntimeTransportError, SubscriptionId, TableDependency, TableId, TeamId, WriteInvalidation, canonicalInvocationInput, canonicalQueryKey, dependencyKey, documentDependency, indexPointInvalidation, indexRangeDependency, mutationInvocationKey, tableDependency };\n\n//# sourceMappingURL=hosted.js.map","import { FunctionAddress } from \"./sync.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/functions.ts\nconst FunctionKind = Schema.Literals([\"Mutation\", \"Query\"]);\nvar UnknownFunction = class extends Schema.TaggedError()(\"UnknownFunction\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar WrongFunctionKind = class extends Schema.TaggedError()(\"WrongFunctionKind\", {\n\tactual: FunctionKind,\n\texpected: FunctionKind,\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar InvalidArguments = class extends Schema.TaggedError()(\"InvalidArguments\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar FunctionUnavailable = class extends Schema.TaggedError()(\"FunctionUnavailable\", {\n\tcause: Schema.Defect(),\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\n//#endregion\nexport { FunctionKind, FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\n\n//# sourceMappingURL=functions.js.map","import { initial, upgrade } from \"./versioned.js\";\nimport { FunctionAddress } from \"./runtime/sync.js\";\nimport { FunctionKind } from \"./runtime/functions.js\";\nimport { t as ValueDescriptor } from \"./descriptor-Cyo9FP9n.js\";\nimport { Schema } from \"effect\";\n//#region src/deployment.ts\nconst ArtifactPath = Schema.String.check(Schema.isPattern(/^(?!\\/)(?![A-Za-z]:\\/)(?!.*(?:^|\\/)\\.\\.(?:\\/|$))(?!.*(?:^|\\/)\\.(?:\\/|$))(?!.*\\/\\/)[^\\\\\\0]+$/)).pipe(Schema.brand(\"ignotum/deployment/ArtifactPath\"));\nconst ClientPath = Schema.String.check(Schema.isPattern(/^\\/(?!_ignotum(?:\\/|$))(?:(?:[A-Za-z0-9._~-]+\\/)*[A-Za-z0-9._~-]+\\/?)?$/)).pipe(Schema.brand(\"ignotum/deployment/ClientPath\"));\nconst Sha256 = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/)).pipe(Schema.brand(\"ignotum/deployment/Sha256\"));\nconst ArtifactKind = Schema.Literals([\n\t\"ClientAsset\",\n\t\"ClientDocument\",\n\t\"ClientManifest\",\n\t\"ClientPublicFile\",\n\t\"ClientShell\",\n\t\"FunctionBundle\",\n\t\"ServerManifest\",\n\t\"ServerEnvironment\",\n\t\"SourceMap\",\n\t\"SchemaSnapshot\"\n]);\nconst ArtifactReference = Schema.Struct({\n\tpath: ArtifactPath,\n\tsize: Schema.Natural,\n\tsha256: Sha256\n});\nconst ArtifactFile = Schema.Struct({\n\tpath: ArtifactPath,\n\tsize: Schema.Natural,\n\tsha256: Sha256,\n\tkind: ArtifactKind,\n\tcontentType: Schema.String,\n\tcontentEncoding: Schema.optional(Schema.String)\n});\nconst ClientRoute = Schema.Struct({\n\tpathname: ClientPath,\n\tartifact: ArtifactReference\n});\nconst DeploymentInventoryV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tfiles: Schema.Array(ArtifactFile)\n});\nconst DeploymentInventoryV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\tfiles: Schema.Array(ArtifactFile)\n});\nconst DeploymentInventory = upgrade(initial(DeploymentInventoryV1), DeploymentInventoryV2, (inventory) => ({\n\tformatVersion: 2,\n\tfiles: inventory.files\n}));\nconst ClientManifestV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tshell: ArtifactReference,\n\troutes: Schema.Array(ClientRoute)\n});\nconst ClientManifest = initial(ClientManifestV1);\nconst ClientRoutingRoute = Schema.Struct({\n\tpathname: ClientPath,\n\tartifact: ArtifactPath\n});\nconst ClientRoutingV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tshell: ArtifactPath,\n\troutes: Schema.Array(ClientRoutingRoute)\n});\nconst ClientRouting = initial(ClientRoutingV1);\nconst SchemaSnapshotField = Schema.Struct({\n\tname: Schema.String,\n\tvalue: ValueDescriptor\n});\nconst EnvironmentArtifactV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tnonce: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]{43}$/)),\n\tvalues: Schema.Record(Schema.String, Schema.String)\n});\nconst EnvironmentArtifact = initial(EnvironmentArtifactV1);\nconst ServerEnvironmentArtifact = Schema.Struct({\n\tartifact: ArtifactReference,\n\tfields: Schema.Array(SchemaSnapshotField)\n});\nconst SchemaSnapshotIndex = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(Schema.String)\n});\nconst SchemaSnapshotTableV1 = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(SchemaSnapshotField)\n});\nconst SchemaSnapshotV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\ttables: Schema.Array(SchemaSnapshotTableV1)\n});\nconst SchemaSnapshotTable = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(SchemaSnapshotField),\n\tindexes: Schema.Array(SchemaSnapshotIndex)\n});\nconst SchemaSnapshotV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\ttables: Schema.Array(SchemaSnapshotTable)\n});\nconst SchemaSnapshot = upgrade(initial(SchemaSnapshotV1), SchemaSnapshotV2, (snapshot) => ({\n\tformatVersion: 2,\n\ttables: snapshot.tables.map((table) => ({\n\t\t...table,\n\t\tindexes: []\n\t}))\n}));\nconst ServerFunctionArtifactV1 = Schema.Struct({\n\taddress: FunctionAddress,\n\tkind: FunctionKind,\n\tbundle: ArtifactReference,\n\tsourceMap: ArtifactReference\n});\nconst ServerFunctionArtifact = Schema.Struct({\n\taddress: FunctionAddress,\n\tkind: FunctionKind,\n\targs: Schema.optional(ValueDescriptor),\n\treturns: Schema.optional(ValueDescriptor),\n\terrors: Schema.optional(ValueDescriptor),\n\tbundle: ArtifactReference,\n\tsourceMap: ArtifactReference\n});\nconst ServerBuildManifestV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tschema: ArtifactReference,\n\tfunctions: Schema.Array(ServerFunctionArtifactV1)\n});\nconst ServerBuildManifestV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\tschema: ArtifactReference,\n\tfunctions: Schema.Array(ServerFunctionArtifact)\n});\nconst ServerBuildManifestThroughV2 = upgrade(initial(ServerBuildManifestV1), ServerBuildManifestV2, (manifest) => ({\n\tformatVersion: 2,\n\tschema: manifest.schema,\n\tfunctions: manifest.functions\n}));\nconst ServerBuildManifestV3 = Schema.Struct({\n\tformatVersion: Schema.Literal(3),\n\tschema: ArtifactReference,\n\tenvironment: Schema.optional(ServerEnvironmentArtifact),\n\tfunctions: Schema.Array(ServerFunctionArtifact)\n});\nconst ServerBuildManifest = upgrade(ServerBuildManifestThroughV2, ServerBuildManifestV3, (manifest) => ({\n\tformatVersion: 3,\n\tschema: manifest.schema,\n\tfunctions: manifest.functions\n}));\nconst deploymentInventoryPath = ArtifactPath.make(\"inventory.json\");\nconst clientManifestPath = ArtifactPath.make(\"client/manifest.json\");\nconst clientShellPath = ArtifactPath.make(\"client/shell.html\");\nconst clientAssetDirectory = ArtifactPath.make(\"client/assets\");\nconst clientAssetPathPrefix = `${clientAssetDirectory}/`;\nconst clientRouteDirectory = ArtifactPath.make(\"client/routes\");\nconst clientRoutePathPrefix = `${clientRouteDirectory}/`;\nconst clientPublicFileExtensions = [\n\t\".avif\",\n\t\".gif\",\n\t\".ico\",\n\t\".jpeg\",\n\t\".jpg\",\n\t\".pdf\",\n\t\".png\",\n\t\".webp\"\n];\nconst serverManifestPath = ArtifactPath.make(\"server/manifest.json\");\nconst schemaSnapshotPath = ArtifactPath.make(\"server/schema.json\");\nconst serverEnvironmentPath = ArtifactPath.make(\"server/environment.json\");\nconst deploymentArtifactLimits = {\n\tfileBytes: 16777216,\n\tfileCount: 512,\n\tinventoryBytes: 1048576,\n\tserverBytes: 67108864,\n\ttotalBytes: 134217728\n};\n//#endregion\nexport { ArtifactFile, ArtifactKind, ArtifactPath, ArtifactReference, ClientManifest, ClientPath, ClientRoute, ClientRouting, ClientRoutingRoute, DeploymentInventory, EnvironmentArtifact, SchemaSnapshot, SchemaSnapshotField, SchemaSnapshotIndex, SchemaSnapshotTable, ServerBuildManifest, ServerEnvironmentArtifact, ServerFunctionArtifact, Sha256, clientAssetDirectory, clientAssetPathPrefix, clientManifestPath, clientPublicFileExtensions, clientRouteDirectory, clientRoutePathPrefix, clientShellPath, deploymentArtifactLimits, deploymentInventoryPath, schemaSnapshotPath, serverEnvironmentPath, serverManifestPath };\n\n//# sourceMappingURL=deployment.js.map","import { encodeCanonicalJson } from \"../json.js\";\nimport { AppId, DeploymentId, RuntimeRequestNonce } from \"./id.js\";\nimport { Sha256 } from \"../deployment.js\";\nimport { RuntimeInvocationRejectionCode } from \"./hosted.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/transport.ts\nconst runtimeInvocationPath = \"/v1/invoke\";\nconst runtimeRevisionPath = \"/v1/revision\";\nconst runtimeIndexPreparePath = \"/v1/indexes/prepare\";\nconst runtimeIndexCommitPath = \"/v1/indexes/commit\";\nconst runtimeFileEffectsPath = \"/v1/files/effects\";\nconst runtimeFileEffectsAcknowledgePath = \"/v1/files/effects/acknowledge\";\nconst ignotumPathPrefix = \"/_ignotum\";\nconst clientAssetUrlPrefix = `${ignotumPathPrefix}/assets/`;\nconst gatewayHealthPath = `${ignotumPathPrefix}/health`;\nconst appSyncPath = `${ignotumPathPrefix}/v1/sync`;\nconst fileUploadUrlPrefix = `${ignotumPathPrefix}/v1/files/upload/`;\nconst fileGrantUrlPrefix = `${ignotumPathPrefix}/v1/files/grant/`;\nconst RuntimeRequestPath = Schema.Literals([\n\truntimeInvocationPath,\n\truntimeRevisionPath,\n\truntimeIndexPreparePath,\n\truntimeIndexCommitPath,\n\truntimeFileEffectsPath,\n\truntimeFileEffectsAcknowledgePath\n]);\nconst RuntimeRequestTimestamp = Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)), Schema.brand(\"ignotum/runtime/RequestTimestamp\"));\nconst RuntimeRequestSignature = Sha256.pipe(Schema.brand(\"ignotum/runtime/RequestSignature\"));\nconst RuntimeRequestHeaders = Schema.Struct({\n\tappId: AppId,\n\tdeploymentId: Schema.optional(DeploymentId),\n\tnonce: RuntimeRequestNonce,\n\ttimestamp: RuntimeRequestTimestamp,\n\tsignature: RuntimeRequestSignature\n});\nconst RuntimeSigningInput = Schema.Struct({\n\tmethod: Schema.Literal(\"POST\"),\n\tpath: RuntimeRequestPath,\n\ttimestamp: RuntimeRequestTimestamp,\n\tnonce: RuntimeRequestNonce,\n\tappId: AppId,\n\tdeploymentId: Schema.optional(DeploymentId),\n\tbodySha256: Sha256\n});\nconst runtimeRequestHeaderNames = {\n\tappId: \"x-ignotum-app-id\",\n\tdeploymentId: \"x-ignotum-deployment-id\",\n\tnonce: \"x-ignotum-nonce\",\n\tsignature: \"x-ignotum-signature\",\n\ttimestamp: \"x-ignotum-timestamp\"\n};\nconst appSyncRequestHeaderNames = {\n\tdeploymentId: \"x-ignotum-deployment-id\",\n\tgeneration: \"x-ignotum-deployment-generation\"\n};\nconst runtimeRequestMaxSkewMillis = 3e4;\nconst RuntimeIndexRequest = Schema.Struct({\n\tappId: AppId,\n\tdeploymentId: DeploymentId\n});\nconst RuntimeIndexResult = Schema.Struct({ completed: Schema.Literal(true) });\nconst encodeRuntimeSigningInput = (input) => encodeCanonicalJson(input.deploymentId === void 0 ? {\n\tappId: input.appId,\n\tbodySha256: input.bodySha256,\n\tmethod: input.method,\n\tnonce: input.nonce,\n\tpath: input.path,\n\ttimestamp: input.timestamp\n} : {\n\tappId: input.appId,\n\tbodySha256: input.bodySha256,\n\tdeploymentId: input.deploymentId,\n\tmethod: input.method,\n\tnonce: input.nonce,\n\tpath: input.path,\n\ttimestamp: input.timestamp\n});\nconst RuntimeErrorCode = Schema.Literals([\n\t\"InvalidRequest\",\n\t\"InvalidSignature\",\n\t\"RequestExpired\",\n\t\"RequestReplay\",\n\t\"InvocationRejected\",\n\t\"RuntimeUnavailable\"\n]);\nconst RuntimeErrorResponse = Schema.Struct({\n\tcode: RuntimeErrorCode,\n\tmessage: Schema.String,\n\trejectionCode: Schema.optional(RuntimeInvocationRejectionCode)\n});\n//#endregion\nexport { RuntimeErrorCode, RuntimeErrorResponse, RuntimeIndexRequest, RuntimeIndexResult, RuntimeRequestHeaders, RuntimeRequestNonce, RuntimeRequestPath, RuntimeRequestSignature, RuntimeRequestTimestamp, RuntimeSigningInput, appSyncPath, appSyncRequestHeaderNames, clientAssetUrlPrefix, encodeRuntimeSigningInput, fileGrantUrlPrefix, fileUploadUrlPrefix, gatewayHealthPath, ignotumPathPrefix, runtimeFileEffectsAcknowledgePath, runtimeFileEffectsPath, runtimeIndexCommitPath, runtimeIndexPreparePath, runtimeInvocationPath, runtimeRequestHeaderNames, runtimeRequestMaxSkewMillis, runtimeRevisionPath };\n\n//# sourceMappingURL=transport.js.map","import { appSyncPath } from \"@ignotum/contracts/runtime/transport\";\n\nexport const ignotumPathPrefix = \"/_ignotum\";\nexport const syncPath = appSyncPath;\n\nexport const isIgnotumPath = (pathname: string): boolean =>\n pathname === ignotumPathPrefix || pathname.startsWith(`${ignotumPathPrefix}/`);\n","import { BrowserSession } from \"./id.js\";\nimport {\n Context,\n Deferred,\n Duration,\n Effect,\n Fiber,\n HashMap,\n Layer,\n ManagedRuntime,\n Option,\n Schedule,\n Schema,\n} from \"effect\";\nimport * as Socket from \"effect/unstable/socket/Socket\";\nimport * as BrowserCrypto from \"@effect/platform-browser/BrowserCrypto\";\n\nimport { encodeCanonicalJson } from \"@ignotum/contracts/json\";\nimport { type AppStateRevision } from \"@ignotum/contracts/runtime/hosted\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport { encodeTransportObject } from \"@ignotum/contracts/runtime/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 ClientMessageJson,\n DeploymentCloseCode,\n InvocationId,\n ServerMessageJson,\n SubscriptionId,\n decodeTransportValue,\n type ClientMessage,\n type FunctionAddress,\n type ServerMessage,\n type SyncHandshake,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport {\n ClientInfrastructureError,\n ConnectionUnavailable,\n InvalidClientMessage,\n InvalidServerMessage,\n ServerError,\n InvalidMutationArguments,\n clientErrorReporterLayer,\n reportClientError,\n} from \"./errors.js\";\nimport { syncPath } from \"../internal/http-paths.js\";\nimport { applyFileGrants, prepareMutationArguments } from \"./files.js\";\n\ntype Listener = () => void;\ntype SocketWriter = (chunk: string) => Effect.Effect<void, Socket.SocketError>;\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\ninterface 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<ClientMessage, { readonly type: \"Subscribe\" | \"Unsubscribe\" }>;\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<Extract<ServerMessage, { readonly type: \"Snapshot\" }>[\"files\"]>;\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 shouldReloadForCloseCode = (code: number): boolean => code === DeploymentCloseCode;\n\nconst handshakesMatch = (first: SyncHandshake, next: SyncHandshake): boolean =>\n first.appId === next.appId &&\n first.deploymentId === next.deploymentId &&\n first.generation === next.generation;\n\ntype HandshakeDecision = \"Accept\" | \"Ignore\" | \"Reload\";\n\nconst handshakeDecision = (\n remembered: SyncHandshake | undefined,\n acceptedOnConnection: boolean,\n next: SyncHandshake,\n): HandshakeDecision => {\n if (remembered !== undefined && !handshakesMatch(remembered, next)) return \"Reload\";\n return acceptedOnConnection ? \"Ignore\" : \"Accept\";\n};\n\nexport const syncClientInternals = {\n makeQueryCache,\n handshakeDecision,\n queryIdentity: queryKey,\n resultFromWire,\n handshakesMatch,\n shouldReloadForCloseCode,\n};\n\nconst socketUrl = (): string => {\n const url = new URL(syncPath, globalThis.location.href);\n url.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n return url.href;\n};\n\ninterface 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\ninterface PendingInvocation {\n readonly sessionEpoch: string;\n readonly deferred: Deferred.Deferred<\n IgnotumResult<unknown, ErrorValue>,\n ClientInfrastructureError\n >;\n readonly function: FunctionAddress;\n readonly message: Extract<ClientMessage, { readonly type: \"Invoke\" | \"Prepare\" }>;\n readonly prepared: Deferred.Deferred<\n Extract<ServerMessage, { readonly type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >;\n}\n\nexport class SyncClient extends Context.Service<SyncClient, SyncClientService>()(\n \"ignotum/client/sync/SyncClient\",\n) {\n static readonly layer = Layer.effect(\n SyncClient,\n Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const session = yield* BrowserSession;\n let invocations = HashMap.empty<InvocationId, PendingInvocation>();\n let rememberedHandshake: SyncHandshake | undefined;\n let reloadRequested = false;\n let writer: SocketWriter | undefined;\n let sessionSuspended: Deferred.Deferred<void> | undefined;\n\n const encode = (message: ClientMessage) =>\n Schema.encodeEffect(ClientMessageJson)(message).pipe(\n Effect.mapError((cause) =>\n InvalidClientMessage.make({\n cause,\n message: \"Could not encode an Ignotum sync message.\",\n }),\n ),\n );\n\n const sendWith = (write: SocketWriter, message: ClientMessage) =>\n encode(message).pipe(\n Effect.flatMap(write),\n Effect.mapError((cause) =>\n Schema.is(InvalidClientMessage)(cause)\n ? cause\n : ConnectionUnavailable.make({\n cause,\n message: \"The sync connection was lost.\",\n }),\n ),\n );\n\n const send = (message: ClientMessage) =>\n writer === undefined\n ? Effect.fail(\n ConnectionUnavailable.make({ message: \"The sync connection is not ready.\" }),\n )\n : sendWith(writer, message);\n\n const queryCache = makeQueryCache(ids.generate(SubscriptionId), (message) =>\n writer === undefined\n ? Effect.void\n : send(message).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: reportClientError,\n }),\n ),\n );\n\n const unsubscribeSession = session.subscribe(() => {\n if (session.current() === undefined) {\n queryCache.invalidatePrivate();\n writer = undefined;\n if (sessionSuspended !== undefined) Deferred.doneUnsafe(sessionSuspended, Effect.void);\n }\n });\n yield* Effect.addFinalizer(() => Effect.sync(unsubscribeSession));\n\n const rejectInvocation = (id: InvocationId, error: ClientInfrastructureError) => {\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, id));\n if (pendingInvocation === undefined) {\n return Effect.void;\n }\n invocations = HashMap.remove(invocations, id);\n return reportClientError(error).pipe(\n Effect.andThen(Deferred.fail(pendingInvocation.prepared, error)),\n Effect.andThen(Deferred.fail(pendingInvocation.deferred, error)),\n Effect.asVoid,\n );\n };\n\n const handleMessage = Effect.fn(\"SyncClient.handleMessage\")(function* (\n message: Exclude<ServerMessage, SyncHandshake | { readonly type: \"Deployment\" }>,\n ) {\n switch (message.type) {\n case \"Session\": {\n if (message.event === \"Updated\") {\n const previous = session.current();\n if (previous !== undefined && previous.sessionEpoch !== message.session.sessionEpoch)\n return;\n if (previous?.viewRevision !== message.session.viewRevision)\n queryCache.invalidatePrivate();\n session.accept(message.session, message.serverTime);\n } else {\n if (rememberedHandshake?.session?.sessionEpoch !== message.sessionEpoch) return;\n session.suspend(\n message.event === \"Unavailable\"\n ? \"Your ID session is temporarily unavailable.\"\n : undefined,\n );\n if (message.event !== \"Unavailable\") {\n yield* Effect.forEach(HashMap.keys(invocations), (id) =>\n rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n }\n }\n return;\n }\n case \"Invalidate\": {\n if (message.sessionEpoch === session.current()?.sessionEpoch)\n queryCache.invalidate(message.ids);\n return;\n }\n case \"Snapshot\": {\n const current = session.current();\n if (current === undefined || message.identity?.sessionEpoch !== current.sessionEpoch)\n return;\n if (\n message.identity.dependsOnId &&\n message.identity.viewRevision !== current.viewRevision\n )\n return;\n const entry = queryCache.getById(message.id);\n if (entry === undefined) return;\n entry.dependsOnId = message.identity.dependsOnId;\n if (entry.revision !== undefined && message.revision < entry.revision) return;\n yield* resultFromWire(message.result, message.files ?? []).pipe(\n Effect.tap((result) =>\n Effect.sync(() => queryCache.setResult(message.id, result, message.revision)),\n ),\n Effect.catchTags({\n InvalidServerMessage: (error) => {\n queryCache.setResult(message.id, error, message.revision);\n return reportClientError(error);\n },\n }),\n );\n return;\n }\n case \"Preparation\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, message.id));\n if (pendingInvocation !== undefined) {\n yield* Deferred.succeed(pendingInvocation.prepared, message.uploads);\n }\n return;\n }\n case \"Result\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, message.id));\n if (pendingInvocation === undefined) return;\n yield* resultFromWire(message.result).pipe(\n Effect.flatMap((result) => {\n invocations = HashMap.remove(invocations, message.id);\n return Deferred.succeed(pendingInvocation.deferred, result);\n }),\n Effect.catchTags({\n InvalidServerMessage: (error) => rejectInvocation(message.id, error),\n }),\n );\n return;\n }\n case \"Error\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const error =\n message.operation === undefined\n ? ServerError.make({\n code: message.code,\n message: message.message,\n })\n : ServerError.make({\n code: message.code,\n message: message.message,\n operation: message.operation,\n });\n if (message.operation?.type === \"Invocation\") {\n yield* rejectInvocation(message.operation.id, error);\n } else if (message.operation?.type === \"Subscription\") {\n queryCache.setResult(message.operation.id, error);\n yield* reportClientError(error);\n } else {\n yield* reportClientError(error);\n }\n return;\n }\n }\n });\n\n const requestReload = () => {\n if (reloadRequested) return;\n reloadRequested = true;\n writer = undefined;\n globalThis.location.reload();\n };\n\n const disconnect = Effect.sync(() => {\n writer = undefined;\n });\n\n const connect = Effect.scoped(\n Effect.gen(function* () {\n if (reloadRequested) return yield* Effect.never;\n yield* session.bootstrap.pipe(\n Effect.mapError((error) => ConnectionUnavailable.make({ message: error.message })),\n );\n const socket = yield* Socket.makeWebSocket(\n `${socketUrl()}${session.socketParameters()}`,\n {\n closeCodeIsError: (code) => {\n if (shouldReloadForCloseCode(code)) requestReload();\n return false;\n },\n },\n );\n const write = yield* socket.writer;\n const handshakeReceived = yield* Deferred.make<void>();\n let handshakeAccepted = false;\n const acceptHandshake = Effect.fn(\"SyncClient.acceptHandshake\")(function* (\n handshake: SyncHandshake,\n ) {\n const decision = handshakeDecision(rememberedHandshake, handshakeAccepted, handshake);\n if (decision === \"Reload\") {\n requestReload();\n return;\n }\n if (decision === \"Ignore\") return;\n if (handshake.session === undefined || handshake.serverTime === undefined) {\n requestReload();\n return;\n }\n if (\n rememberedHandshake?.session !== undefined &&\n rememberedHandshake.session.sessionEpoch !== handshake.session.sessionEpoch\n ) {\n queryCache.invalidatePrivate();\n yield* Effect.forEach(HashMap.keys(invocations), (id) =>\n rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n } else if (\n rememberedHandshake?.session?.viewRevision !== handshake.session.viewRevision\n ) {\n queryCache.invalidatePrivate();\n }\n yield* Effect.forEach(HashMap.entries(invocations), ([id, pending]) =>\n pending.sessionEpoch === handshake.session!.sessionEpoch\n ? Effect.void\n : rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n session.accept(handshake.session, handshake.serverTime);\n rememberedHandshake = handshake;\n handshakeAccepted = true;\n writer = write;\n yield* Deferred.succeed(handshakeReceived, undefined);\n yield* Effect.gen(function* () {\n yield* Effect.forEach(queryCache.entries(), (entry) =>\n sendWith(write, subscribeMessage(entry)),\n );\n yield* Effect.forEach(HashMap.values(invocations), (pendingInvocation) =>\n sendWith(write, pendingInvocation.message),\n );\n }).pipe(Effect.tapError(reportClientError), Effect.ignore);\n });\n\n const handleText = Effect.fn(\"SyncClient.handleText\")(function* (text: string) {\n const message = yield* Schema.decodeEffect(ServerMessageJson)(text).pipe(\n Effect.mapError((cause) =>\n InvalidServerMessage.make({\n cause,\n message: \"The server returned an invalid sync message.\",\n }),\n ),\n );\n if (message.type === \"Handshake\") return yield* acceptHandshake(message);\n if (message.type === \"Deployment\") {\n requestReload();\n return;\n }\n if (!handshakeAccepted) {\n return yield* InvalidServerMessage.make({\n cause: new Error(\"The server sent a sync message before the handshake.\"),\n message: \"The server returned a sync message before the handshake.\",\n });\n }\n return yield* handleMessage(message);\n });\n\n const suspended = yield* Deferred.make<void>();\n sessionSuspended = suspended;\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n if (sessionSuspended === suspended) sessionSuspended = undefined;\n }),\n );\n const run = yield* socket.runString(handleText).pipe(Effect.forkChild);\n yield* Effect.raceFirst(\n Deferred.await(handshakeReceived).pipe(Effect.timeout(\"10 seconds\")),\n Fiber.join(run),\n );\n yield* Effect.raceFirst(Fiber.join(run), Deferred.await(suspended));\n }),\n ).pipe(\n Effect.mapError((cause) =>\n Schema.is(ClientInfrastructureError)(cause)\n ? cause\n : ConnectionUnavailable.make({\n cause,\n message: \"The sync connection was lost.\",\n }),\n ),\n Effect.ensuring(disconnect),\n );\n\n const reconnectSchedule = Schedule.exponential(\"250 millis\").pipe(\n Schedule.modifyDelay(({ duration }) =>\n Effect.succeed(Duration.min(duration, Duration.seconds(5))),\n ),\n Schedule.jittered,\n );\n yield* connect.pipe(\n Effect.andThen(\n Effect.fail(\n ConnectionUnavailable.make({\n message: \"The sync connection closed; reconnecting.\",\n }),\n ),\n ),\n Effect.tapError(reportClientError),\n Effect.retry(reconnectSchedule),\n Effect.forkScoped,\n );\n\n const observe: SyncClientService[\"observe\"] = Effect.fn(\"SyncClient.observe\")(\n function* (functionAddress, args) {\n return yield* queryCache.observe(functionAddress, args);\n },\n );\n\n const mutate: SyncClientService[\"mutate\"] = Effect.fn(\"SyncClient.mutate\")(\n function* (functionAddress, args) {\n const admittedSession =\n session.current() ??\n rememberedHandshake?.session ??\n (yield* session.bootstrap.pipe(\n Effect.mapError((error) => ConnectionUnavailable.make({ message: error.message })),\n ));\n const invocationId = yield* ids.generate(InvocationId);\n const preparedArguments = yield* prepareMutationArguments(args).pipe(\n Effect.provideService(IdGenerator, ids),\n Effect.mapError((cause) =>\n InvalidMutationArguments.make({\n cause,\n function: functionAddress,\n message: `Mutation arguments for ${functionAddress} contain an unsupported file or value.`,\n }),\n ),\n Effect.tapError(reportClientError),\n );\n const jsonArgs = yield* Effect.try({\n try: () => encodeTransportObject(preparedArguments.value),\n catch: (cause) =>\n InvalidMutationArguments.make({\n cause,\n function: functionAddress,\n message: `Mutation arguments for ${functionAddress} contain an unsupported value.`,\n }),\n }).pipe(Effect.tapError(reportClientError));\n const deferred = yield* Deferred.make<\n IgnotumResult<unknown, ErrorValue>,\n ClientInfrastructureError\n >();\n const prepared = yield* Deferred.make<\n Extract<ServerMessage, { readonly type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >();\n const invokeMessage: Extract<ClientMessage, { readonly type: \"Invoke\" }> = {\n type: \"Invoke\",\n id: invocationId,\n kind: \"Mutation\",\n function: functionAddress,\n args: jsonArgs,\n };\n const message: PendingInvocation[\"message\"] =\n preparedArguments.fileIds.length === 0\n ? invokeMessage\n : {\n type: \"Prepare\",\n id: invocationId,\n kind: \"Mutation\",\n function: functionAddress,\n args: jsonArgs,\n files: preparedArguments.fileIds,\n };\n invocations = HashMap.set(invocations, invocationId, {\n sessionEpoch: admittedSession.sessionEpoch,\n deferred,\n function: functionAddress,\n message,\n prepared,\n });\n return yield* Effect.gen(function* () {\n if (writer !== undefined) {\n yield* sendWith(writer, message).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: (error) => rejectInvocation(invocationId, error),\n }),\n );\n }\n if (message.type === \"Prepare\") {\n const uploads = yield* Deferred.await(prepared);\n const expected = new Set(message.files);\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 = preparedArguments.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 const pendingInvocation = Option.getOrUndefined(\n HashMap.get(invocations, invocationId),\n );\n if (pendingInvocation === undefined) return yield* Deferred.await(deferred);\n invocations = HashMap.set(invocations, invocationId, {\n ...pendingInvocation,\n message: invokeMessage,\n });\n if (writer !== undefined) {\n yield* sendWith(writer, invokeMessage).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: (error) => rejectInvocation(invocationId, error),\n }),\n );\n }\n }\n return yield* Deferred.await(deferred);\n }).pipe(\n Effect.tapError(() =>\n Effect.sync(() => {\n invocations = HashMap.remove(invocations, invocationId);\n }),\n ),\n );\n },\n );\n\n return SyncClient.of({ mutate, observe });\n }),\n ).pipe(Layer.provide(Layer.merge(Socket.layerWebSocketConstructorGlobal, BrowserCrypto.layer)));\n}\n\nexport const syncRuntime = ManagedRuntime.make(\n SyncClient.layer.pipe(\n Layer.provideMerge(BrowserSession.layer),\n Layer.provideMerge(clientErrorReporterLayer),\n Layer.provideMerge(IdGenerator.layer),\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\";\n\nimport type { FunctionAddress } from \"@ignotum/contracts/runtime/sync\";\nimport { SyncClient, syncClientInternals } from \"./sync.js\";\nimport type { ClientInfrastructureError } from \"./errors.js\";\n\ntype QueryObserver = Effect.Success<ReturnType<SyncClient[\"Service\"][\"observe\"]>>;\n\ninterface PageEntry {\n readonly acquire: Effect.Effect<QueryObserver | undefined, ClientInfrastructureError, SyncClient>;\n release: (() => void) | undefined;\n released: boolean;\n}\n\n// @effect-diagnostics-next-line missingPipeableSignature:off This hook-owned lifecycle takes two callbacks, not a data argument.\nexport const makePageObservers = (\n onChange: () => void,\n releaseObserver: (release: Effect.Effect<void>) => void,\n) => {\n const pages = new Map<string, PageEntry>();\n let disposed = false;\n\n const releaseEntry = (entry: PageEntry) => {\n entry.released = true;\n entry.release?.();\n };\n\n const observe = Effect.fn(\"PageObservers.observe\")(function* (\n functionAddress: FunctionAddress,\n args: Schema.Json,\n ) {\n if (disposed) return;\n const key = syncClientInternals.queryIdentity(functionAddress, args);\n const existing = pages.get(key);\n if (existing !== undefined) return yield* existing.acquire;\n\n const entry: PageEntry = {\n acquire: yield* Effect.cached(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n const observer = yield* client.observe(functionAddress, args);\n if (entry.released) {\n releaseObserver(observer.release);\n return;\n }\n const unsubscribe = observer.subscribe(onChange);\n entry.release = () => {\n unsubscribe();\n releaseObserver(observer.release);\n };\n return observer;\n }),\n ),\n release: undefined,\n released: false,\n };\n pages.set(key, entry);\n return yield* entry.acquire;\n });\n\n return {\n observe,\n retain: (keys: ReadonlySet<string>) => {\n for (const [key, entry] of pages) {\n if (keys.has(key)) continue;\n pages.delete(key);\n releaseEntry(entry);\n }\n },\n release: () => {\n if (disposed) return;\n disposed = true;\n for (const entry of pages.values()) releaseEntry(entry);\n pages.clear();\n },\n };\n};\n","import { BrowserSession, type IdState } from \"./id.js\";\nimport type { ProfileField } from \"@ignotum/contracts/id\";\nimport { Effect, Schema } from \"effect\";\nimport { useCallback, useDebugValue, useEffect, useMemo, useState } from \"preact/hooks\";\n\nimport { functionPathOf, type FunctionReference } from \"../internal/api.js\";\nimport { inspectResult, pending, Result as RuntimeResult } from \"@ignotum/contracts/runtime/result\";\nimport type { ErrorValue, QueryResult, SettledResult } from \"@ignotum/contracts/runtime/result\";\nimport {\n PaginationPageSize,\n type PaginationOptions,\n type PaginationPage,\n} from \"@ignotum/contracts/runtime/pagination\";\nimport { encodeTransportObject } from \"@ignotum/contracts/runtime/sync\";\nimport { ClientInfrastructureError } from \"./errors.js\";\nimport { isQuerySkip, type QuerySkip } from \"./query.js\";\n// oxlint-disable-next-line anti-slop-effect/no-service-constructor-imports -- Each mounted pagination hook owns and releases its page observers.\nimport { makePageObservers } from \"./page-observers.js\";\nimport { SyncClient, syncClientInternals, syncRuntime } from \"./sync.js\";\n\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks are not pipeable functions.\nexport function useQuery<Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", void, Success, Failure>,\n): QueryResult<Success, Failure>;\nexport function useQuery<Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", void, Success, Failure>,\n args: QuerySkip,\n): QueryResult<Success, Failure>;\nexport function useQuery<Args extends object, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args, Success, Failure>,\n args: NoInfer<Args> | QuerySkip,\n): QueryResult<Success, Failure>;\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks must remain direct calls so hook order is statically visible.\nexport function useQuery<Args extends object, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args | void, Success, Failure>,\n args?: Args | QuerySkip,\n): QueryResult<Success, Failure> {\n const functionPath = functionPathOf(reference);\n const skipped = isQuerySkip(args);\n const input = args === undefined || skipped ? {} : args;\n const jsonArgs = encodeTransportObject(input);\n const identity = skipped\n ? `skip:${functionPath}`\n : syncClientInternals.queryIdentity(functionPath, jsonArgs);\n const [state, setState] = useState<{\n readonly identity: string;\n readonly result: QueryResult<Success, Failure> | ClientInfrastructureError;\n }>(() => ({ identity, result: pending() }));\n\n useDebugValue({ args: input, function: functionPath, result: state.result });\n useEffect(() => {\n if (skipped) return;\n\n let active = true;\n let release: (() => void) | undefined;\n\n void syncRuntime\n .runPromise(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n return yield* client.observe(functionPath, jsonArgs);\n }),\n )\n .then(\n (observer) => {\n if (!active) {\n syncRuntime.runFork(observer.release);\n return;\n }\n const update = () => {\n // SAFETY: the function reference couples this subscription's runtime\n // path to its generated success and failure types.\n const result = observer.getSnapshot() as\n | QueryResult<Success, Failure>\n | ClientInfrastructureError;\n setState({ identity, result });\n };\n release = observer.subscribe(update);\n update();\n const releaseObserver = release;\n release = () => {\n releaseObserver();\n syncRuntime.runFork(observer.release);\n };\n },\n (error) => {\n if (active && Schema.is(ClientInfrastructureError)(error)) {\n setState({ identity, result: error });\n }\n },\n );\n\n return () => {\n active = false;\n release?.();\n };\n }, [identity]);\n\n if (skipped) return pending();\n\n if (state.identity !== identity) {\n return pending();\n }\n\n const result = state.result;\n if (Schema.is(ClientInfrastructureError)(result)) throw result;\n return result;\n}\n\nexport type PaginationStatus = \"CanLoadMore\" | \"Exhausted\" | \"LoadingMore\";\n\nexport interface PaginatedQueryValue<Item> {\n readonly items: ReadonlyArray<Item>;\n readonly loadMore: () => void;\n readonly status: PaginationStatus;\n}\n\nexport interface PaginatedQueryOptions {\n readonly pageSize?: number;\n}\n\ntype PaginationArguments = { readonly pagination: PaginationOptions };\ntype ApplicationPaginationArguments<Args extends PaginationArguments> = Omit<Args, \"pagination\">;\n\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks are not pipeable functions.\nexport function usePaginatedQuery<\n Args extends PaginationArguments,\n Item,\n Failure extends ErrorValue,\n>(\n reference: keyof ApplicationPaginationArguments<Args> extends never\n ? FunctionReference<\"Query\", Args, PaginationPage<Item>, Failure>\n : never,\n): QueryResult<PaginatedQueryValue<Item>, Failure>;\nexport function usePaginatedQuery<\n Args extends PaginationArguments,\n Item,\n Failure extends ErrorValue,\n>(\n reference: FunctionReference<\"Query\", Args, PaginationPage<Item>, Failure>,\n args: NoInfer<ApplicationPaginationArguments<Args>> | QuerySkip,\n options?: PaginatedQueryOptions,\n): QueryResult<PaginatedQueryValue<Item>, Failure>;\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks must remain direct calls so hook order is statically visible.\nexport function usePaginatedQuery<Args extends object, Item, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args & PaginationArguments, PaginationPage<Item>, Failure>,\n args?: Args | QuerySkip,\n options: PaginatedQueryOptions = {},\n): QueryResult<PaginatedQueryValue<Item>, Failure> {\n const functionPath = functionPathOf(reference);\n const skipped = isQuerySkip(args);\n const input = args === undefined || skipped ? {} : args;\n const jsonArgs = encodeTransportObject(input);\n const pageSize = Schema.decodeSync(PaginationPageSize)(options.pageSize ?? 20);\n const identity = skipped\n ? `skip:${functionPath}`\n : syncClientInternals.queryIdentity(functionPath, jsonArgs);\n const [requestedPages, setRequestedPages] = useState(1);\n const [refresh, setRefresh] = useState(0);\n const [state, setState] = useState<{\n readonly identity: string;\n readonly result: QueryResult<PaginatedQueryValue<Item>, Failure> | ClientInfrastructureError;\n }>(() => ({ identity, result: pending() }));\n const loadMore = useCallback(() => setRequestedPages((count) => count + 1), []);\n const pages = useMemo(\n () =>\n makePageObservers(\n () => setRefresh((version) => version + 1),\n (release) => {\n syncRuntime.runFork(release);\n },\n ),\n [identity, pageSize],\n );\n\n useEffect(() => () => pages.release(), [pages]);\n\n useDebugValue({ args: input, function: functionPath, result: state.result });\n\n useEffect(() => {\n setRequestedPages(1);\n setState({ identity, result: pending() });\n }, [identity, pageSize]);\n\n useEffect(() => {\n if (skipped) return;\n\n let active = true;\n const usedPages = new Set<string>();\n\n void syncRuntime\n .runPromise(\n Effect.gen(function* () {\n const items: Item[] = [];\n let cursor: PaginationOptions[\"cursor\"] = null;\n\n for (let pageNumber = 0; pageNumber < requestedPages; pageNumber += 1) {\n const pageArgs = encodeTransportObject({\n ...input,\n pagination: { cursor, pageSize },\n });\n usedPages.add(syncClientInternals.queryIdentity(functionPath, pageArgs));\n const observer = yield* pages.observe(functionPath, pageArgs);\n if (!active || observer === undefined) return;\n\n const snapshot = observer.getSnapshot();\n if (Schema.is(ClientInfrastructureError)(snapshot)) {\n setState({ identity, result: snapshot });\n return;\n }\n const inspected = inspectResult(snapshot);\n if (inspected === undefined) {\n setState({\n identity,\n result:\n items.length === 0\n ? pending()\n : RuntimeResult.succeed({ items, loadMore, status: \"LoadingMore\" }),\n });\n return;\n }\n if (inspected.type === \"Failure\") {\n // SAFETY: pagination changes only the successful value. The\n // failure channel is the generated query reference's Failure.\n setState({\n identity,\n result: snapshot as QueryResult<PaginatedQueryValue<Item>, Failure>,\n });\n return;\n }\n // SAFETY: the generated reference and values.page validator couple\n // this successful snapshot to PaginationPage<Item>.\n const page = inspected.value as PaginationPage<Item>;\n items.push(...page.items);\n cursor = page.nextCursor;\n if (cursor === null) {\n setState({\n identity,\n result: RuntimeResult.succeed({ items, loadMore, status: \"Exhausted\" }),\n });\n return;\n }\n }\n\n setState({\n identity,\n result: RuntimeResult.succeed({ items, loadMore, status: \"CanLoadMore\" }),\n });\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (active) pages.retain(usedPages);\n }),\n ),\n ),\n )\n .catch((error) => {\n if (active && Schema.is(ClientInfrastructureError)(error)) {\n setState({ identity, result: error });\n }\n });\n\n return () => {\n active = false;\n };\n }, [functionPath, identity, loadMore, pageSize, pages, refresh, requestedPages, skipped]);\n\n if (skipped || state.identity !== identity) return pending();\n const result = state.result;\n if (Schema.is(ClientInfrastructureError)(result)) throw result;\n return result;\n}\n\ntype Mutation<Args, Success, Failure extends ErrorValue> = [Args] extends [void]\n ? () => Promise<SettledResult<Success, Failure>>\n : (args: Args) => Promise<SettledResult<Success, Failure>>;\n\nexport const useMutation = <Args extends object | void, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Mutation\", Args, Success, Failure>,\n): Mutation<Args, Success, Failure> =>\n useMemo(() => {\n const mutate = (args: Args | undefined) => {\n const functionPath = functionPathOf(reference);\n const input = args === undefined ? {} : args;\n return syncRuntime.runPromise<SettledResult<Success, Failure>, ClientInfrastructureError>(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n // SAFETY: generated function references bind the runtime path to the\n // declared public result types validated by the server executor.\n // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- The untyped sync transport deliberately erases the generated reference's result parameters.\n return (yield* client.mutate(functionPath, input)) as unknown as SettledResult<\n Success,\n Failure\n >;\n }),\n );\n };\n // SAFETY: the builder gives argument-free functions Args = void. At runtime\n // both call shapes normalize omitted arguments to the empty JSON object.\n return mutate as Mutation<Args, Success, Failure>;\n }, [reference]);\n\nexport type IdOptions = {\n readonly profile?: ReadonlyArray<ProfileField>;\n readonly returnTo?: string;\n};\nexport type IdResult = IdState & {\n readonly signIn: (options?: IdOptions) => Promise<void>;\n readonly requestProfile: (\n fields: ReadonlyArray<ProfileField>,\n options?: { readonly returnTo?: string },\n ) => Promise<void>;\n readonly signOut: () => Promise<void>;\n};\n\nexport function useId(): IdResult {\n const [state, setState] = useState<IdState>({ status: \"pending\" });\n useEffect(() => {\n let active = true;\n let unsubscribe: (() => void) | undefined;\n void syncRuntime.runPromise(BrowserSession).then((session) => {\n if (!active) return;\n const update = () => setState(session.snapshot());\n unsubscribe = session.subscribe(update);\n update();\n });\n return () => {\n active = false;\n unsubscribe?.();\n };\n }, []);\n const actions = useMemo(\n () => ({\n signIn: (options?: IdOptions) =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).start(\n \"signIn\",\n options?.profile ?? [],\n options?.returnTo,\n );\n }),\n ),\n requestProfile: (\n fields: ReadonlyArray<ProfileField>,\n options?: { readonly returnTo?: string },\n ) =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).start(\n \"requestProfile\",\n fields,\n options?.returnTo,\n );\n }),\n ),\n signOut: () =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).signOut;\n }),\n ),\n }),\n [],\n );\n return { ...state, ...actions };\n}\n","import type { ComponentType } from \"preact\";\n\nexport interface AppDefinition<Component extends ComponentType<{}> = ComponentType<{}>> {\n readonly component: Component;\n readonly title: string;\n}\n\nexport const app = <Component extends ComponentType<{}>>(\n definition: AppDefinition<Component>,\n): AppDefinition<Component> => {\n if (definition.title.trim().length === 0) {\n throw new Error(\"The app title must contain a non-whitespace character.\");\n }\n return definition;\n};\n","import { Result as contractResult } from \"@ignotum/contracts/runtime/result\";\nimport type {\n ErrorValue,\n QueryResult as ContractQueryResult,\n SettledResult,\n} from \"@ignotum/contracts/runtime/result\";\n\nexport const Result = { match: contractResult.match };\nexport type Result<Value, Error extends ErrorValue> = SettledResult<Value, Error>;\nexport type QueryResult<Value, Error extends ErrorValue> = ContractQueryResult<Value, Error>;\nexport type { InternalServerError } from \"@ignotum/contracts/runtime/result\";\nexport type {\n FileFormat,\n FileMetadata,\n FileMimeType,\n FileValue,\n} from \"@ignotum/contracts/schema/file\";\nexport { Files } from \"./files.js\";\nexport { useId, useMutation, usePaginatedQuery, useQuery } from \"./hooks.js\";\nexport type { PaginatedQueryOptions, PaginatedQueryValue, PaginationStatus } from \"./hooks.js\";\nexport { Query } from \"./query.js\";\nexport type { QuerySkip } from \"./query.js\";\nexport { app } from \"./app.js\";\nexport type { AppDefinition } from \"./app.js\";\n\nexport {\n Component,\n Fragment,\n cloneElement,\n createContext,\n createElement,\n createRef,\n h,\n isValidElement,\n toChildArray,\n} from \"preact\";\nexport type {\n AnyComponent,\n Attributes,\n ClassAttributes,\n ComponentChild,\n ComponentChildren,\n ComponentClass,\n ComponentConstructor,\n ComponentFactory,\n ComponentProps,\n ComponentType,\n Consumer,\n Context,\n ContextType,\n ErrorInfo,\n FunctionComponent,\n FunctionalComponent,\n JSX,\n Key,\n PreactContext,\n PreactConsumer,\n PreactDOMAttributes,\n PreactProvider,\n Provider,\n Ref,\n RefCallback,\n RefObject,\n RenderableProps,\n TargetedAnimationEvent,\n TargetedClipboardEvent,\n TargetedCommandEvent,\n TargetedCompositionEvent,\n TargetedDragEvent,\n TargetedEvent,\n TargetedFocusEvent,\n TargetedInputEvent,\n TargetedKeyboardEvent,\n TargetedMouseEvent,\n TargetedPictureInPictureEvent,\n TargetedPointerEvent,\n TargetedSnapEvent,\n TargetedSubmitEvent,\n TargetedToggleEvent,\n TargetedTouchEvent,\n TargetedTransitionEvent,\n TargetedUIEvent,\n TargetedWheelEvent,\n VNode,\n} from \"preact\";\nexport {\n useCallback,\n useContext,\n useDebugValue,\n useEffect,\n useErrorBoundary,\n useId as useElementId,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n} from \"preact/hooks\";\nexport type { Dispatch, Reducer, StateUpdater } from \"preact/hooks\";\n\nexport type { User, UserId, ProfileField } from \"@ignotum/contracts/id\";\nexport type { IdResult, IdOptions } from \"./hooks.js\";\n"],"mappings":";;;;;;;;;;;AAIA,MAAM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Y,CAAC,IAAI;EACxC,OAAO,YAAY,WACjB,OAAO,IAAI,aAAa;GAKtB,OAAQ,QAAO,OAJO,WAAA,CAIA,OAAO,cAAc,KAAK;EAIlD,CAAC,CACH;CACF;CAGA,OAAO;AACT,GAAG,CAAC,SAAS,CAAC;AAehB,SAAgB,QAAkB;CAChC,MAAM,CAAC,OAAO,YAAYF,WAAkB,EAAE,QAAQ,UAAU,CAAC;CACjE,kBAAgB;EACd,IAAI,SAAS;EACb,IAAI;EACJ,YAAiB,WAAW,cAAc,CAAC,CAAC,MAAM,YAAY;GAC5D,IAAI,CAAC,QAAQ;GACb,MAAM,eAAe,SAAS,QAAQ,SAAS,CAAC;GAChD,cAAc,QAAQ,UAAU,MAAM;GACtC,OAAO;EACT,CAAC;EACD,aAAa;GACX,SAAS;GACT,cAAc;EAChB;CACF,GAAG,CAAC,CAAC;CACL,MAAM,UAAUE,iBACP;EACL,SAAS,YACP,YAAY,WACV,OAAO,IAAI,aAAa;GACtB,OAAO,QAAQ,OAAO,eAAA,CAAgB,MACpC,UACA,SAAS,WAAW,CAAC,GACrB,SAAS,QACX;EACF,CAAC,CACH;EACF,iBACE,QACA,YAEA,YAAY,WACV,OAAO,IAAI,aAAa;GACtB,OAAO,QAAQ,OAAO,eAAA,CAAgB,MACpC,kBACA,QACA,SAAS,QACX;EACF,CAAC,CACH;EACF,eACE,YAAY,WACV,OAAO,IAAI,aAAa;GACtB,OAAO,QAAQ,OAAO,eAAA,CAAgB;EACxC,CAAC,CACH;CACJ,IACA,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAQ;AAChC;;;ACvWA,MAAa,OACX,eAC6B;CAC7B,IAAI,WAAW,MAAM,KAAK,CAAC,CAAC,WAAW,GACrC,MAAM,IAAI,MAAM,wDAAwD;CAE1E,OAAO;AACT;;;ACPA,MAAa,SAAS,EAAE,OAAOE,SAAe,MAAM"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["Array","Result","useState","useCallback","useMemo","RuntimeResult","contractResult"],"sources":["../../../shared/dist/id.js","../../src/client/files.ts","../../../contracts/dist/json.js","../../src/client/id.ts","../../src/client/errors.ts","../../src/client/query.ts","../../../contracts/dist/runtime/index.js","../../../contracts/dist/runtime/hosted.js","../../../contracts/dist/runtime/functions.js","../../../contracts/dist/deployment.js","../../../contracts/dist/runtime/transport.js","../../src/internal/http-paths.ts","../../src/client/sync.ts","../../src/client/page-observers.ts","../../src/client/hooks.ts","../../src/client/app.ts","../../src/client/index.ts"],"sourcesContent":["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 { 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","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","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 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 };\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","/** @effect-diagnostics globalConsole:skip-file */\nimport { Cause, Effect, ErrorReporter, Schema } from \"effect\";\n\nimport { ErrorCode, FunctionAddress, Operation } 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 InvalidClientMessage extends Schema.TaggedError<InvalidClientMessage>()(\n \"InvalidClientMessage\",\n {\n cause: Schema.Defect(),\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: ErrorCode,\n message: Schema.String,\n operation: Schema.optional(Operation),\n}) {}\n\nexport const ClientInfrastructureError = Schema.Union([\n ConnectionUnavailable,\n InvalidClientMessage,\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","const QuerySkipTypeId: unique symbol = Symbol.for(\"ignotum/client/QuerySkip\");\n\nexport interface QuerySkip {\n readonly [QuerySkipTypeId]: typeof QuerySkipTypeId;\n}\n\nclass QuerySkipToken implements QuerySkip {\n readonly [QuerySkipTypeId]: typeof QuerySkipTypeId = QuerySkipTypeId;\n}\n\nconst skip: QuerySkip = Object.freeze(new QuerySkipToken());\n\nexport const Query = { skip };\n\nexport const isQuerySkip = <Value extends object | undefined>(\n value: Value,\n): value is Value & QuerySkip => value === skip;\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 { encodeCanonicalJson } from \"../json.js\";\nimport { AppId, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, ConnectionId, DeploymentId, DevDatabaseLockId, GeneratedId, InvocationId, PlatformPrincipalId, RequestId, RuntimeRequestNonce, SubscriptionId, TableId, TeamId } from \"./id.js\";\nimport { FileId, RuntimeFileMetadata, RuntimeFileOccurrence } from \"../schema/file.js\";\nimport { SessionState } from \"../id.js\";\nimport { AppStateRevision, DeploymentGeneration, InvocationKey } from \"./identity.js\";\nimport { FunctionAddress, WireFailure, WireResult, WireSuccess } from \"./sync.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\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});\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 InvocationBase = {\n\tappId: AppId,\n\tdeploymentId: DeploymentId,\n\tgeneration: DeploymentGeneration,\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\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 RuntimeDeploymentUnavailable = class extends Schema.TaggedError()(\"RuntimeDeploymentUnavailable\", {\n\tdeploymentId: DeploymentId,\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\tRuntimeDeploymentUnavailable,\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 = (deploymentId, functionAddress, args) => QueryKey.make(encodeCanonicalJson([\n\tdeploymentId,\n\tfunctionAddress,\n\targs\n]));\nconst canonicalInvocationInput = (deploymentId, functionKind, functionAddress, args, sessionEpoch) => encodeCanonicalJson(sessionEpoch === void 0 ? [\n\tdeploymentId,\n\tfunctionKind,\n\tfunctionAddress,\n\targs\n] : [\n\tdeploymentId,\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 { AppId, AppStateRevision, AuthAccountId, AuthDeviceCodeId, AuthInternalId, AuthInvitationId, AuthMemberId, AuthSessionId, AuthVerificationId, ConnectionId, DependencyKey, DependencySet, DeploymentGeneration, DeploymentId, DevDatabaseLockId, DocumentDependency, FileEffectBatch, FileEffectsAcknowledgeRequest, FileEffectsAcknowledgeResult, FileEffectsRequest, FileEffectsResult, FileReferenceAdded, FileReferenceEffect, FileReferenceRemoved, IdDependency, IndexPointInvalidation, IndexRangeDependency, InvalidationSet, InvocationId, InvocationKey, MutationInvocation, PlatformPrincipalId, QueryInvocation, QueryKey, ReadDependency, RequestId, RevisionCheck, RevisionCheckResult, RuntimeDeploymentUnavailable, RuntimeInvocation, RuntimeInvocationRejected, RuntimeInvocationRejectionCode, RuntimeInvocationResult, RuntimeInvocationUnavailable, RuntimeMutationFailure, RuntimeMutationResult, RuntimeMutationSuccess, RuntimeQueryResult, RuntimeRequestNonce, RuntimeRevisionRejected, RuntimeTransportError, SubscriptionId, TableDependency, TableId, TeamId, WriteInvalidation, canonicalInvocationInput, canonicalQueryKey, dependencyKey, documentDependency, indexPointInvalidation, indexRangeDependency, mutationInvocationKey, tableDependency };\n\n//# sourceMappingURL=hosted.js.map","import { FunctionAddress } from \"./sync.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/functions.ts\nconst FunctionKind = Schema.Literals([\"Mutation\", \"Query\"]);\nvar UnknownFunction = class extends Schema.TaggedError()(\"UnknownFunction\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar WrongFunctionKind = class extends Schema.TaggedError()(\"WrongFunctionKind\", {\n\tactual: FunctionKind,\n\texpected: FunctionKind,\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar InvalidArguments = class extends Schema.TaggedError()(\"InvalidArguments\", {\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\nvar FunctionUnavailable = class extends Schema.TaggedError()(\"FunctionUnavailable\", {\n\tcause: Schema.Defect(),\n\tfunction: FunctionAddress,\n\tmessage: Schema.String\n}) {};\n//#endregion\nexport { FunctionKind, FunctionUnavailable, InvalidArguments, UnknownFunction, WrongFunctionKind };\n\n//# sourceMappingURL=functions.js.map","import { initial, upgrade } from \"./versioned.js\";\nimport { FunctionAddress } from \"./runtime/sync.js\";\nimport { FunctionKind } from \"./runtime/functions.js\";\nimport { t as ValueDescriptor } from \"./descriptor-DCCz5AHd.js\";\nimport { Schema } from \"effect\";\n//#region src/deployment.ts\nconst ArtifactPath = Schema.String.check(Schema.isPattern(/^(?!\\/)(?![A-Za-z]:\\/)(?!.*(?:^|\\/)\\.\\.(?:\\/|$))(?!.*(?:^|\\/)\\.(?:\\/|$))(?!.*\\/\\/)[^\\\\\\0]+$/)).pipe(Schema.brand(\"ignotum/deployment/ArtifactPath\"));\nconst ClientPath = Schema.String.check(Schema.isPattern(/^\\/(?!_ignotum(?:\\/|$))(?:(?:[A-Za-z0-9._~-]+\\/)*[A-Za-z0-9._~-]+\\/?)?$/)).pipe(Schema.brand(\"ignotum/deployment/ClientPath\"));\nconst Sha256 = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/)).pipe(Schema.brand(\"ignotum/deployment/Sha256\"));\nconst ArtifactKind = Schema.Literals([\n\t\"ClientAsset\",\n\t\"ClientDocument\",\n\t\"ClientManifest\",\n\t\"ClientPublicFile\",\n\t\"ClientShell\",\n\t\"FunctionBundle\",\n\t\"ServerManifest\",\n\t\"ServerEnvironment\",\n\t\"SourceMap\",\n\t\"SchemaSnapshot\"\n]);\nconst ArtifactReference = Schema.Struct({\n\tpath: ArtifactPath,\n\tsize: Schema.Natural,\n\tsha256: Sha256\n});\nconst ArtifactFile = Schema.Struct({\n\tpath: ArtifactPath,\n\tsize: Schema.Natural,\n\tsha256: Sha256,\n\tkind: ArtifactKind,\n\tcontentType: Schema.String,\n\tcontentEncoding: Schema.optional(Schema.String)\n});\nconst ClientRoute = Schema.Struct({\n\tpathname: ClientPath,\n\tartifact: ArtifactReference\n});\nconst DeploymentInventoryV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tfiles: Schema.Array(ArtifactFile)\n});\nconst DeploymentInventoryV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\tfiles: Schema.Array(ArtifactFile)\n});\nconst DeploymentInventory = upgrade(initial(DeploymentInventoryV1), DeploymentInventoryV2, (inventory) => ({\n\tformatVersion: 2,\n\tfiles: inventory.files\n}));\nconst ClientManifestV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tshell: ArtifactReference,\n\troutes: Schema.Array(ClientRoute)\n});\nconst ClientManifest = initial(ClientManifestV1);\nconst ClientRoutingRoute = Schema.Struct({\n\tpathname: ClientPath,\n\tartifact: ArtifactPath\n});\nconst ClientRoutingV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tshell: ArtifactPath,\n\troutes: Schema.Array(ClientRoutingRoute)\n});\nconst ClientRouting = initial(ClientRoutingV1);\nconst SchemaSnapshotField = Schema.Struct({\n\tname: Schema.String,\n\tvalue: ValueDescriptor\n});\nconst EnvironmentArtifactV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tnonce: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]{43}$/)),\n\tvalues: Schema.Record(Schema.String, Schema.String)\n});\nconst EnvironmentArtifact = initial(EnvironmentArtifactV1);\nconst ServerEnvironmentArtifact = Schema.Struct({\n\tartifact: ArtifactReference,\n\tfields: Schema.Array(SchemaSnapshotField)\n});\nconst SchemaSnapshotIndex = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(Schema.String)\n});\nconst SchemaSnapshotTableV1 = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(SchemaSnapshotField)\n});\nconst SchemaSnapshotV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\ttables: Schema.Array(SchemaSnapshotTableV1)\n});\nconst SchemaSnapshotTable = Schema.Struct({\n\tname: Schema.String,\n\tfields: Schema.Array(SchemaSnapshotField),\n\tindexes: Schema.Array(SchemaSnapshotIndex)\n});\nconst SchemaSnapshotV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\ttables: Schema.Array(SchemaSnapshotTable)\n});\nconst SchemaSnapshot = upgrade(initial(SchemaSnapshotV1), SchemaSnapshotV2, (snapshot) => ({\n\tformatVersion: 2,\n\ttables: snapshot.tables.map((table) => ({\n\t\t...table,\n\t\tindexes: []\n\t}))\n}));\nconst ServerFunctionArtifactV1 = Schema.Struct({\n\taddress: FunctionAddress,\n\tkind: FunctionKind,\n\tbundle: ArtifactReference,\n\tsourceMap: ArtifactReference\n});\nconst ServerFunctionArtifact = Schema.Struct({\n\taddress: FunctionAddress,\n\tkind: FunctionKind,\n\targs: Schema.optional(ValueDescriptor),\n\treturns: Schema.optional(ValueDescriptor),\n\terrors: Schema.optional(ValueDescriptor),\n\tbundle: ArtifactReference,\n\tsourceMap: ArtifactReference\n});\nconst ServerBuildManifestV1 = Schema.Struct({\n\tformatVersion: Schema.Literal(1),\n\tschema: ArtifactReference,\n\tfunctions: Schema.Array(ServerFunctionArtifactV1)\n});\nconst ServerBuildManifestV2 = Schema.Struct({\n\tformatVersion: Schema.Literal(2),\n\tschema: ArtifactReference,\n\tfunctions: Schema.Array(ServerFunctionArtifact)\n});\nconst ServerBuildManifestThroughV2 = upgrade(initial(ServerBuildManifestV1), ServerBuildManifestV2, (manifest) => ({\n\tformatVersion: 2,\n\tschema: manifest.schema,\n\tfunctions: manifest.functions\n}));\nconst ServerBuildManifestV3 = Schema.Struct({\n\tformatVersion: Schema.Literal(3),\n\tschema: ArtifactReference,\n\tenvironment: Schema.optional(ServerEnvironmentArtifact),\n\tfunctions: Schema.Array(ServerFunctionArtifact)\n});\nconst ServerBuildManifestThroughV3 = upgrade(ServerBuildManifestThroughV2, ServerBuildManifestV3, (manifest) => ({\n\tformatVersion: 3,\n\tschema: manifest.schema,\n\tfunctions: manifest.functions\n}));\nconst ServerBuildManifestV4 = Schema.Struct({\n\tformatVersion: Schema.Literal(4),\n\tschema: ArtifactReference,\n\tenvironment: Schema.optional(ServerEnvironmentArtifact),\n\tfunctions: Schema.Array(ServerFunctionArtifact),\n\tschemaEvolution: Schema.optional(Schema.Struct({\n\t\tbundle: ArtifactReference,\n\t\tsourceMap: ArtifactReference\n\t}))\n});\nconst ServerBuildManifest = upgrade(ServerBuildManifestThroughV3, ServerBuildManifestV4, (manifest) => ({\n\t...manifest,\n\tformatVersion: 4\n}));\nconst deploymentInventoryPath = ArtifactPath.make(\"inventory.json\");\nconst clientManifestPath = ArtifactPath.make(\"client/manifest.json\");\nconst clientShellPath = ArtifactPath.make(\"client/shell.html\");\nconst clientAssetDirectory = ArtifactPath.make(\"client/assets\");\nconst clientAssetPathPrefix = `${clientAssetDirectory}/`;\nconst clientRouteDirectory = ArtifactPath.make(\"client/routes\");\nconst clientRoutePathPrefix = `${clientRouteDirectory}/`;\nconst clientPublicFileExtensions = [\n\t\".avif\",\n\t\".gif\",\n\t\".ico\",\n\t\".jpeg\",\n\t\".jpg\",\n\t\".pdf\",\n\t\".png\",\n\t\".webp\"\n];\nconst serverManifestPath = ArtifactPath.make(\"server/manifest.json\");\nconst schemaSnapshotPath = ArtifactPath.make(\"server/schema.json\");\nconst serverEnvironmentPath = ArtifactPath.make(\"server/environment.json\");\nconst deploymentArtifactLimits = {\n\tfileBytes: 16777216,\n\tfileCount: 512,\n\tinventoryBytes: 1048576,\n\tserverBytes: 67108864,\n\ttotalBytes: 134217728\n};\n//#endregion\nexport { ArtifactFile, ArtifactKind, ArtifactPath, ArtifactReference, ClientManifest, ClientPath, ClientRoute, ClientRouting, ClientRoutingRoute, DeploymentInventory, EnvironmentArtifact, SchemaSnapshot, SchemaSnapshotField, SchemaSnapshotIndex, SchemaSnapshotTable, ServerBuildManifest, ServerEnvironmentArtifact, ServerFunctionArtifact, Sha256, clientAssetDirectory, clientAssetPathPrefix, clientManifestPath, clientPublicFileExtensions, clientRouteDirectory, clientRoutePathPrefix, clientShellPath, deploymentArtifactLimits, deploymentInventoryPath, schemaSnapshotPath, serverEnvironmentPath, serverManifestPath };\n\n//# sourceMappingURL=deployment.js.map","import { encodeCanonicalJson } from \"../json.js\";\nimport { AppId, DeploymentId, RuntimeRequestNonce } from \"./id.js\";\nimport { Sha256 } from \"../deployment.js\";\nimport { RuntimeInvocationRejectionCode } from \"./hosted.js\";\nimport { Schema } from \"effect\";\n//#region src/runtime/transport.ts\nconst runtimeInvocationPath = \"/v1/invoke\";\nconst runtimeConsolePath = \"/v1/console/read\";\nconst runtimeRevisionPath = \"/v1/revision\";\nconst runtimeIndexPreparePath = \"/v1/indexes/prepare\";\nconst runtimeIndexCommitPath = \"/v1/indexes/commit\";\nconst runtimeFileEffectsPath = \"/v1/files/effects\";\nconst runtimeFileEffectsAcknowledgePath = \"/v1/files/effects/acknowledge\";\nconst ignotumPathPrefix = \"/_ignotum\";\nconst clientAssetUrlPrefix = `${ignotumPathPrefix}/assets/`;\nconst gatewayHealthPath = `${ignotumPathPrefix}/health`;\nconst appSyncPath = `${ignotumPathPrefix}/v1/sync`;\nconst fileUploadUrlPrefix = `${ignotumPathPrefix}/v1/files/upload/`;\nconst fileGrantUrlPrefix = `${ignotumPathPrefix}/v1/files/grant/`;\nconst RuntimeRequestPath = Schema.Literals([\n\truntimeConsolePath,\n\truntimeInvocationPath,\n\truntimeRevisionPath,\n\truntimeIndexPreparePath,\n\truntimeIndexCommitPath,\n\truntimeFileEffectsPath,\n\truntimeFileEffectsAcknowledgePath\n]);\nconst RuntimeRequestTimestamp = Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)), Schema.brand(\"ignotum/runtime/RequestTimestamp\"));\nconst RuntimeRequestSignature = Sha256.pipe(Schema.brand(\"ignotum/runtime/RequestSignature\"));\nconst RuntimeRequestHeaders = Schema.Struct({\n\tappId: AppId,\n\tdeploymentId: Schema.optional(DeploymentId),\n\tnonce: RuntimeRequestNonce,\n\ttimestamp: RuntimeRequestTimestamp,\n\tsignature: RuntimeRequestSignature\n});\nconst RuntimeSigningInput = Schema.Struct({\n\tmethod: Schema.Literal(\"POST\"),\n\tpath: RuntimeRequestPath,\n\ttimestamp: RuntimeRequestTimestamp,\n\tnonce: RuntimeRequestNonce,\n\tappId: AppId,\n\tdeploymentId: Schema.optional(DeploymentId),\n\tbodySha256: Sha256\n});\nconst runtimeRequestHeaderNames = {\n\tappId: \"x-ignotum-app-id\",\n\tdeploymentId: \"x-ignotum-deployment-id\",\n\tnonce: \"x-ignotum-nonce\",\n\tsignature: \"x-ignotum-signature\",\n\ttimestamp: \"x-ignotum-timestamp\"\n};\nconst appSyncRequestHeaderNames = {\n\tdeploymentId: \"x-ignotum-deployment-id\",\n\tgeneration: \"x-ignotum-deployment-generation\"\n};\nconst runtimeRequestMaxSkewMillis = 3e4;\nconst RuntimeIndexRequest = Schema.Struct({\n\tappId: AppId,\n\tdeploymentId: DeploymentId,\n\tgeneration: Schema.optional(Schema.Natural)\n});\nconst RuntimeIndexResult = Schema.Union([Schema.Struct({ completed: Schema.Literal(true) }), Schema.Struct({\n\tcompleted: Schema.Literal(false),\n\tmessage: Schema.String\n})]);\nconst encodeRuntimeSigningInput = (input) => encodeCanonicalJson(input.deploymentId === void 0 ? {\n\tappId: input.appId,\n\tbodySha256: input.bodySha256,\n\tmethod: input.method,\n\tnonce: input.nonce,\n\tpath: input.path,\n\ttimestamp: input.timestamp\n} : {\n\tappId: input.appId,\n\tbodySha256: input.bodySha256,\n\tdeploymentId: input.deploymentId,\n\tmethod: input.method,\n\tnonce: input.nonce,\n\tpath: input.path,\n\ttimestamp: input.timestamp\n});\nconst RuntimeErrorCode = Schema.Literals([\n\t\"InvalidRequest\",\n\t\"InvalidSignature\",\n\t\"RequestExpired\",\n\t\"RequestReplay\",\n\t\"InvocationRejected\",\n\t\"RuntimeUnavailable\"\n]);\nconst RuntimeErrorResponse = Schema.Struct({\n\tcode: RuntimeErrorCode,\n\tmessage: Schema.String,\n\trejectionCode: Schema.optional(RuntimeInvocationRejectionCode)\n});\n//#endregion\nexport { RuntimeErrorCode, RuntimeErrorResponse, RuntimeIndexRequest, RuntimeIndexResult, RuntimeRequestHeaders, RuntimeRequestNonce, RuntimeRequestPath, RuntimeRequestSignature, RuntimeRequestTimestamp, RuntimeSigningInput, appSyncPath, appSyncRequestHeaderNames, clientAssetUrlPrefix, encodeRuntimeSigningInput, fileGrantUrlPrefix, fileUploadUrlPrefix, gatewayHealthPath, ignotumPathPrefix, runtimeConsolePath, runtimeFileEffectsAcknowledgePath, runtimeFileEffectsPath, runtimeIndexCommitPath, runtimeIndexPreparePath, runtimeInvocationPath, runtimeRequestHeaderNames, runtimeRequestMaxSkewMillis, runtimeRevisionPath };\n\n//# sourceMappingURL=transport.js.map","import { appSyncPath } from \"@ignotum/contracts/runtime/transport\";\n\nexport const ignotumPathPrefix = \"/_ignotum\";\nexport const syncPath = appSyncPath;\n\nexport const isIgnotumPath = (pathname: string): boolean =>\n pathname === ignotumPathPrefix || pathname.startsWith(`${ignotumPathPrefix}/`);\n","import { BrowserSession } from \"./id.js\";\nimport {\n Context,\n Deferred,\n Duration,\n Effect,\n Fiber,\n HashMap,\n Layer,\n ManagedRuntime,\n Option,\n Schedule,\n Schema,\n} from \"effect\";\nimport * as Socket from \"effect/unstable/socket/Socket\";\nimport * as BrowserCrypto from \"@effect/platform-browser/BrowserCrypto\";\n\nimport { encodeCanonicalJson } from \"@ignotum/contracts/json\";\nimport { type AppStateRevision } from \"@ignotum/contracts/runtime/hosted\";\nimport { IdGenerator } from \"@ignotum/shared/id\";\nimport { encodeTransportObject } from \"@ignotum/contracts/runtime/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 ClientMessageJson,\n DeploymentCloseCode,\n InvocationId,\n ServerMessageJson,\n SubscriptionId,\n decodeTransportValue,\n type ClientMessage,\n type FunctionAddress,\n type ServerMessage,\n type SyncHandshake,\n type WireResult,\n} from \"@ignotum/contracts/runtime/sync\";\nimport {\n ClientInfrastructureError,\n ConnectionUnavailable,\n InvalidClientMessage,\n InvalidServerMessage,\n ServerError,\n InvalidMutationArguments,\n clientErrorReporterLayer,\n reportClientError,\n} from \"./errors.js\";\nimport { syncPath } from \"../internal/http-paths.js\";\nimport { applyFileGrants, prepareMutationArguments } from \"./files.js\";\n\ntype Listener = () => void;\ntype SocketWriter = (chunk: string) => Effect.Effect<void, Socket.SocketError>;\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<ClientMessage, { readonly type: \"Subscribe\" | \"Unsubscribe\" }>;\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<Extract<ServerMessage, { readonly type: \"Snapshot\" }>[\"files\"]>;\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 shouldReloadForCloseCode = (code: number): boolean => code === DeploymentCloseCode;\n\nconst handshakesMatch = (first: SyncHandshake, next: SyncHandshake): boolean =>\n first.appId === next.appId &&\n first.deploymentId === next.deploymentId &&\n first.generation === next.generation;\n\ntype HandshakeDecision = \"Accept\" | \"Ignore\" | \"Reload\";\n\nconst handshakeDecision = (\n remembered: SyncHandshake | undefined,\n acceptedOnConnection: boolean,\n next: SyncHandshake,\n): HandshakeDecision => {\n if (remembered !== undefined && !handshakesMatch(remembered, next)) return \"Reload\";\n return acceptedOnConnection ? \"Ignore\" : \"Accept\";\n};\n\nexport const syncClientInternals = {\n makeQueryCache,\n handshakeDecision,\n queryIdentity: queryKey,\n resultFromWire,\n handshakesMatch,\n shouldReloadForCloseCode,\n};\n\nconst socketUrl = (): string => {\n const url = new URL(syncPath, globalThis.location.href);\n url.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n return url.href;\n};\n\ninterface 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\ninterface PendingInvocation {\n readonly sessionEpoch: string;\n readonly deferred: Deferred.Deferred<\n IgnotumResult<unknown, ErrorValue>,\n ClientInfrastructureError\n >;\n readonly function: FunctionAddress;\n readonly message: Extract<ClientMessage, { readonly type: \"Invoke\" | \"Prepare\" }>;\n readonly prepared: Deferred.Deferred<\n Extract<ServerMessage, { readonly type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >;\n}\n\nexport class SyncClient extends Context.Service<SyncClient, SyncClientService>()(\n \"ignotum/client/sync/SyncClient\",\n) {\n static readonly layer = Layer.effect(\n SyncClient,\n Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const session = yield* BrowserSession;\n let invocations = HashMap.empty<InvocationId, PendingInvocation>();\n let rememberedHandshake: SyncHandshake | undefined;\n let reloadRequested = false;\n let writer: SocketWriter | undefined;\n let sessionSuspended: Deferred.Deferred<void> | undefined;\n\n const encode = (message: ClientMessage) =>\n Schema.encodeEffect(ClientMessageJson)(message).pipe(\n Effect.mapError((cause) =>\n InvalidClientMessage.make({\n cause,\n message: \"Could not encode an Ignotum sync message.\",\n }),\n ),\n );\n\n const sendWith = (write: SocketWriter, message: ClientMessage) =>\n encode(message).pipe(\n Effect.flatMap(write),\n Effect.mapError((cause) =>\n Schema.is(InvalidClientMessage)(cause)\n ? cause\n : ConnectionUnavailable.make({\n cause,\n message: \"The sync connection was lost.\",\n }),\n ),\n );\n\n const send = (message: ClientMessage) =>\n writer === undefined\n ? Effect.fail(\n ConnectionUnavailable.make({ message: \"The sync connection is not ready.\" }),\n )\n : sendWith(writer, message);\n\n const queryCache = makeQueryCache(ids.generate(SubscriptionId), (message) =>\n writer === undefined\n ? Effect.void\n : send(message).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: reportClientError,\n }),\n ),\n );\n\n const unsubscribeSession = session.subscribe(() => {\n if (session.current() === undefined) {\n queryCache.invalidatePrivate();\n writer = undefined;\n if (sessionSuspended !== undefined) Deferred.doneUnsafe(sessionSuspended, Effect.void);\n }\n });\n yield* Effect.addFinalizer(() => Effect.sync(unsubscribeSession));\n\n const rejectInvocation = (id: InvocationId, error: ClientInfrastructureError) => {\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, id));\n if (pendingInvocation === undefined) {\n return Effect.void;\n }\n invocations = HashMap.remove(invocations, id);\n return reportClientError(error).pipe(\n Effect.andThen(Deferred.fail(pendingInvocation.prepared, error)),\n Effect.andThen(Deferred.fail(pendingInvocation.deferred, error)),\n Effect.asVoid,\n );\n };\n\n const handleMessage = Effect.fn(\"SyncClient.handleMessage\")(function* (\n message: Exclude<ServerMessage, SyncHandshake | { readonly type: \"Deployment\" }>,\n ) {\n switch (message.type) {\n case \"Session\": {\n if (message.event === \"Updated\") {\n const previous = session.current();\n if (previous !== undefined && previous.sessionEpoch !== message.session.sessionEpoch)\n return;\n if (previous?.viewRevision !== message.session.viewRevision)\n queryCache.invalidatePrivate();\n session.accept(message.session, message.serverTime);\n } else {\n if (rememberedHandshake?.session?.sessionEpoch !== message.sessionEpoch) return;\n session.suspend(\n message.event === \"Unavailable\"\n ? \"Your ID session is temporarily unavailable.\"\n : undefined,\n );\n if (message.event !== \"Unavailable\") {\n yield* Effect.forEach(HashMap.keys(invocations), (id) =>\n rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n }\n }\n return;\n }\n case \"Invalidate\": {\n if (message.sessionEpoch === session.current()?.sessionEpoch)\n queryCache.invalidate(message.ids);\n return;\n }\n case \"Snapshot\": {\n const current = session.current();\n if (current === undefined || message.identity?.sessionEpoch !== current.sessionEpoch)\n return;\n if (\n message.identity.dependsOnId &&\n message.identity.viewRevision !== current.viewRevision\n )\n return;\n const entry = queryCache.getById(message.id);\n if (entry === undefined) return;\n entry.dependsOnId = message.identity.dependsOnId;\n if (entry.revision !== undefined && message.revision < entry.revision) return;\n yield* resultFromWire(message.result, message.files ?? []).pipe(\n Effect.tap((result) =>\n Effect.sync(() => queryCache.setResult(message.id, result, message.revision)),\n ),\n Effect.catchTags({\n InvalidServerMessage: (error) => {\n queryCache.setResult(message.id, error, message.revision);\n return reportClientError(error);\n },\n }),\n );\n return;\n }\n case \"Preparation\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, message.id));\n if (pendingInvocation !== undefined) {\n yield* Deferred.succeed(pendingInvocation.prepared, message.uploads);\n }\n return;\n }\n case \"Result\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const pendingInvocation = Option.getOrUndefined(HashMap.get(invocations, message.id));\n if (pendingInvocation === undefined) return;\n yield* resultFromWire(message.result).pipe(\n Effect.flatMap((result) => {\n invocations = HashMap.remove(invocations, message.id);\n return Deferred.succeed(pendingInvocation.deferred, result);\n }),\n Effect.catchTags({\n InvalidServerMessage: (error) => rejectInvocation(message.id, error),\n }),\n );\n return;\n }\n case \"Error\": {\n if (message.sessionEpoch !== session.current()?.sessionEpoch) return;\n const error =\n message.operation === undefined\n ? ServerError.make({\n code: message.code,\n message: message.message,\n })\n : ServerError.make({\n code: message.code,\n message: message.message,\n operation: message.operation,\n });\n if (message.operation?.type === \"Invocation\") {\n yield* rejectInvocation(message.operation.id, error);\n } else if (message.operation?.type === \"Subscription\") {\n queryCache.setResult(message.operation.id, error);\n yield* reportClientError(error);\n } else {\n yield* reportClientError(error);\n }\n return;\n }\n }\n });\n\n const requestReload = () => {\n if (reloadRequested) return;\n reloadRequested = true;\n writer = undefined;\n globalThis.location.reload();\n };\n\n const disconnect = Effect.sync(() => {\n writer = undefined;\n });\n\n const connect = Effect.scoped(\n Effect.gen(function* () {\n if (reloadRequested) return yield* Effect.never;\n yield* session.bootstrap.pipe(\n Effect.mapError((error) => ConnectionUnavailable.make({ message: error.message })),\n );\n const socket = yield* Socket.makeWebSocket(\n `${socketUrl()}${session.socketParameters()}`,\n {\n closeCodeIsError: (code) => {\n if (shouldReloadForCloseCode(code)) requestReload();\n return false;\n },\n },\n );\n const write = yield* socket.writer;\n const handshakeReceived = yield* Deferred.make<void>();\n let handshakeAccepted = false;\n const acceptHandshake = Effect.fn(\"SyncClient.acceptHandshake\")(function* (\n handshake: SyncHandshake,\n ) {\n const decision = handshakeDecision(rememberedHandshake, handshakeAccepted, handshake);\n if (decision === \"Reload\") {\n requestReload();\n return;\n }\n if (decision === \"Ignore\") return;\n if (handshake.session === undefined || handshake.serverTime === undefined) {\n requestReload();\n return;\n }\n if (\n rememberedHandshake?.session !== undefined &&\n rememberedHandshake.session.sessionEpoch !== handshake.session.sessionEpoch\n ) {\n queryCache.invalidatePrivate();\n yield* Effect.forEach(HashMap.keys(invocations), (id) =>\n rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n } else if (\n rememberedHandshake?.session?.viewRevision !== handshake.session.viewRevision\n ) {\n queryCache.invalidatePrivate();\n }\n yield* Effect.forEach(HashMap.entries(invocations), ([id, pending]) =>\n pending.sessionEpoch === handshake.session!.sessionEpoch\n ? Effect.void\n : rejectInvocation(\n id,\n ServerError.make({\n code: \"SessionChanged\",\n message: \"The session changed. This operation may already have completed.\",\n }),\n ),\n );\n session.accept(handshake.session, handshake.serverTime);\n rememberedHandshake = handshake;\n handshakeAccepted = true;\n writer = write;\n yield* Deferred.succeed(handshakeReceived, undefined);\n yield* Effect.gen(function* () {\n yield* Effect.forEach(queryCache.entries(), (entry) =>\n sendWith(write, subscribeMessage(entry)),\n );\n yield* Effect.forEach(HashMap.values(invocations), (pendingInvocation) =>\n sendWith(write, pendingInvocation.message),\n );\n }).pipe(Effect.tapError(reportClientError), Effect.ignore);\n });\n\n const handleText = Effect.fn(\"SyncClient.handleText\")(function* (text: string) {\n const message = yield* Schema.decodeEffect(ServerMessageJson)(text).pipe(\n Effect.mapError((cause) =>\n InvalidServerMessage.make({\n cause,\n message: \"The server returned an invalid sync message.\",\n }),\n ),\n );\n if (message.type === \"Handshake\") return yield* acceptHandshake(message);\n if (message.type === \"Deployment\") {\n requestReload();\n return;\n }\n if (!handshakeAccepted) {\n return yield* InvalidServerMessage.make({\n cause: new Error(\"The server sent a sync message before the handshake.\"),\n message: \"The server returned a sync message before the handshake.\",\n });\n }\n return yield* handleMessage(message);\n });\n\n const suspended = yield* Deferred.make<void>();\n sessionSuspended = suspended;\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n if (sessionSuspended === suspended) sessionSuspended = undefined;\n }),\n );\n const run = yield* socket.runString(handleText).pipe(Effect.forkChild);\n yield* Effect.raceFirst(\n Deferred.await(handshakeReceived).pipe(Effect.timeout(\"10 seconds\")),\n Fiber.join(run),\n );\n yield* Effect.raceFirst(Fiber.join(run), Deferred.await(suspended));\n }),\n ).pipe(\n Effect.mapError((cause) =>\n Schema.is(ClientInfrastructureError)(cause)\n ? cause\n : ConnectionUnavailable.make({\n cause,\n message: \"The sync connection was lost.\",\n }),\n ),\n Effect.ensuring(disconnect),\n );\n\n const reconnectSchedule = Schedule.exponential(\"250 millis\").pipe(\n Schedule.modifyDelay(({ duration }) =>\n Effect.succeed(Duration.min(duration, Duration.seconds(5))),\n ),\n Schedule.jittered,\n );\n yield* connect.pipe(\n Effect.andThen(\n Effect.fail(\n ConnectionUnavailable.make({\n message: \"The sync connection closed; reconnecting.\",\n }),\n ),\n ),\n Effect.tapError(reportClientError),\n Effect.retry(reconnectSchedule),\n Effect.forkScoped,\n );\n\n const observe: SyncClientService[\"observe\"] = Effect.fn(\"SyncClient.observe\")(\n function* (functionAddress, args) {\n return yield* queryCache.observe(functionAddress, args);\n },\n );\n\n const mutate: SyncClientService[\"mutate\"] = Effect.fn(\"SyncClient.mutate\")(\n function* (functionAddress, args) {\n const admittedSession =\n session.current() ??\n rememberedHandshake?.session ??\n (yield* session.bootstrap.pipe(\n Effect.mapError((error) => ConnectionUnavailable.make({ message: error.message })),\n ));\n const invocationId = yield* ids.generate(InvocationId);\n const preparedArguments = yield* prepareMutationArguments(args).pipe(\n Effect.provideService(IdGenerator, ids),\n Effect.mapError((cause) =>\n InvalidMutationArguments.make({\n cause,\n function: functionAddress,\n message: `Mutation arguments for ${functionAddress} contain an unsupported file or value.`,\n }),\n ),\n Effect.tapError(reportClientError),\n );\n const jsonArgs = yield* Effect.try({\n try: () => encodeTransportObject(preparedArguments.value),\n catch: (cause) =>\n InvalidMutationArguments.make({\n cause,\n function: functionAddress,\n message: `Mutation arguments for ${functionAddress} contain an unsupported value.`,\n }),\n }).pipe(Effect.tapError(reportClientError));\n const deferred = yield* Deferred.make<\n IgnotumResult<unknown, ErrorValue>,\n ClientInfrastructureError\n >();\n const prepared = yield* Deferred.make<\n Extract<ServerMessage, { readonly type: \"Preparation\" }>[\"uploads\"],\n ClientInfrastructureError\n >();\n const invokeMessage: Extract<ClientMessage, { readonly type: \"Invoke\" }> = {\n type: \"Invoke\",\n id: invocationId,\n kind: \"Mutation\",\n function: functionAddress,\n args: jsonArgs,\n };\n const message: PendingInvocation[\"message\"] =\n preparedArguments.fileIds.length === 0\n ? invokeMessage\n : {\n type: \"Prepare\",\n id: invocationId,\n kind: \"Mutation\",\n function: functionAddress,\n args: jsonArgs,\n files: preparedArguments.fileIds,\n };\n invocations = HashMap.set(invocations, invocationId, {\n sessionEpoch: admittedSession.sessionEpoch,\n deferred,\n function: functionAddress,\n message,\n prepared,\n });\n return yield* Effect.gen(function* () {\n if (writer !== undefined) {\n yield* sendWith(writer, message).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: (error) => rejectInvocation(invocationId, error),\n }),\n );\n }\n if (message.type === \"Prepare\") {\n const uploads = yield* Deferred.await(prepared);\n const expected = new Set(message.files);\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 = preparedArguments.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 const pendingInvocation = Option.getOrUndefined(\n HashMap.get(invocations, invocationId),\n );\n if (pendingInvocation === undefined) return yield* Deferred.await(deferred);\n invocations = HashMap.set(invocations, invocationId, {\n ...pendingInvocation,\n message: invokeMessage,\n });\n if (writer !== undefined) {\n yield* sendWith(writer, invokeMessage).pipe(\n Effect.catchTags({\n ConnectionUnavailable: reportClientError,\n InvalidClientMessage: (error) => rejectInvocation(invocationId, error),\n }),\n );\n }\n }\n return yield* Deferred.await(deferred);\n }).pipe(\n Effect.tapError(() =>\n Effect.sync(() => {\n invocations = HashMap.remove(invocations, invocationId);\n }),\n ),\n );\n },\n );\n\n return SyncClient.of({ mutate, observe });\n }),\n ).pipe(Layer.provide(Layer.merge(Socket.layerWebSocketConstructorGlobal, BrowserCrypto.layer)));\n}\n\nexport const syncRuntime = ManagedRuntime.make(\n SyncClient.layer.pipe(\n Layer.provideMerge(BrowserSession.layer),\n Layer.provideMerge(clientErrorReporterLayer),\n Layer.provideMerge(IdGenerator.layer),\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\";\n\nimport type { FunctionAddress } from \"@ignotum/contracts/runtime/sync\";\nimport { SyncClient, syncClientInternals } from \"./sync.js\";\nimport type { ClientInfrastructureError } from \"./errors.js\";\n\ntype QueryObserver = Effect.Success<ReturnType<SyncClient[\"Service\"][\"observe\"]>>;\n\ninterface PageEntry {\n readonly acquire: Effect.Effect<QueryObserver | undefined, ClientInfrastructureError, SyncClient>;\n release: (() => void) | undefined;\n released: boolean;\n}\n\n// @effect-diagnostics-next-line missingPipeableSignature:off This hook-owned lifecycle takes two callbacks, not a data argument.\nexport const makePageObservers = (\n onChange: () => void,\n releaseObserver: (release: Effect.Effect<void>) => void,\n) => {\n const pages = new Map<string, PageEntry>();\n let disposed = false;\n\n const releaseEntry = (entry: PageEntry) => {\n entry.released = true;\n entry.release?.();\n };\n\n const observe = Effect.fn(\"PageObservers.observe\")(function* (\n functionAddress: FunctionAddress,\n args: Schema.Json,\n ) {\n if (disposed) return;\n const key = syncClientInternals.queryIdentity(functionAddress, args);\n const existing = pages.get(key);\n if (existing !== undefined) return yield* existing.acquire;\n\n const entry: PageEntry = {\n acquire: yield* Effect.cached(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n const observer = yield* client.observe(functionAddress, args);\n if (entry.released) {\n releaseObserver(observer.release);\n return;\n }\n const unsubscribe = observer.subscribe(onChange);\n entry.release = () => {\n unsubscribe();\n releaseObserver(observer.release);\n };\n return observer;\n }),\n ),\n release: undefined,\n released: false,\n };\n pages.set(key, entry);\n return yield* entry.acquire;\n });\n\n return {\n observe,\n retain: (keys: ReadonlySet<string>) => {\n for (const [key, entry] of pages) {\n if (keys.has(key)) continue;\n pages.delete(key);\n releaseEntry(entry);\n }\n },\n release: () => {\n if (disposed) return;\n disposed = true;\n for (const entry of pages.values()) releaseEntry(entry);\n pages.clear();\n },\n };\n};\n","import { BrowserSession, type IdState } from \"./id.js\";\nimport type { ProfileField } from \"@ignotum/contracts/id\";\nimport { Effect, Schema } from \"effect\";\nimport { useCallback, useDebugValue, useEffect, useMemo, useState } from \"preact/hooks\";\n\nimport { functionPathOf, type FunctionReference } from \"../internal/api.js\";\nimport { inspectResult, pending, Result as RuntimeResult } from \"@ignotum/contracts/runtime/result\";\nimport type { ErrorValue, QueryResult, SettledResult } from \"@ignotum/contracts/runtime/result\";\nimport {\n PaginationPageSize,\n type PaginationOptions,\n type PaginationPage,\n} from \"@ignotum/contracts/runtime/pagination\";\nimport { encodeTransportObject } from \"@ignotum/contracts/runtime/sync\";\nimport { ClientInfrastructureError } from \"./errors.js\";\nimport { isQuerySkip, type QuerySkip } from \"./query.js\";\n// oxlint-disable-next-line anti-slop-effect/no-service-constructor-imports -- Each mounted pagination hook owns and releases its page observers.\nimport { makePageObservers } from \"./page-observers.js\";\nimport { SyncClient, syncClientInternals, syncRuntime } from \"./sync.js\";\n\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks are not pipeable functions.\nexport function useQuery<Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", void, Success, Failure>,\n): QueryResult<Success, Failure>;\nexport function useQuery<Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", void, Success, Failure>,\n args: QuerySkip,\n): QueryResult<Success, Failure>;\nexport function useQuery<Args extends object, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args, Success, Failure>,\n args: NoInfer<Args> | QuerySkip,\n): QueryResult<Success, Failure>;\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks must remain direct calls so hook order is statically visible.\nexport function useQuery<Args extends object, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args | void, Success, Failure>,\n args?: Args | QuerySkip,\n): QueryResult<Success, Failure> {\n const functionPath = functionPathOf(reference);\n const skipped = isQuerySkip(args);\n const input = args === undefined || skipped ? {} : args;\n const jsonArgs = encodeTransportObject(input);\n const identity = skipped\n ? `skip:${functionPath}`\n : syncClientInternals.queryIdentity(functionPath, jsonArgs);\n const [state, setState] = useState<{\n readonly identity: string;\n readonly result: QueryResult<Success, Failure> | ClientInfrastructureError;\n }>(() => ({ identity, result: pending() }));\n\n useDebugValue({ args: input, function: functionPath, result: state.result });\n useEffect(() => {\n if (skipped) return;\n\n let active = true;\n let release: (() => void) | undefined;\n\n void syncRuntime\n .runPromise(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n return yield* client.observe(functionPath, jsonArgs);\n }),\n )\n .then(\n (observer) => {\n if (!active) {\n syncRuntime.runFork(observer.release);\n return;\n }\n const update = () => {\n // SAFETY: the function reference couples this subscription's runtime\n // path to its generated success and failure types.\n const result = observer.getSnapshot() as\n | QueryResult<Success, Failure>\n | ClientInfrastructureError;\n setState({ identity, result });\n };\n release = observer.subscribe(update);\n update();\n const releaseObserver = release;\n release = () => {\n releaseObserver();\n syncRuntime.runFork(observer.release);\n };\n },\n (error) => {\n if (active && Schema.is(ClientInfrastructureError)(error)) {\n setState({ identity, result: error });\n }\n },\n );\n\n return () => {\n active = false;\n release?.();\n };\n }, [identity]);\n\n if (skipped) return pending();\n\n if (state.identity !== identity) {\n return pending();\n }\n\n const result = state.result;\n if (Schema.is(ClientInfrastructureError)(result)) throw result;\n return result;\n}\n\nexport type PaginationStatus = \"CanLoadMore\" | \"Exhausted\" | \"LoadingMore\";\n\nexport interface PaginatedQueryValue<Item> {\n readonly items: ReadonlyArray<Item>;\n readonly loadMore: () => void;\n readonly status: PaginationStatus;\n}\n\nexport interface PaginatedQueryOptions {\n readonly pageSize?: number;\n}\n\ntype PaginationArguments = { readonly pagination: PaginationOptions };\ntype ApplicationPaginationArguments<Args extends PaginationArguments> = Omit<Args, \"pagination\">;\n\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks are not pipeable functions.\nexport function usePaginatedQuery<\n Args extends PaginationArguments,\n Item,\n Failure extends ErrorValue,\n>(\n reference: keyof ApplicationPaginationArguments<Args> extends never\n ? FunctionReference<\"Query\", Args, PaginationPage<Item>, Failure>\n : never,\n): QueryResult<PaginatedQueryValue<Item>, Failure>;\nexport function usePaginatedQuery<\n Args extends PaginationArguments,\n Item,\n Failure extends ErrorValue,\n>(\n reference: FunctionReference<\"Query\", Args, PaginationPage<Item>, Failure>,\n args: NoInfer<ApplicationPaginationArguments<Args>> | QuerySkip,\n options?: PaginatedQueryOptions,\n): QueryResult<PaginatedQueryValue<Item>, Failure>;\n// @effect-diagnostics-next-line missingPipeableSignature:off React hooks must remain direct calls so hook order is statically visible.\nexport function usePaginatedQuery<Args extends object, Item, Failure extends ErrorValue>(\n reference: FunctionReference<\"Query\", Args & PaginationArguments, PaginationPage<Item>, Failure>,\n args?: Args | QuerySkip,\n options: PaginatedQueryOptions = {},\n): QueryResult<PaginatedQueryValue<Item>, Failure> {\n const functionPath = functionPathOf(reference);\n const skipped = isQuerySkip(args);\n const input = args === undefined || skipped ? {} : args;\n const jsonArgs = encodeTransportObject(input);\n const pageSize = Schema.decodeSync(PaginationPageSize)(options.pageSize ?? 20);\n const identity = skipped\n ? `skip:${functionPath}`\n : syncClientInternals.queryIdentity(functionPath, jsonArgs);\n const [requestedPages, setRequestedPages] = useState(1);\n const [refresh, setRefresh] = useState(0);\n const [state, setState] = useState<{\n readonly identity: string;\n readonly result: QueryResult<PaginatedQueryValue<Item>, Failure> | ClientInfrastructureError;\n }>(() => ({ identity, result: pending() }));\n const loadMore = useCallback(() => setRequestedPages((count) => count + 1), []);\n const pages = useMemo(\n () =>\n makePageObservers(\n () => setRefresh((version) => version + 1),\n (release) => {\n syncRuntime.runFork(release);\n },\n ),\n [identity, pageSize],\n );\n\n useEffect(() => () => pages.release(), [pages]);\n\n useDebugValue({ args: input, function: functionPath, result: state.result });\n\n useEffect(() => {\n setRequestedPages(1);\n setState({ identity, result: pending() });\n }, [identity, pageSize]);\n\n useEffect(() => {\n if (skipped) return;\n\n let active = true;\n const usedPages = new Set<string>();\n\n void syncRuntime\n .runPromise(\n Effect.gen(function* () {\n const items: Item[] = [];\n let cursor: PaginationOptions[\"cursor\"] = null;\n\n for (let pageNumber = 0; pageNumber < requestedPages; pageNumber += 1) {\n const pageArgs = encodeTransportObject({\n ...input,\n pagination: { cursor, pageSize },\n });\n usedPages.add(syncClientInternals.queryIdentity(functionPath, pageArgs));\n const observer = yield* pages.observe(functionPath, pageArgs);\n if (!active || observer === undefined) return;\n\n const snapshot = observer.getSnapshot();\n if (Schema.is(ClientInfrastructureError)(snapshot)) {\n setState({ identity, result: snapshot });\n return;\n }\n const inspected = inspectResult(snapshot);\n if (inspected === undefined) {\n setState({\n identity,\n result:\n items.length === 0\n ? pending()\n : RuntimeResult.succeed({ items, loadMore, status: \"LoadingMore\" }),\n });\n return;\n }\n if (inspected.type === \"Failure\") {\n // SAFETY: pagination changes only the successful value. The\n // failure channel is the generated query reference's Failure.\n setState({\n identity,\n result: snapshot as QueryResult<PaginatedQueryValue<Item>, Failure>,\n });\n return;\n }\n // SAFETY: the generated reference and values.page validator couple\n // this successful snapshot to PaginationPage<Item>.\n const page = inspected.value as PaginationPage<Item>;\n items.push(...page.items);\n cursor = page.nextCursor;\n if (cursor === null) {\n setState({\n identity,\n result: RuntimeResult.succeed({ items, loadMore, status: \"Exhausted\" }),\n });\n return;\n }\n }\n\n setState({\n identity,\n result: RuntimeResult.succeed({ items, loadMore, status: \"CanLoadMore\" }),\n });\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (active) pages.retain(usedPages);\n }),\n ),\n ),\n )\n .catch((error) => {\n if (active && Schema.is(ClientInfrastructureError)(error)) {\n setState({ identity, result: error });\n }\n });\n\n return () => {\n active = false;\n };\n }, [functionPath, identity, loadMore, pageSize, pages, refresh, requestedPages, skipped]);\n\n if (skipped || state.identity !== identity) return pending();\n const result = state.result;\n if (Schema.is(ClientInfrastructureError)(result)) throw result;\n return result;\n}\n\ntype Mutation<Args, Success, Failure extends ErrorValue> = [Args] extends [void]\n ? () => Promise<SettledResult<Success, Failure>>\n : (args: Args) => Promise<SettledResult<Success, Failure>>;\n\nexport const useMutation = <Args extends object | void, Success, Failure extends ErrorValue>(\n reference: FunctionReference<\"Mutation\", Args, Success, Failure>,\n): Mutation<Args, Success, Failure> =>\n useMemo(() => {\n const mutate = (args: Args | undefined) => {\n const functionPath = functionPathOf(reference);\n const input = args === undefined ? {} : args;\n return syncRuntime.runPromise<SettledResult<Success, Failure>, ClientInfrastructureError>(\n Effect.gen(function* () {\n const client = yield* SyncClient;\n // SAFETY: generated function references bind the runtime path to the\n // declared public result types validated by the server executor.\n // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- The untyped sync transport deliberately erases the generated reference's result parameters.\n return (yield* client.mutate(functionPath, input)) as unknown as SettledResult<\n Success,\n Failure\n >;\n }),\n );\n };\n // SAFETY: the builder gives argument-free functions Args = void. At runtime\n // both call shapes normalize omitted arguments to the empty JSON object.\n return mutate as Mutation<Args, Success, Failure>;\n }, [reference]);\n\nexport type IdOptions = {\n readonly profile?: ReadonlyArray<ProfileField>;\n readonly returnTo?: string;\n};\nexport type IdResult = IdState & {\n readonly signIn: (options?: IdOptions) => Promise<void>;\n readonly requestProfile: (\n fields: ReadonlyArray<ProfileField>,\n options?: { readonly returnTo?: string },\n ) => Promise<void>;\n readonly signOut: () => Promise<void>;\n};\n\nexport function useId(): IdResult {\n const [state, setState] = useState<IdState>({ status: \"pending\" });\n useEffect(() => {\n let active = true;\n let unsubscribe: (() => void) | undefined;\n void syncRuntime.runPromise(BrowserSession).then((session) => {\n if (!active) return;\n const update = () => setState(session.snapshot());\n unsubscribe = session.subscribe(update);\n update();\n });\n return () => {\n active = false;\n unsubscribe?.();\n };\n }, []);\n const actions = useMemo(\n () => ({\n signIn: (options?: IdOptions) =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).start(\n \"signIn\",\n options?.profile ?? [],\n options?.returnTo,\n );\n }),\n ),\n requestProfile: (\n fields: ReadonlyArray<ProfileField>,\n options?: { readonly returnTo?: string },\n ) =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).start(\n \"requestProfile\",\n fields,\n options?.returnTo,\n );\n }),\n ),\n signOut: () =>\n syncRuntime.runPromise(\n Effect.gen(function* () {\n return yield* (yield* BrowserSession).signOut;\n }),\n ),\n }),\n [],\n );\n return { ...state, ...actions };\n}\n","import type { ComponentType } from \"preact\";\n\nexport interface AppDefinition<Component extends ComponentType<{}> = ComponentType<{}>> {\n readonly component: Component;\n readonly title: string;\n}\n\nexport const app = <Component extends ComponentType<{}>>(\n definition: AppDefinition<Component>,\n): AppDefinition<Component> => {\n if (definition.title.trim().length === 0) {\n throw new Error(\"The app title must contain a non-whitespace character.\");\n }\n return definition;\n};\n","import { Result as contractResult } from \"@ignotum/contracts/runtime/result\";\nimport type {\n ErrorValue,\n QueryResult as ContractQueryResult,\n SettledResult,\n} from \"@ignotum/contracts/runtime/result\";\n\nexport const Result = { match: contractResult.match };\nexport type Result<Value, Error extends ErrorValue> = SettledResult<Value, Error>;\nexport type QueryResult<Value, Error extends ErrorValue> = ContractQueryResult<Value, Error>;\nexport type { InternalServerError } from \"@ignotum/contracts/runtime/result\";\nexport type {\n FileFormat,\n FileMetadata,\n FileMimeType,\n FileValue,\n} from \"@ignotum/contracts/schema/file\";\nexport { Files } from \"./files.js\";\nexport { useId, useMutation, usePaginatedQuery, useQuery } from \"./hooks.js\";\nexport type { PaginatedQueryOptions, PaginatedQueryValue, PaginationStatus } from \"./hooks.js\";\nexport { Query } from \"./query.js\";\nexport type { QuerySkip } from \"./query.js\";\nexport { app } from \"./app.js\";\nexport type { AppDefinition } from \"./app.js\";\n\nexport {\n Component,\n Fragment,\n cloneElement,\n createContext,\n createElement,\n createRef,\n h,\n isValidElement,\n toChildArray,\n} from \"preact\";\nexport type {\n AnyComponent,\n Attributes,\n ClassAttributes,\n ComponentChild,\n ComponentChildren,\n ComponentClass,\n ComponentConstructor,\n ComponentFactory,\n ComponentProps,\n ComponentType,\n Consumer,\n Context,\n ContextType,\n ErrorInfo,\n FunctionComponent,\n FunctionalComponent,\n JSX,\n Key,\n PreactContext,\n PreactConsumer,\n PreactDOMAttributes,\n PreactProvider,\n Provider,\n Ref,\n RefCallback,\n RefObject,\n RenderableProps,\n TargetedAnimationEvent,\n TargetedClipboardEvent,\n TargetedCommandEvent,\n TargetedCompositionEvent,\n TargetedDragEvent,\n TargetedEvent,\n TargetedFocusEvent,\n TargetedInputEvent,\n TargetedKeyboardEvent,\n TargetedMouseEvent,\n TargetedPictureInPictureEvent,\n TargetedPointerEvent,\n TargetedSnapEvent,\n TargetedSubmitEvent,\n TargetedToggleEvent,\n TargetedTouchEvent,\n TargetedTransitionEvent,\n TargetedUIEvent,\n TargetedWheelEvent,\n VNode,\n} from \"preact\";\nexport {\n useCallback,\n useContext,\n useDebugValue,\n useEffect,\n useErrorBoundary,\n useId as useElementId,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n} from \"preact/hooks\";\nexport type { Dispatch, Reducer, StateUpdater } from \"preact/hooks\";\n\nexport type { User, UserId, ProfileField } from \"@ignotum/contracts/id\";\nexport type { IdResult, IdOptions } from \"./hooks.js\";\n"],"mappings":";;;;;;;;;;;AAIA,MAAM,mBAAmB,YAAY,YAAY,OAAO,WAAW,UAAU,CAAC,CAAC,WAAW,aAAa,KAAK,IAAI,UAAU,GAAG,WAAW,SAAS,GAAG,SAAS;AAC7J,IAAI,cAAc,MAAM,oBAAoB,QAAQ,QAAQ,CAAC,CAAC,gCAAgC,CAAC,CAAC;CAC/F,OAAO,QAAQ,MAAM,KAAK,mBAAmB;EAC5C,MAAM,kBAAkB,eAAe,YAAA,EAAoB;EAC3D,OAAO,YAAY,GAAG,EAAE,WAAW,eAAe,OAAO,WAAW,gBAAgB,YAAY,gBAAgB,CAAC,CAAC,EAAE,CAAC;CACtH,CAAC;CACD,OAAO,iBAAiB,UAAU,MAAM,MAAM,KAAK,mBAAmB;EACrE,MAAM,2BAA2B,IAAI,IAAI;EACzC,OAAO,YAAY,GAAG,EAAE,WAAW,eAAe,OAAO,WAAW;GACnE,MAAM,WAAW,SAAS,IAAI,WAAW,QAAQ,KAAK,UAAU,KAAK;GACrE,SAAS,IAAI,WAAW,UAAU,OAAO;GACzC,OAAO,gBAAgB,YAAY,QAAQ,SAAS,EAAE,CAAC,CAAC,SAAA,IAAmB,GAAG,CAAC;EAChF,CAAC,EAAE,CAAC;CACL,CAAC;AACF;;;ACFA,MAAa,QAAQ,EACnB,MAAM,SAA4B;CAChC,MAAM,MAAM,eAAe,IAAI;CAC/B,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MAAM,2CAA2C;CAE7D,OAAO;AACT,EACF;AAEA,MAAM,eAAoD,CAAC;AAC3D,KAAK,MAAM,UAAU,aAAa,aAAa,cAAc,WAAW;AAExE,MAAM,iBAAiB,OAA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