@selvajs/selva 4.20.1-beta.4 → 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"}
@@ -56,7 +56,7 @@ function createDefinitionLoader(deps) {
56
56
  }
57
57
  let client;
58
58
  try {
59
- client = (await getClient(computeServer, { definitionGuid: record.guid })).client;
59
+ client = (await getClient(computeServer)).client;
60
60
  } catch (err) {
61
61
  throw new DefinitionLoadError("connect", `Failed to connect to Rhino Compute server: ${err instanceof Error ? err.message : String(err)}`, err);
62
62
  }
@@ -179,7 +179,7 @@ var load = (async ({ params, locals, request, url }) => {
179
179
  await asHttpError(() => requireEditableDefinition(scoped(locals), guid));
180
180
  }
181
181
  const [loaded, orgLogoUrl] = await Promise.all([loadDefinitionForRender(ctx, record, channel, explicitVersionId), resolveOrgLogo(ctx, record.projectId, locals.log)]);
182
- const { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });
182
+ const { limits } = await getClient(loaded.computeServer);
183
183
  return {
184
184
  schema: loaded.schema,
185
185
  ghDefinition: clientDefUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id with a definition-guid affinity header. */\n\tgetClient: (\n\t\tserver: ComputeServerConfig,\n\t\topts: { definitionGuid: string }\n\t) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer, { definitionGuid: record.guid })).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AA2DA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,OACf,QACA,SAAS,IAAI,WAAW,MACrB;CAEJ,OAAO,eAAe,wBAAwB,KAAK,QAAQ,SAAS,mBAAmB,SAAS;EAC/F,MAAM,YACL,sBAAsB,YAAY,UAAU,OAAO,iBAAiB,OAAO;EAC5E,IAAI,CAAC,WACJ,MAAM,IAAI,oBACT,QACA,eAAe,OAAO,KAAK,WAAW,QAAQ,SAC/C;EAID,MAAM,iBAAiB,YAA0C;GAChE,MAAM,UAAU,MAAM,SAAS,WAAW,KAAK,OAAO,SAAS;GAC/D,IAAI;IACH,OAAO,MAAM,cAAc,KAAK,SAAS,SAAS,MAAM,EACvD,eAAe,OAAO,mBAAmB,KAC1C,CAAC;GACF,SAAS,KAAK;IACb,MAAM,IAAI,oBACT,kBACA,oDACA,GACD;GACD;EACD,EAAA,CAAG;EACH,cAAc,YAAY,CAAC,CAAC;EAE5B,MAAM,UAAU,MAAM,YAAY,WAAW,KAAK,SAAS;EAC3D,IAAI,CAAC,SAAS,MAAM,IAAI,oBAAoB,QAAQ,wBAAwB,OAAO,KAAK,EAAE;EAE1F,IAAI,QAAQ,iBAAiB,OAAO,MACnC,MAAM,IAAI,oBAAoB,QAAQ,+BAA+B,OAAO,KAA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AA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
1
+ {"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id. */\n\tgetClient: (server: ComputeServerConfig) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer)).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer);\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"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KAC7C,WAAW;KACX;KACA,KAAK,aAAa,GAAG;IACtB,CAAC;IAED,IAAA,QAAA,IAAA,aAA6B,eAE5B,MAAM,MAAM,KAAK,kCAAkC,aAAa,IAAI,IAAI,QAAA;;;;8CAAgB;IAEzF,MAAM,MAAM,KAAK,8BAA8B,IAAI,SAAS;GAC7D;EAED;EAEA,IAAI,eAAe,OAAO;GACzB,OAAO,IAAI,KAAK,6BAA6B;IAC5C,WAAW;IACX;IACA,KAAK,aAAa,GAAG;GACtB,CAAC;GACD,MAAM,MAAM,KAAK,8BAA8B,KAAK,KAAK,IAAI,SAAS;EACvE;EACA,MAAM;CACP;AACD;AAEA,eAAe,gBAAgB,QAAoB,MAAgC;CAClF,IAAI,CAAC,OAAO,OAAO,CAAC,OAAO,MAAM,OAAO;CACxC,MAAM,SAAS,MAAM,kBAAkB,CAAC,CAAC,IAAI,OAAO,KAAK,IAAI;CAC7D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI;EACH,MAAM,gBAAgB,OAAO,MAAM,GAAG,OAAO,SAAS;EACtD,OAAO;CACR,SAAS,KAAK;EACb,IAAI,WAAW,GAAG,GAAG,OAAO;EAC5B,MAAM;CACP;AACD;;;;;;AAOA,eAAe,eACd,KACA,WACA,KACyB;CACzB,IAAI;EACH,MAAM,UAAU,MAAM,mBAAmB,CAAC,CAAC,WAAW,KAAK,SAAS;EACpE,IAAI,CAAC,SAAS,OAAO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/selva",
3
- "version": "4.20.1-beta.4",
3
+ "version": "4.20.1-beta.5",
4
4
  "description": "Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.",
5
5
  "license": "MIT",
6
6
  "author": "VektorNode",
@@ -58,18 +58,18 @@
58
58
  "rimraf": "^6.1.3",
59
59
  "tw-animate-css": "^1.4.0",
60
60
  "vitest": "^5.0.5",
61
- "@selvajs/compute": "5.0.1",
62
- "@selvajs/header-auth-provider": "0.11.1",
61
+ "@selvajs/compute": "5.1.0-beta.0",
63
62
  "@selvajs/config": "0.0.4",
64
- "@selvajs/local-provider": "0.16.1-beta.2",
65
63
  "@selvajs/mcp": "0.1.0",
64
+ "@selvajs/header-auth-provider": "0.11.1",
65
+ "@selvajs/local-provider": "0.16.1-beta.2",
66
66
  "@selvajs/notifications": "0.3.1-beta.2",
67
- "@selvajs/schemas": "5.3.1-beta.1",
68
67
  "@selvajs/platform": "1.1.0-beta.2",
69
- "@selvajs/server": "3.0.0-beta.1",
70
- "@selvajs/solve": "2.1.0-beta.2",
68
+ "@selvajs/server": "3.0.0-beta.2",
69
+ "@selvajs/schemas": "5.3.1-beta.1",
70
+ "@selvajs/solve": "2.1.0-beta.3",
71
+ "@selvajs/ui": "7.0.3-beta.2",
71
72
  "@selvajs/supabase-provider": "0.21.0-beta.3",
72
- "@selvajs/ui": "7.0.3-beta.1",
73
73
  "@selvajs/visualization": "1.7.1-beta.1"
74
74
  },
75
75
  "imports": {