@selvajs/selva 4.20.1-beta.3 → 4.20.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { F as postedServerSourcedIds, I as solveInputsFromSchema, M as MAX_SOLVE_DEADLINE_MS, T as providers, b as getSolveMetricSink, w as lazyLogger, x as getStorageProvider } from "./providers.server.js";
2
2
  import { E as scoped, M as isApiError, N as toErrorBody, O as ApiError, d as requireCanEditDefinition, h as requireCanSolve, k as ApiErrorCode } from "./access.js";
3
+ import { t as hmacKeys } from "./keys.server.js";
3
4
  import { E as chargeApiRateLimit, M as assertScope, j as withRateLimitHeaders, k as rateLimitedResponse } from "./api.js";
4
5
  import { t as createRemoteDefinitionFetcher } from "./remote-definition.js";
5
6
  import { a as ComputeServerUnconfiguredError, r as fetchSchemaFromCompute } from "./schema-extraction.js";
@@ -14,6 +15,30 @@ import { t as serverResolver } from "./serverResolver.server.js";
14
15
  import { n as checkComputeRateLimit, t as apiRateLimiter } from "./computeRateLimit.server.js";
15
16
  import { n as liveOwnerKey, r as solveEndedKind, t as bindLiveSolve } from "./liveSolve.server.js";
16
17
  import { isHttpError } from "@sveltejs/kit";
18
+ import { createHmac } from "node:crypto";
19
+ // src/lib/server/compute/sessionId.server.ts
20
+ /**
21
+ * Share links have no caller identity, and a remote URL (no `guid`) is caller-chosen, so varying
22
+ * its query string would mint ids: neither gets one, and both route as if compute had no sessions.
23
+ */
24
+ function solveSessionId(access, guid) {
25
+ if (access.kind !== "user" || !access.ctx.userId || !guid) return void 0;
26
+ return computeSessionId(access.ctx.userId, guid);
27
+ }
28
+ /**
29
+ * The `X-Session-Id` for one user's solves of one definition: the compute fork routes them back
30
+ * to the child holding that user's warm document. Derived rather than stored, so every Selva
31
+ * instance computes the same id with no shared state, and the browser can't mint ids to fill
32
+ * compute's claim cap. Keyed, so a compute operator can't recover the user id from it.
33
+ *
34
+ * Undefined without `SELVA_HMAC_KEY`: a routing hint never fails a solve. Rotating the key moves
35
+ * every session to a new id, so each solves cold once.
36
+ */
37
+ function computeSessionId(userId, definitionKey) {
38
+ const key = hmacKeys().current;
39
+ if (!key) return void 0;
40
+ return createHmac("sha256", key).update(`compute-session\0${userId}\0${definitionKey}`).digest("hex").slice(0, 32);
41
+ }
17
42
  // src/lib/server/compute/errorLogFields.ts
18
43
  /**
19
44
  * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure
@@ -256,7 +281,8 @@ async function runSolve(params) {
256
281
  loadStartMs: loadStart,
257
282
  defLoadMs,
258
283
  prepMarks,
259
- selvaEvents: live.selvaEvents
284
+ selvaEvents: live.selvaEvents,
285
+ sessionId: solveSessionId(access, guid)
260
286
  });
261
287
  } finally {
262
288
  live.end(outcome ? solveEndedKind(outcome) : "error");
@@ -1 +1 @@
1
- {"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,sBACf,KACA,aACkC;CAClC,IAAI,EAAE,eAAe,eAAe,OAAO,CAAC;CAC5C,MAAM,EAAE,WAAW,iBAAiB,IAAI,WAAW,CAAC;CACpD,OAAO;EACN,GAAI,OAAO,cAAc,YAAY,EAAE,kBAAkB,UAAU;EACnE,GAAI,OAAO,iBAAiB,YAAY;GACvC,kBAAkB,aAAa;GAC/B,GAAI,eAAe,EAAE,qBAAqB,aAAa;EACxD;CACD;AACD;;;;;;ACLA,IAAM,UAAU,8BAA8B;CAC7C,UAAU;CACV,gBAAgB;CAChB,YAAY;CACZ,WAAW,KAAK,IAAI;CACpB,QAAQ;AACT,CAAC;;AAGD,SAAgB,qBAAqB,KAAkC;CACtE,OAAO,QAAQ,KAAK,GAAG;AACxB;;;;;;;;;;;;;;;;;ACqFA,SAAS,iBAAiB,QAA+B;CAUxD,IAAI,EARH,M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CACD,IAAI,QAAQ,oBAAoB,MAC/B,OAAO,IAAI,MAAM,oBAAoB;EACpC,WAAW;EACX,iBAAiB,QAAQ;EACzB,iBAAiB,QAAQ;EACzB,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,gBAAA,CAAiB,QAAQ,CAAC,CAAC;CAC7E,CAAC;MACK;EAGN,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
1
+ {"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/sessionId.server.ts","../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport type { SolveAccess } from '#lib/server/compute/solve.server.js';\n\n/**\n * Share links have no caller identity, and a remote URL (no `guid`) is caller-chosen, so varying\n * its query string would mint ids: neither gets one, and both route as if compute had no sessions.\n */\nexport function solveSessionId(access: SolveAccess, guid: string | null): string | undefined {\n\tif (access.kind !== 'user' || !access.ctx.userId || !guid) return undefined;\n\treturn computeSessionId(access.ctx.userId, guid);\n}\n\n/**\n * The `X-Session-Id` for one user's solves of one definition: the compute fork routes them back\n * to the child holding that user's warm document. Derived rather than stored, so every Selva\n * instance computes the same id with no shared state, and the browser can't mint ids to fill\n * compute's claim cap. Keyed, so a compute operator can't recover the user id from it.\n *\n * Undefined without `SELVA_HMAC_KEY`: a routing hint never fails a solve. Rotating the key moves\n * every session to a new id, so each solves cold once.\n */\nexport function computeSessionId(userId: string, definitionKey: string): string | undefined {\n\tconst key = hmacKeys().current;\n\tif (!key) return undefined;\n\treturn createHmac('sha256', key)\n\t\t.update(`compute-session\\0${userId}\\0${definitionKey}`)\n\t\t.digest('hex')\n\t\t.slice(0, 32);\n}\n","import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { solveSessionId } from '#lib/server/compute/sessionId.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents,\n\t\t\tsessionId: solveSessionId(access, guid)\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,QAAqB,MAAyC;CAC5F,IAAI,OAAO,SAAS,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,MAAM,OAAO,KAAA;CAClE,OAAO,iBAAiB,OAAO,IAAI,QAAQ,IAAI;AAChD;;;;;;;;;;AAWA,SAAgB,iBAAiB,QAAgB,eAA2C;CAC3F,MAAM,MAAM,SAAS,CAAC,CAAC;CACvB,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,OAAO,WAAW,UAAU,GAAG,CAAC,CAC9B,OAAO,oBAAoB,OAAO,IAAI,eAAe,CAAC,CACtD,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;AACd;;;;;;;ACtBA,SAAgB,sBACf,KACA,aACkC;CAClC,IAAI,EAAE,eAAe,eAAe,OAAO,CAAC;CAC5C,MAAM,EAAE,WAAW,iBAAiB,IAAI,WAAW,CAAC;CACpD,OAAO;EACN,GAAI,OAAO,cAAc,YAAY,EAAE,kBAAkB,UAAU;EACnE,GAAI,OAAO,iBAAiB,YAAY;GACvC,kBAAkB,aAAa;GAC/B,GAAI,eAAe,EAAE,qBAAqB,aAAa;EACxD;CACD;AACD;;;;;;ACLA,IAAM,UAAU,8BAA8B;CAC7C,UAAU;CACV,gB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AAS;EAC5B,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,SAAS,KAAK,MAAM,QAAQ,OAAO;EACnC,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,QAAQ,KAAK,MAAM,QAAQ,MAAM;EACjC,eAAe,KAAK,MAAM,QAAQ,aAAa;EAC/C,iBAAiB,QAAQ;CAC1B,CAAC;CACD,IAAI,QAAQ,oBAAoB,MAC/B,OAAO,IAAI,MAAM,oBAAoB;EACpC,WAAW;EACX,iBAAiB,QAAQ;EACzB,iBAAiB,QAAQ;EACzB,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,gBAAA,CAAiB,QAAQ,CAAC,CAAC;CAC7E,CAAC;MACK;EAGN,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
@@ -400,6 +400,27 @@ var requestTiming = createRequestTiming({
400
400
  labels: env.SELVA_RELEASE ? { release: env.SELVA_RELEASE } : {}
401
401
  });
402
402
  requestTiming.instrumentFetch();
403
+ // src/lib/server/framing.ts
404
+ var FRAME_DENIED_PREFIXES = [
405
+ "/admin",
406
+ "/setup",
407
+ "/login",
408
+ "/oauth"
409
+ ];
410
+ /**
411
+ * Whether a response to `pathname` must refuse framing. Kit routes on the decoded path, so
412
+ * `/%61dmin` renders /admin: this matches what Kit matches, and a path that does not decode is
413
+ * refused too.
414
+ */
415
+ function deniesFraming(pathname) {
416
+ let path;
417
+ try {
418
+ path = pathname.split("%25").map(decodeURI).join("%25");
419
+ } catch {
420
+ return true;
421
+ }
422
+ return FRAME_DENIED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));
423
+ }
403
424
  // src/hooks.server.ts
404
425
  var OAUTH_TOKEN_PATH = "/oauth/token";
405
426
  var holderVerdicts = createHolderVerdictCache();
@@ -662,15 +683,6 @@ var gate = async ({ event, resolve }) => {
662
683
  }
663
684
  return applyResponseHeaders(await resolve(event), pathname, requestId);
664
685
  };
665
- var FRAME_DENIED_PREFIXES = [
666
- "/admin",
667
- "/setup",
668
- "/login",
669
- "/oauth"
670
- ];
671
- function deniesFraming(pathname) {
672
- return FRAME_DENIED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
673
- }
674
686
  function applyResponseHeaders(response, pathname, requestId) {
675
687
  applySecurityHeaders(response, {
676
688
  hsts: process.env.NODE_ENV === "production",