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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/chunks/{D-SwRD80.js → D-uUm_OB.js} +43 -43
  3. package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
  4. package/build/client/_app/immutable/chunks/{D-SwRD80.js.gz → D-uUm_OB.js.gz} +0 -0
  5. package/build/client/_app/immutable/chunks/D84F7w9g.js +1 -0
  6. package/build/client/_app/immutable/chunks/D84F7w9g.js.br +1 -0
  7. package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
  8. package/build/client/_app/immutable/entry/{app.hg2qyLJU.js → app.BpT6WkO1.js} +2 -2
  9. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
  10. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
  11. package/build/client/_app/immutable/nodes/21.BkNlRItr.js +1 -0
  12. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
  13. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
  14. package/build/client/_app/version.json +1 -1
  15. package/build/client/_app/version.json.br +0 -0
  16. package/build/client/_app/version.json.gz +0 -0
  17. package/build/server/.vite/manifest.json +9 -2
  18. package/build/server/chunks/access.js +0 -3
  19. package/build/server/chunks/access.js.map +1 -1
  20. package/build/server/chunks/definitions.js +178 -1
  21. package/build/server/chunks/definitions.js.map +1 -1
  22. package/build/server/chunks/handlers.js +4 -5
  23. package/build/server/chunks/handlers.js.map +1 -1
  24. package/build/server/chunks/instance.js +3 -3
  25. package/build/server/chunks/internal.js +1 -1
  26. package/build/server/chunks/package.js +1 -1
  27. package/build/server/chunks/package.js.map +1 -1
  28. package/build/server/chunks/providers.server.js +112 -189
  29. package/build/server/chunks/providers.server.js.map +1 -1
  30. package/build/server/chunks/registry.js +3 -3
  31. package/build/server/chunks/registry.js.map +1 -1
  32. package/build/server/chunks/resolve.server.js +1 -1
  33. package/build/server/chunks/server-config-write.js +13 -1
  34. package/build/server/chunks/server-config-write.js.map +1 -1
  35. package/build/server/chunks/solve.server.js +8 -3
  36. package/build/server/chunks/solve.server.js.map +1 -1
  37. package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +30 -48
  38. package/build/server/entries/endpoints/api/admin/compute/_server.ts.js.map +1 -1
  39. package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +3 -2
  40. package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js.map +1 -1
  41. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +3 -2
  42. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js.map +1 -1
  43. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +3 -2
  44. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js.map +1 -1
  45. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +6 -2
  46. package/build/server/entries/endpoints/api/admin/users/_server.ts.js.map +1 -1
  47. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +8 -8
  48. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
  49. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +1 -1
  50. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +1 -1
  51. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  52. package/build/server/entries/hooks.server.js +13 -1
  53. package/build/server/entries/hooks.server.js.map +1 -1
  54. package/build/server/entries/pages/accept-invite/_page.server.ts.js +19 -1
  55. package/build/server/entries/pages/accept-invite/_page.server.ts.js.map +1 -1
  56. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +16 -3
  57. package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
  58. package/build/server/entries/pages/library/_guid_/_page.svelte.js +132 -89
  59. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  60. package/build/server/manifest-full.js +1 -1
  61. package/build/server/manifest.js +1 -1
  62. package/build/server/nodes/21.js +1 -1
  63. package/build/server/server.js +1 -1
  64. package/package.json +10 -10
  65. package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
  66. package/build/client/_app/immutable/chunks/Dvq2vJj6.js +0 -1
  67. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +0 -1
  68. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
  69. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
  70. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
  71. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +0 -1
  72. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +0 -1
  73. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
@@ -452,7 +452,7 @@ var V1_ENDPOINTS = [
452
452
  method: "GET",
453
453
  path: "/orgs/{orgId}/invites",
454
454
  scope: "read",
455
- summary: "List pending invites.",
455
+ summary: "List pending invites. Browser session only: an API key gets 403.",
456
456
  response: "collection",
457
457
  errors: [403]
458
458
  },
@@ -460,7 +460,7 @@ var V1_ENDPOINTS = [
460
460
  method: "POST",
461
461
  path: "/orgs/{orgId}/invites",
462
462
  scope: "write",
463
- summary: "Invite someone to the org. The accept URL is returned once.",
463
+ summary: "Invite someone to the org. The accept URL is returned once. Browser session only: an API key gets 403.",
464
464
  response: "object",
465
465
  status: 201,
466
466
  requestBody: CreateInviteBodySchema,
@@ -482,7 +482,7 @@ var V1_ENDPOINTS = [
482
482
  method: "POST",
483
483
  path: "/orgs/{orgId}/invites/{id}/resend",
484
484
  scope: "write",
485
- summary: "Re-send an invite. Issues a replacement and revokes the original, so the previous link stops working.",
485
+ summary: "Re-send an invite. Issues a replacement and revokes the original, so the previous link stops working. Browser session only: an API key gets 403.",
486
486
  response: "object",
487
487
  status: 201,
488
488
  errors: [
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","names":[],"sources":["../../../src/lib/server/api/v1/registry.ts"],"sourcesContent":["/**\n * The v1 contract as data: one entry per method+path, naming its body validator,\n * response shape, and whether it's public or internal.\n *\n * Both the OpenAPI generator and the conformance test read this file. The test\n * walks `routes/api/v1/**` against this table and fails if either side has an\n * entry the other doesn't — a route with no registry entry is undocumented, a\n * registry entry with no route is a spec promising something that 404s.\n *\n * Request schemas are Zod values imported from `@selvajs/server/api`, not\n * transcribed, so a renamed field changes the spec on the next generate\n * instead of silently disagreeing with the validator.\n */\n\nimport {\n\ttype Endpoint,\n\ttype HttpMethod,\n\tSolveBodySchema,\n\tUpdateDefinitionBodySchema,\n\tPublishVersionBodySchema,\n\tCreateShareLinkBodySchema,\n\tCreateProjectBodySchema,\n\tUpdateProjectBodySchema,\n\tAddProjectMemberBodySchema,\n\tUpdateProjectMemberBodySchema,\n\tCreateInviteBodySchema,\n\tUpdateOrgMemberBodySchema,\n\tOrgComputePatchBodySchema,\n\tCreateApiTokenBodySchema\n} from '@selvajs/server/api';\n\nexport type { Endpoint, HttpMethod };\n\nconst solveErrors = [400, 401, 404, 429, 503];\n\nexport const V1_ENDPOINTS: Endpoint[] = [\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/openapi.json',\n\t\tscope: 'read',\n\t\tsummary: 'This document, as JSON.',\n\t\tresponse: 'object'\n\t},\n\n\t// ==========================================================================\n\t// Me\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/me',\n\t\tscope: 'read',\n\t\tsummary:\n\t\t\t'The calling identity, its acting org, its effective permissions, and for a token its id, scopes and expiry.',\n\t\tresponse: 'object',\n\t\treturns:\n\t\t\t'`apiToken: { id, scopes, expiresAt }` is present only when the caller is an API token. `capabilities.createProjects` says whether `POST /projects` would accept this caller, narrowed to the key; `orgPermissions` is the owner’s and is not.'\n\t},\n\t// Every key may call it, whatever its scopes; `read` is the action every key holds.\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/me/token',\n\t\tscope: 'read',\n\t\tsummary:\n\t\t\t'Revoke the API token that sent this request. A key can revoke itself and nothing else; a browser session gets 400.',\n\t\tresponse: 'empty',\n\t\terrors: [400, 503]\n\t},\n\t{\n\t\tmethod: 'PUT',\n\t\tpath: '/me/starred/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Star a definition. Idempotent.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/me/starred/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Unstar a definition. Idempotent.',\n\t\tresponse: 'empty'\n\t},\n\n\t// ==========================================================================\n\t// Definitions\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions',\n\t\tscope: 'read',\n\t\tsummary: 'List definitions the caller can see.',\n\t\tresponse: 'collection',\n\t\treturns:\n\t\t\t'Each item has `sourceDocumentId`: the Grasshopper document GUID the definition was last uploaded from, or null.',\n\t\tquery: [\n\t\t\t{ name: 'projectId', description: 'Restrict to one project.' },\n\t\t\t{ name: 'status', description: 'One of `draft`, `published`, `archived`.' },\n\t\t\t{\n\t\t\t\tname: 'documentId',\n\t\t\t\tdescription:\n\t\t\t\t\t'A Grasshopper document GUID. Returns only definitions last uploaded from that document which the caller can upload a new version of. Not a GUID: 400.'\n\t\t\t}\n\t\t],\n\t\terrors: [400]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions',\n\t\tscope: 'upload',\n\t\tidempotent: true,\n\t\tsummary: 'Create a definition from a Grasshopper file.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\tmultipart: [\n\t\t\t{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' },\n\t\t\t{ field: 'projectId', required: true, description: 'Owning project.' },\n\t\t\t{ field: 'displayName', required: true, description: 'Human-readable name.' },\n\t\t\t{ field: 'description', required: false, description: 'Long description.' },\n\t\t\t{ field: 'category', required: false, description: 'Grouping label.' },\n\t\t\t{ field: 'tags', required: false, description: 'Comma-separated tags.' },\n\t\t\t{ field: 'image', required: false, description: 'Cover image.' },\n\t\t\t{ field: 'computeServerId', required: false, description: 'Pin to a compute server.' }\n\t\t],\n\t\terrors: [400, 403, 422, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'read',\n\t\tsummary: 'Definition record plus its live and draft version summaries.',\n\t\tresponse: 'object',\n\t\treturns:\n\t\t\t'`canEdit` is true when the caller can upload a version and make one live; for an API token that includes its scopes. `sourceDocumentId` is the Grasshopper document GUID it was last uploaded from, or null.',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Update definition metadata.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateDefinitionBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Soft-delete a definition.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/solve',\n\t\tscope: 'solve',\n\t\tidempotent: true,\n\t\tsummary: 'Solve a definition. The primary action of the API.',\n\t\tresponse: 'object',\n\t\trequestBody: SolveBodySchema,\n\t\terrors: solveErrors\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/schema',\n\t\tscope: 'read',\n\t\tsummary: \"The live version's UI schema. 404 when nothing is published.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions',\n\t\tscope: 'read',\n\t\tsummary: 'List versions, newest first.',\n\t\tresponse: 'collection',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/versions',\n\t\tscope: 'upload',\n\t\tidempotent: true,\n\t\tsummary: 'Upload a new version.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\tmultipart: [\n\t\t\t{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' },\n\t\t\t{ field: 'changeNote', required: false, description: 'Truncated to 1000 characters.' }\n\t\t],\n\t\terrors: [400, 404, 422, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions/{versionId}',\n\t\tscope: 'read',\n\t\tsummary: 'One version, without its cached schema.',\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}/versions/{versionId}',\n\t\tscope: 'write',\n\t\tsummary: 'Delete a version. 409 when it is the live or draft pointer.',\n\t\tresponse: 'empty',\n\t\terrors: [404, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions/{versionId}/schema',\n\t\tscope: 'read',\n\t\tsummary: \"That version's cached UI schema. No compute round-trip.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/publish',\n\t\tscope: 'upload',\n\t\tsummary: 'Promote a version to live.',\n\t\tresponse: 'object',\n\t\trequestBody: PublishVersionBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/image',\n\t\tscope: 'write',\n\t\tsummary: 'Upload a cover image.',\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'image', required: true, description: 'PNG, JPEG, WebP or GIF.' }],\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/share-links',\n\t\tscope: 'read',\n\t\tsummary: 'List share links. 404 when sharing is disabled on the instance.',\n\t\tresponse: 'collection',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/share-links',\n\t\tscope: 'write',\n\t\tidempotent: true,\n\t\tsummary: 'Create a share link. The raw token is returned once and never again.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateShareLinkBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}/share-links/{linkId}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke a share link.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\n\t// ==========================================================================\n\t// Projects\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects',\n\t\tscope: 'read',\n\t\tsummary: 'List projects the caller can view.',\n\t\tresponse: 'collection',\n\t\treturns:\n\t\t\t'Each item has `canCreateDefinitions`: whether `POST /definitions` would accept this project from the caller, scopes included for an API token.'\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects',\n\t\tscope: 'create_projects',\n\t\tidempotent: true,\n\t\tsummary:\n\t\t\t'Create a project. A key with `create_projects` but not `write` may create private projects only, with `autoJoinOnUpload` off.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateProjectBodySchema,\n\t\terrors: [400, 403, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'read',\n\t\tsummary: \"Project record plus the caller's effective role and capabilities.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Update project settings. Owner-only.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateProjectBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Delete a project.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects/{id}/members',\n\t\tscope: 'read',\n\t\tsummary: 'List project members.',\n\t\tresponse: 'collection',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects/{id}/members',\n\t\tscope: 'write',\n\t\tsummary: 'Add a member. The target must already belong to the org.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: AddProjectMemberBodySchema,\n\t\terrors: [400, 403, 404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/projects/{id}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Change a member role.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateProjectMemberBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/projects/{id}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove a member. Idempotent.',\n\t\tresponse: 'empty',\n\t\tquery: [\n\t\t\t{\n\t\t\t\tname: 'confirm',\n\t\t\t\tdescription: 'Set to `true` to remove a co-owner; without it the call returns 409.'\n\t\t\t}\n\t\t],\n\t\terrors: [403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects/{id}/reclaim',\n\t\tscope: 'write',\n\t\tsummary: 'Claim ownership of an unowned project.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\terrors: [403, 404, 409]\n\t},\n\n\t// ==========================================================================\n\t// Orgs\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}',\n\t\tscope: 'read',\n\t\tsummary: \"Org record. The org must be the caller's acting org.\",\n\t\tresponse: 'object',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/members',\n\t\tscope: 'read',\n\t\tsummary: 'List org members.',\n\t\tresponse: 'collection',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/orgs/{orgId}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Change an org role or permission set. The sole owner cannot be demoted.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateOrgMemberBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove an org member. The sole owner cannot be removed.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/invites',\n\t\tscope: 'read',\n\t\tsummary: 'List pending invites.',\n\t\tresponse: 'collection',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/invites',\n\t\tscope: 'write',\n\t\tsummary: 'Invite someone to the org. The accept URL is returned once.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateInviteBodySchema,\n\t\terrors: [400, 403, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/invites/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke an invite.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/invites/{id}/resend',\n\t\tscope: 'write',\n\t\tsummary:\n\t\t\t'Re-send an invite. Issues a replacement and revokes the original, so the previous link stops working.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\terrors: [403, 404, 409]\n\t},\n\t// Internal and session-only: a key can never manage keys.\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/tokens',\n\t\tscope: 'read',\n\t\tsummary: 'Your API tokens in this org, revoked and expired included.',\n\t\tinternal: true,\n\t\tresponse: 'collection',\n\t\tquery: [\n\t\t\t{ name: 'all', description: \"`true` for every member's tokens. Needs `manage_org_members`.\" }\n\t\t],\n\t\terrors: [403, 503]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/tokens',\n\t\tscope: 'write',\n\t\tsummary: 'Create an API token acting as you. The raw key is returned once, as `secret`.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateApiTokenBodySchema,\n\t\terrors: [400, 403, 503]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/tokens/{tokenId}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke an API token: your own, or any in the org with `manage_org_members`.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [403, 404, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/compute',\n\t\tscope: 'read',\n\t\tsummary: 'Org compute-server overrides and the shared catalog.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/orgs/{orgId}/compute',\n\t\tscope: 'write',\n\t\tsummary: 'Replace the org compute-server overrides.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\trequestBody: OrgComputePatchBodySchema,\n\t\terrors: [400, 403]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/assets/{kind}',\n\t\tscope: 'write',\n\t\tsummary: 'Upload an org branding asset.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'image', required: true, description: 'PNG, JPEG, WebP, GIF or SVG.' }],\n\t\terrors: [400, 403, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/assets/{kind}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove an org branding asset.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\n\t// ==========================================================================\n\t// Compute\n\t// ==========================================================================\n\t//\n\t// Internal: accepts a remote `definitionUrl` and the anonymous share-token\n\t// flow, neither part of the public contract. Public callers solve through\n\t// `/definitions/{guid}/solve`.\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/compute',\n\t\tscope: 'solve',\n\t\tsummary: 'Generic solve, including remote definition URLs and share-token access.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: solveErrors\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/compute/schema',\n\t\tscope: 'upload',\n\t\tsummary: 'Extract UI schemas from an uploaded file before it becomes a definition.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' }],\n\t\tquery: [\n\t\t\t{ name: 'projectId', description: 'Project the file will belong to.' },\n\t\t\t{ name: 'computeServerId', description: 'Pin to a compute server.' }\n\t\t],\n\t\terrors: [400, 403, 422, 503]\n\t},\n\n\t// ==========================================================================\n\t// Live solve events\n\t// ==========================================================================\n\t//\n\t// Internal: the browser's live channel and the plugin's callback into it. Both\n\t// are shaped by the Selva plugin and web app, not by the public contract.\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/solve-events',\n\t\tscope: 'read',\n\t\tsummary: \"The tab's live event stream (SSE). Solves that name its `streamId` report here.\",\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tquery: [{ name: 'streamId', description: 'Minted by the tab, 16-64 URL-safe characters.' }],\n\t\terrors: [400, 401, 409]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/solve-events/{solveId}',\n\t\tscope: 'write',\n\t\tsummary: \"The plugin's callback from inside a Compute solve. The reply carries `abort`.\",\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: [400, 401, 410]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/solve/{solveId}/cancel',\n\t\tscope: 'solve',\n\t\tsummary: 'Ask a running solve to abort. Cooperative: it stops at the next component.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [401, 404]\n\t}\n];\n\n/** `/definitions/{guid}` → the SvelteKit directory form `definitions/[guid]`. */\nexport function toRoutePath(openApiPath: string): string {\n\treturn openApiPath.replace(/^\\//, '').replace(/\\{(\\w+)\\}/g, '[$1]');\n}\n\nexport function endpointKey(method: HttpMethod, path: string): string {\n\treturn `${method} ${path}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiCA,IAAM,cAAc;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG;AAE5C,IAAa,eAA2B;CACvC;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;CACX;CAKA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SACC;EACD,UAAU;EACV,SACC;CACF;CAEA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SACC;EACD,UAAU;EACV,QAAQ,CAAC,KAAK,GAAG;CAClB;CACA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,QAAQ,CAAC,GAAG;CACb;CACA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;CACX;CAKA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,SACC;EACD,OAAO;GACN;IAAE,MAAM;IAAa,aAAa;GAA2B;GAC7D;IAAE,MAAM;IAAU,aAAa;GAA2C;GAC1E;IACC,MAAM;IACN,aACC;GACF;EACD;EACA,QAAQ,CAAC,GAAG;CACb;CACA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,YAAY;EACZ,SAAS;EACT,UAAU;EACV,QAAQ;EACR,WAAW;GACV;IAAE,OAAO;IAAQ,UAAU;IAAM,aAAa;GAA4B;GAC1E;IAAE,OAAO;IAAa,UAAU;IAAM,aAAa;GAAkB;GACrE;IAAE,OAAO;IAAe,UAAU;IAAM,aAAa;GAAuB;GAC5E;IAAE,OAAO;IAAe,UAAU;IAAO,aAAa;GAA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N,OAAO;EACP,SAAS;EACT,UAAU;EACV,UAAU;EACV,WAAW,CAAC;GAAE,OAAO;GAAQ,UAAU;GAAM,aAAa;EAA4B,CAAC;EACvF,OAAO,CACN;GAAE,MAAM;GAAa,aAAa;EAAmC,GACrE;GAAE,MAAM;GAAmB,aAAa;EAA2B,CACpE;EACA,QAAQ;GAAC;GAAK;GAAK;GAAK;EAAG;CAC5B;CAQA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,UAAU;EACV,OAAO,CAAC;GAAE,MAAM;GAAY,aAAa;EAAgD,CAAC;EAC1F,QAAQ;GAAC;GAAK;GAAK;EAAG;CACvB;CACA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,UAAU;EACV,QAAQ;GAAC;GAAK;GAAK;EAAG;CACvB;CACA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,UAAU;EACV,QAAQ,CAAC,KAAK,GAAG;CAClB;AACD"}
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../../src/lib/server/api/v1/registry.ts"],"sourcesContent":["/**\n * The v1 contract as data: one entry per method+path, naming its body validator,\n * response shape, and whether it's public or internal.\n *\n * Both the OpenAPI generator and the conformance test read this file. The test\n * walks `routes/api/v1/**` against this table and fails if either side has an\n * entry the other doesn't — a route with no registry entry is undocumented, a\n * registry entry with no route is a spec promising something that 404s.\n *\n * Request schemas are Zod values imported from `@selvajs/server/api`, not\n * transcribed, so a renamed field changes the spec on the next generate\n * instead of silently disagreeing with the validator.\n */\n\nimport {\n\ttype Endpoint,\n\ttype HttpMethod,\n\tSolveBodySchema,\n\tUpdateDefinitionBodySchema,\n\tPublishVersionBodySchema,\n\tCreateShareLinkBodySchema,\n\tCreateProjectBodySchema,\n\tUpdateProjectBodySchema,\n\tAddProjectMemberBodySchema,\n\tUpdateProjectMemberBodySchema,\n\tCreateInviteBodySchema,\n\tUpdateOrgMemberBodySchema,\n\tOrgComputePatchBodySchema,\n\tCreateApiTokenBodySchema\n} from '@selvajs/server/api';\n\nexport type { Endpoint, HttpMethod };\n\nconst solveErrors = [400, 401, 404, 429, 503];\n\nexport const V1_ENDPOINTS: Endpoint[] = [\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/openapi.json',\n\t\tscope: 'read',\n\t\tsummary: 'This document, as JSON.',\n\t\tresponse: 'object'\n\t},\n\n\t// ==========================================================================\n\t// Me\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/me',\n\t\tscope: 'read',\n\t\tsummary:\n\t\t\t'The calling identity, its acting org, its effective permissions, and for a token its id, scopes and expiry.',\n\t\tresponse: 'object',\n\t\treturns:\n\t\t\t'`apiToken: { id, scopes, expiresAt }` is present only when the caller is an API token. `capabilities.createProjects` says whether `POST /projects` would accept this caller, narrowed to the key; `orgPermissions` is the owner’s and is not.'\n\t},\n\t// Every key may call it, whatever its scopes; `read` is the action every key holds.\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/me/token',\n\t\tscope: 'read',\n\t\tsummary:\n\t\t\t'Revoke the API token that sent this request. A key can revoke itself and nothing else; a browser session gets 400.',\n\t\tresponse: 'empty',\n\t\terrors: [400, 503]\n\t},\n\t{\n\t\tmethod: 'PUT',\n\t\tpath: '/me/starred/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Star a definition. Idempotent.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/me/starred/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Unstar a definition. Idempotent.',\n\t\tresponse: 'empty'\n\t},\n\n\t// ==========================================================================\n\t// Definitions\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions',\n\t\tscope: 'read',\n\t\tsummary: 'List definitions the caller can see.',\n\t\tresponse: 'collection',\n\t\treturns:\n\t\t\t'Each item has `sourceDocumentId`: the Grasshopper document GUID the definition was last uploaded from, or null.',\n\t\tquery: [\n\t\t\t{ name: 'projectId', description: 'Restrict to one project.' },\n\t\t\t{ name: 'status', description: 'One of `draft`, `published`, `archived`.' },\n\t\t\t{\n\t\t\t\tname: 'documentId',\n\t\t\t\tdescription:\n\t\t\t\t\t'A Grasshopper document GUID. Returns only definitions last uploaded from that document which the caller can upload a new version of. Not a GUID: 400.'\n\t\t\t}\n\t\t],\n\t\terrors: [400]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions',\n\t\tscope: 'upload',\n\t\tidempotent: true,\n\t\tsummary: 'Create a definition from a Grasshopper file.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\tmultipart: [\n\t\t\t{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' },\n\t\t\t{ field: 'projectId', required: true, description: 'Owning project.' },\n\t\t\t{ field: 'displayName', required: true, description: 'Human-readable name.' },\n\t\t\t{ field: 'description', required: false, description: 'Long description.' },\n\t\t\t{ field: 'category', required: false, description: 'Grouping label.' },\n\t\t\t{ field: 'tags', required: false, description: 'Comma-separated tags.' },\n\t\t\t{ field: 'image', required: false, description: 'Cover image.' },\n\t\t\t{ field: 'computeServerId', required: false, description: 'Pin to a compute server.' }\n\t\t],\n\t\terrors: [400, 403, 422, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'read',\n\t\tsummary: 'Definition record plus its live and draft version summaries.',\n\t\tresponse: 'object',\n\t\treturns:\n\t\t\t'`canEdit` is true when the caller can upload a version and make one live; for an API token that includes its scopes. `sourceDocumentId` is the Grasshopper document GUID it was last uploaded from, or null.',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Update definition metadata.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateDefinitionBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}',\n\t\tscope: 'write',\n\t\tsummary: 'Soft-delete a definition.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/solve',\n\t\tscope: 'solve',\n\t\tidempotent: true,\n\t\tsummary: 'Solve a definition. The primary action of the API.',\n\t\tresponse: 'object',\n\t\trequestBody: SolveBodySchema,\n\t\terrors: solveErrors\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/schema',\n\t\tscope: 'read',\n\t\tsummary: \"The live version's UI schema. 404 when nothing is published.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions',\n\t\tscope: 'read',\n\t\tsummary: 'List versions, newest first.',\n\t\tresponse: 'collection',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/versions',\n\t\tscope: 'upload',\n\t\tidempotent: true,\n\t\tsummary: 'Upload a new version.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\tmultipart: [\n\t\t\t{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' },\n\t\t\t{ field: 'changeNote', required: false, description: 'Truncated to 1000 characters.' }\n\t\t],\n\t\terrors: [400, 404, 422, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions/{versionId}',\n\t\tscope: 'read',\n\t\tsummary: 'One version, without its cached schema.',\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}/versions/{versionId}',\n\t\tscope: 'write',\n\t\tsummary: 'Delete a version. 409 when it is the live or draft pointer.',\n\t\tresponse: 'empty',\n\t\terrors: [404, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/versions/{versionId}/schema',\n\t\tscope: 'read',\n\t\tsummary: \"That version's cached UI schema. No compute round-trip.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/publish',\n\t\tscope: 'upload',\n\t\tsummary: 'Promote a version to live.',\n\t\tresponse: 'object',\n\t\trequestBody: PublishVersionBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/image',\n\t\tscope: 'write',\n\t\tsummary: 'Upload a cover image.',\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'image', required: true, description: 'PNG, JPEG, WebP or GIF.' }],\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/definitions/{guid}/share-links',\n\t\tscope: 'read',\n\t\tsummary: 'List share links. 404 when sharing is disabled on the instance.',\n\t\tresponse: 'collection',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/definitions/{guid}/share-links',\n\t\tscope: 'write',\n\t\tidempotent: true,\n\t\tsummary: 'Create a share link. The raw token is returned once and never again.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateShareLinkBodySchema,\n\t\terrors: [400, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/definitions/{guid}/share-links/{linkId}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke a share link.',\n\t\tresponse: 'empty',\n\t\terrors: [404]\n\t},\n\n\t// ==========================================================================\n\t// Projects\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects',\n\t\tscope: 'read',\n\t\tsummary: 'List projects the caller can view.',\n\t\tresponse: 'collection',\n\t\treturns:\n\t\t\t'Each item has `canCreateDefinitions`: whether `POST /definitions` would accept this project from the caller, scopes included for an API token.'\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects',\n\t\tscope: 'create_projects',\n\t\tidempotent: true,\n\t\tsummary:\n\t\t\t'Create a project. A key with `create_projects` but not `write` may create private projects only, with `autoJoinOnUpload` off.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateProjectBodySchema,\n\t\terrors: [400, 403, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'read',\n\t\tsummary: \"Project record plus the caller's effective role and capabilities.\",\n\t\tresponse: 'object',\n\t\terrors: [404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Update project settings. Owner-only.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateProjectBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/projects/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Delete a project.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/projects/{id}/members',\n\t\tscope: 'read',\n\t\tsummary: 'List project members.',\n\t\tresponse: 'collection',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects/{id}/members',\n\t\tscope: 'write',\n\t\tsummary: 'Add a member. The target must already belong to the org.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: AddProjectMemberBodySchema,\n\t\terrors: [400, 403, 404]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/projects/{id}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Change a member role.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateProjectMemberBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/projects/{id}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove a member. Idempotent.',\n\t\tresponse: 'empty',\n\t\tquery: [\n\t\t\t{\n\t\t\t\tname: 'confirm',\n\t\t\t\tdescription: 'Set to `true` to remove a co-owner; without it the call returns 409.'\n\t\t\t}\n\t\t],\n\t\terrors: [403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/projects/{id}/reclaim',\n\t\tscope: 'write',\n\t\tsummary: 'Claim ownership of an unowned project.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\terrors: [403, 404, 409]\n\t},\n\n\t// ==========================================================================\n\t// Orgs\n\t// ==========================================================================\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}',\n\t\tscope: 'read',\n\t\tsummary: \"Org record. The org must be the caller's acting org.\",\n\t\tresponse: 'object',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/members',\n\t\tscope: 'read',\n\t\tsummary: 'List org members.',\n\t\tresponse: 'collection',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/orgs/{orgId}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Change an org role or permission set. The sole owner cannot be demoted.',\n\t\tresponse: 'empty',\n\t\trequestBody: UpdateOrgMemberBodySchema,\n\t\terrors: [400, 403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/members/{userId}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove an org member. The sole owner cannot be removed.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404, 409]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/invites',\n\t\tscope: 'read',\n\t\tsummary: 'List pending invites. Browser session only: an API key gets 403.',\n\t\tresponse: 'collection',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/invites',\n\t\tscope: 'write',\n\t\tsummary:\n\t\t\t'Invite someone to the org. The accept URL is returned once. Browser session only: an API key gets 403.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateInviteBodySchema,\n\t\terrors: [400, 403, 409]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/invites/{id}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke an invite.',\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/invites/{id}/resend',\n\t\tscope: 'write',\n\t\tsummary:\n\t\t\t'Re-send an invite. Issues a replacement and revokes the original, so the previous link stops working. Browser session only: an API key gets 403.',\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\terrors: [403, 404, 409]\n\t},\n\t// Internal and session-only: a key can never manage keys.\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/tokens',\n\t\tscope: 'read',\n\t\tsummary: 'Your API tokens in this org, revoked and expired included.',\n\t\tinternal: true,\n\t\tresponse: 'collection',\n\t\tquery: [\n\t\t\t{ name: 'all', description: \"`true` for every member's tokens. Needs `manage_org_members`.\" }\n\t\t],\n\t\terrors: [403, 503]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/tokens',\n\t\tscope: 'write',\n\t\tsummary: 'Create an API token acting as you. The raw key is returned once, as `secret`.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tstatus: 201,\n\t\trequestBody: CreateApiTokenBodySchema,\n\t\terrors: [400, 403, 503]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/tokens/{tokenId}',\n\t\tscope: 'write',\n\t\tsummary: 'Revoke an API token: your own, or any in the org with `manage_org_members`.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [403, 404, 503]\n\t},\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/orgs/{orgId}/compute',\n\t\tscope: 'read',\n\t\tsummary: 'Org compute-server overrides and the shared catalog.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: [403]\n\t},\n\t{\n\t\tmethod: 'PATCH',\n\t\tpath: '/orgs/{orgId}/compute',\n\t\tscope: 'write',\n\t\tsummary: 'Replace the org compute-server overrides.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\trequestBody: OrgComputePatchBodySchema,\n\t\terrors: [400, 403]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/orgs/{orgId}/assets/{kind}',\n\t\tscope: 'write',\n\t\tsummary: 'Upload an org branding asset.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'image', required: true, description: 'PNG, JPEG, WebP, GIF or SVG.' }],\n\t\terrors: [400, 403, 404]\n\t},\n\t{\n\t\tmethod: 'DELETE',\n\t\tpath: '/orgs/{orgId}/assets/{kind}',\n\t\tscope: 'write',\n\t\tsummary: 'Remove an org branding asset.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [403, 404]\n\t},\n\n\t// ==========================================================================\n\t// Compute\n\t// ==========================================================================\n\t//\n\t// Internal: accepts a remote `definitionUrl` and the anonymous share-token\n\t// flow, neither part of the public contract. Public callers solve through\n\t// `/definitions/{guid}/solve`.\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/compute',\n\t\tscope: 'solve',\n\t\tsummary: 'Generic solve, including remote definition URLs and share-token access.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: solveErrors\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/compute/schema',\n\t\tscope: 'upload',\n\t\tsummary: 'Extract UI schemas from an uploaded file before it becomes a definition.',\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tmultipart: [{ field: 'file', required: true, description: 'The `.gh` or `.ghx` file.' }],\n\t\tquery: [\n\t\t\t{ name: 'projectId', description: 'Project the file will belong to.' },\n\t\t\t{ name: 'computeServerId', description: 'Pin to a compute server.' }\n\t\t],\n\t\terrors: [400, 403, 422, 503]\n\t},\n\n\t// ==========================================================================\n\t// Live solve events\n\t// ==========================================================================\n\t//\n\t// Internal: the browser's live channel and the plugin's callback into it. Both\n\t// are shaped by the Selva plugin and web app, not by the public contract.\n\t{\n\t\tmethod: 'GET',\n\t\tpath: '/solve-events',\n\t\tscope: 'read',\n\t\tsummary: \"The tab's live event stream (SSE). Solves that name its `streamId` report here.\",\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\tquery: [{ name: 'streamId', description: 'Minted by the tab, 16-64 URL-safe characters.' }],\n\t\terrors: [400, 401, 409]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/solve-events/{solveId}',\n\t\tscope: 'write',\n\t\tsummary: \"The plugin's callback from inside a Compute solve. The reply carries `abort`.\",\n\t\tinternal: true,\n\t\tresponse: 'object',\n\t\terrors: [400, 401, 410]\n\t},\n\t{\n\t\tmethod: 'POST',\n\t\tpath: '/solve/{solveId}/cancel',\n\t\tscope: 'solve',\n\t\tsummary: 'Ask a running solve to abort. Cooperative: it stops at the next component.',\n\t\tinternal: true,\n\t\tresponse: 'empty',\n\t\terrors: [401, 404]\n\t}\n];\n\n/** `/definitions/{guid}` → the SvelteKit directory form `definitions/[guid]`. */\nexport function toRoutePath(openApiPath: string): string {\n\treturn openApiPath.replace(/^\\//, '').replace(/\\{(\\w+)\\}/g, '[$1]');\n}\n\nexport function endpointKey(method: HttpMethod, path: string): string {\n\treturn `${method} ${path}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiCA,IAAM,cAAc;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG;AAE5C,IAAa,eAA2B;CACvC;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SAAS;EACT,UAAU;CACX;CAKA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SACC;EACD,UAAU;EACV,SACC;CACF;CAEA;EACC,QAAQ;EACR,MAAM;EACN,OAAO;EACP,SACC;EACD,UAAU;EACV,QAAQ,CAAC,KAAK,GAAG;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M;EACN,OAAO;EACP,SAAS;EACT,UAAU;EACV,UAAU;EACV,QAAQ,CAAC,KAAK,GAAG;CAClB;AACD"}
@@ -52,6 +52,6 @@ async function tryResolveShareToken(request, url, requestedDefinitionId, request
52
52
  }
53
53
  };
54
54
  }
55
- export { tryResolveShareToken as t };
55
+ export { tryResolveShareToken as n, readShareToken as t };
56
56
 
57
57
  //# sourceMappingURL=resolve.server.js.map
@@ -146,6 +146,18 @@ function resolveApiKey(submitted, storedKey) {
146
146
  function storedKeysById(scopedServers) {
147
147
  return new Map(scopedServers.map((s) => [s.id, s.apiKey]));
148
148
  }
149
- export { validateIncomingServers as a, storedKeysById as i, assertStoredKeysReadable as n, evictChangedServers as o, resolveApiKey as r, assertKeyNotRetargeted as t };
149
+ /**
150
+ * The whole apiKey merge for one scope's write: refuses an unreadable or
151
+ * retargeted key with 409, then returns the key to store for each submitted id.
152
+ * `scopedStored` must be read with `includeApiKeys` and hold only the caller's
153
+ * scope.
154
+ */
155
+ function mergeApiKeys(incoming, scopedStored) {
156
+ assertStoredKeysReadable(incoming, scopedStored);
157
+ assertKeyNotRetargeted(incoming, scopedStored);
158
+ const stored = storedKeysById(scopedStored);
159
+ return new Map(incoming.map((s) => [s.id, resolveApiKey(s.apiKey, stored.get(s.id))]));
160
+ }
161
+ export { validateIncomingServers as n, evictChangedServers as r, mergeApiKeys as t };
150
162
 
151
163
  //# sourceMappingURL=server-config-write.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config-write.js","names":[],"sources":["../../../../server/src/compute/evict-changed-servers.ts","../../../../server/src/compute/server-config-write.ts"],"sourcesContent":["/**\n * A warm compute client caches on server `id`, so a rotated `serverUrl`/`apiKey`\n * keeps the same cache key with stale connection details — it never ages out on\n * its own. The config-write path has to evict explicitly.\n *\n * The eviction sink is a parameter rather than an import: which cache holds the\n * warm clients is the host's decision, and importing one would drag a whole\n * solve engine into every consumer that only wants the diff.\n */\n\n/** The connection-identifying fields — a change in either makes the warm client stale. */\nexport interface ServerConnection {\n\tid: string;\n\tserverUrl: string;\n\tapiKey?: string;\n}\n\n/**\n * Drop the warm client for every server that was removed or whose connection\n * details changed. `prev` and `next` are the scoped server sets before and\n * after the write; unchanged servers are left alone.\n */\nexport function evictChangedServers(\n\tprev: readonly ServerConnection[],\n\tnext: readonly ServerConnection[],\n\tevict: (id: string) => void\n): void {\n\tconst nextById = new Map(next.map((s) => [s.id, s]));\n\n\t// Removed: no longer in `next`.\n\tfor (const before of prev) {\n\t\tif (!nextById.has(before.id)) evict(before.id);\n\t}\n\n\t// Rotated: same id, different URL or key.\n\tconst prevById = new Map(prev.map((s) => [s.id, s]));\n\tfor (const after of next) {\n\t\tconst before = prevById.get(after.id);\n\t\tif (before && (before.serverUrl !== after.serverUrl || before.apiKey !== after.apiKey)) {\n\t\t\tevict(after.id);\n\t\t}\n\t}\n}\n","/**\n * Shared write-path rules for compute server config.\n *\n * Two routes accept a server set: `/api/admin/compute` (platform scope,\n * `manage_compute`) and `/api/v1/orgs/{orgId}/compute` (org scope,\n * `manage_org_compute`). They differ in who may call them, what extra fields\n * they carry (`sharedWith` vs `ownerOrgId`), and how they validate the default\n * selection — but the field validation and the apiKey merge below must behave\n * identically in both, so they live here rather than in either handler.\n *\n * The apiKey merge is why this file exists: if the two copies disagree, a\n * stored credential silently gets cleared or leaked, and nothing fails at\n * build time.\n */\n\nimport { GuidSchema, trimTrailing } from '@selvajs/platform';\nimport { isEncryptedSecret } from '@selvajs/platform/computeServer';\nimport { isLinkLocalUrl } from './safe-url.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\n\n/**\n * A stored `serverUrl` is fetched server-side on every status probe, every\n * purge/shutdown action, and every solve, so an unfiltered one is an SSRF\n * primitive handed to whoever holds `manage_compute`. Two rules:\n *\n * - Scheme allowlist: `http`/`https`. `file:`, `gopher:` and friends are never\n * a Rhino.Compute endpoint.\n * - Link-local (`169.254.0.0/16`) is refused. That range carries the cloud\n * metadata service at `169.254.169.254`, which hands out the host's own IAM\n * credentials to anything running on the box.\n *\n * **Loopback and RFC1918 are deliberately allowed.** Running compute on\n * `localhost:6500` or a LAN box is the ordinary self-hosted layout, not an\n * attack — most deployments reach their compute server over exactly those\n * addresses. Blocking them by default would break those instances on upgrade\n * and push every operator toward an opt-out flag, and a guard that everyone\n * disables protects nobody. So the check is narrowed to the range where no\n * legitimate compute server ever lives.\n *\n * What this does not stop: a privileged admin pointing the app at an internal\n * host to probe it. That is a real but much weaker concern than credential\n * theft, it needs `manage_compute` already, and it is inseparable from the\n * legitimate case. Revisit if `manage_org_compute` is ever delegated widely on\n * a multi-tenant instance.\n *\n * `isLinkLocalUrl` is reused rather than hand-rolled because a string compare\n * against `169.254.169.254` misses the encodings that reach the same address:\n * `http://2852039166/`, `http://0xa9fea9fe/`, `http://0251.0376.0251.0376/`.\n */\nfunction assertUsableServerUrl(serverUrl: string): void {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(serverUrl);\n\t} catch {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid serverUrl: ${serverUrl}`);\n\t}\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `serverUrl must use http or https: ${serverUrl}`);\n\t}\n\tif (isLinkLocalUrl(serverUrl)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`serverUrl points at the link-local range, which carries the cloud metadata service: ${serverUrl}`\n\t\t);\n\t}\n}\n\n/** The fields every incoming server carries, whatever its scope. */\nexport interface IncomingServerBase {\n\tid: string;\n\tlabel: string;\n\tserverUrl: string;\n\t/**\n\t * `undefined` → preserve the stored key; `null` → clear it;\n\t * non-empty string → replace it. See {@link resolveApiKey}.\n\t */\n\tapiKey?: string | null;\n}\n\n/**\n * Validates the scope-independent fields of every submitted server. Throws the\n * first failure as a 400; scope-specific fields (`sharedWith`, `ownerOrgId`)\n * are the caller's business.\n */\nexport function validateIncomingServers(servers: readonly IncomingServerBase[]): void {\n\tconst seen = new Set<string>();\n\tfor (const s of servers) {\n\t\tif (!s.id || typeof s.id !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs an id');\n\t\tif (!GuidSchema.safeParse(s.id).success)\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id must be a UUID: ${s.id}`);\n\t\tif (seen.has(s.id))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id appears more than once: ${s.id}`);\n\t\tseen.add(s.id);\n\t\tif (!s.label || typeof s.label !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a label');\n\t\tif (!s.serverUrl || typeof s.serverUrl !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a serverUrl');\n\t\tassertUsableServerUrl(s.serverUrl);\n\t\tif (s.apiKey !== undefined && s.apiKey !== null && typeof s.apiKey !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a string, null, or omitted');\n\t\t// Clients never receive stored keys, so an envelope here is someone else's\n\t\t// ciphertext being replayed against a URL they control.\n\t\tif (s.apiKey && isEncryptedSecret(s.apiKey))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a plaintext key');\n\t}\n}\n\n/**\n * A key that failed to decrypt reads as `hasApiKey` with no `apiKey`. Saving with\n * the field omitted would write `undefined` over the ciphertext, destroying the\n * key the logs tell the operator to recover by restoring `SELVA_AT_REST_KEY`.\n * Replacing or clearing it is a decision, so those pass.\n */\nexport function assertStoredKeysReadable(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'apiKey'>[],\n\tstored: readonly { id: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst unreadable = new Set(stored.filter((s) => s.hasApiKey && !s.apiKey).map((s) => s.id));\n\tfor (const s of incoming) {\n\t\tif (unreadable.has(s.id) && (s.apiKey === undefined || s.apiKey === '')) {\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t`The stored key for server ${s.id} cannot be decrypted. Restore the original SELVA_AT_REST_KEY, or re-enter the key.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * An omitted key is kept, so without this check anyone who may save the config\n * could point a server at their own host and have the next solve send them the\n * stored key, which they never saw. Moving a server needs the key re-entered or\n * cleared.\n */\nexport function assertKeyNotRetargeted(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tstored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst byId = new Map(stored.map((s) => [s.id, s]));\n\tfor (const s of incoming) {\n\t\tconst prev = byId.get(s.id);\n\t\tif (!prev || !(prev.hasApiKey || prev.apiKey)) continue;\n\t\tif (s.apiKey === null || (typeof s.apiKey === 'string' && s.apiKey !== '')) continue;\n\t\tif (sameServerUrl(prev.serverUrl, s.serverUrl)) continue;\n\t\tapiError(\n\t\t\t409,\n\t\t\tApiErrorCode.CONFLICT,\n\t\t\t`Server ${s.id} has a new URL. Re-enter its API key, or clear it, to save.`\n\t\t);\n\t}\n}\n\nfunction sameServerUrl(a: string, b: string): boolean {\n\tconst normalize = (u: string) => {\n\t\ttry {\n\t\t\treturn trimTrailing(new URL(u.trim()).href, '/');\n\t\t} catch {\n\t\t\treturn trimTrailing(u.trim(), '/');\n\t\t}\n\t};\n\treturn normalize(a) === normalize(b);\n}\n\n/**\n * The UI never receives stored keys — it sends back `hasApiKey` and omits the\n * field for servers the operator didn't touch. So \"omitted\" cannot mean \"clear\":\n * it has to preserve, or every save through the settings form would wipe the\n * keys of every server the operator left alone. Clearing is explicit (`null`);\n * an empty string is treated as \"not provided\" since that's what an untouched\n * password input submits.\n */\nexport function resolveApiKey(\n\tsubmitted: string | null | undefined,\n\tstoredKey: string | undefined\n): string | undefined {\n\tif (submitted === null) return undefined;\n\treturn submitted ? submitted : storedKey;\n}\n\n/**\n * Builds the id → stored-key lookup the merge reads. The caller passes only the\n * servers in its own scope, so one scope's write can never resolve a key from\n * another's rows.\n */\nexport function storedKeysById(\n\tscopedServers: readonly { id: string; apiKey?: string }[]\n): Map<string, string | undefined> {\n\treturn new Map(scopedServers.map((s) => [s.id, s.apiKey]));\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,oBACf,MACA,MACA,OACO;CACP,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CAGnD,KAAK,MAAM,UAAU,MACpB,IAAI,CAAC,SAAS,IAAI,OAAO,EAAE,GAAG,MAAM,OAAO,EAAE;CAI9C,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CACnD,KAAK,MAAM,SAAS,MAAM;EACzB,MAAM,SAAS,SAAS,IAAI,MAAM,EAAE;EACpC,IAAI,WAAW,OAAO,cAAc,MAAM,aAAa,OAAO,WAAW,MAAM,SAC9E,MAAM,MAAM,EAAE;CAEhB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOA,SAAS,sBAAsB,WAAyB;CACvD,IAAI;CACJ,IAAI;EACH,SAAS,IAAI,IAAI,SAAS;CAC3B,QAAQ;EACP,SAAS,KAAK,aAAa,mBAAmB,sBAAsB,WAAW;CAChF;CACA,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACtD,SAAS,KAAK,aAAa,mBAAmB,qCAAqC,WAAW;CAE/F,IAAI,eAAe,SAAS,GAC3B,SACC,KACA,aAAa,mBACb,uFAAuF,WACxF;AAEF;;;;;;AAmBA,SAAgB,wBAAwB,SAA8C;CACrF,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,KAAK,SAAS;EACxB,IAAI,CAAC,EAAE,MAAM,OAAO,EAAE,OAAO,UAC5B,SA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a,KAAK,SAAS;EAC/C,IAAI,EAAE,WAAW,QAAS,OAAO,EAAE,WAAW,YAAY,EAAE,WAAW,IAAK;EAC5E,IAAI,cAAc,KAAK,WAAW,EAAE,SAAS,GAAG;EAChD,SACC,KACA,aAAa,UACb,UAAU,EAAE,GAAG,4DAChB;CACD;AACD;AAEA,SAAS,cAAc,GAAW,GAAoB;CACrD,MAAM,aAAa,MAAc;EAChC,IAAI;GACH,OAAO,aAAa,IAAI,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG;EAChD,QAAQ;GACP,OAAO,aAAa,EAAE,KAAK,GAAG,GAAG;EAClC;CACD;CACA,OAAO,UAAU,CAAC,MAAM,UAAU,CAAC;AACpC;;;;;;;;;AAUA,SAAgB,cACf,WACA,WACqB;CACrB,IAAI,cAAc,MAAM,OAAO,KAAA;CAC/B,OAAO,YAAY,YAAY;AAChC;;;;;;AAOA,SAAgB,eACf,eACkC;CAClC,OAAO,IAAI,IAAI,cAAc,KAAK,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1D"}
1
+ {"version":3,"file":"server-config-write.js","names":[],"sources":["../../../../server/src/compute/evict-changed-servers.ts","../../../../server/src/compute/server-config-write.ts"],"sourcesContent":["/**\n * A warm compute client caches on server `id`, so a rotated `serverUrl`/`apiKey`\n * keeps the same cache key with stale connection details — it never ages out on\n * its own. The config-write path has to evict explicitly.\n *\n * The eviction sink is a parameter rather than an import: which cache holds the\n * warm clients is the host's decision, and importing one would drag a whole\n * solve engine into every consumer that only wants the diff.\n */\n\n/** The connection-identifying fields — a change in either makes the warm client stale. */\nexport interface ServerConnection {\n\tid: string;\n\tserverUrl: string;\n\tapiKey?: string;\n}\n\n/**\n * Drop the warm client for every server that was removed or whose connection\n * details changed. `prev` and `next` are the scoped server sets before and\n * after the write; unchanged servers are left alone.\n */\nexport function evictChangedServers(\n\tprev: readonly ServerConnection[],\n\tnext: readonly ServerConnection[],\n\tevict: (id: string) => void\n): void {\n\tconst nextById = new Map(next.map((s) => [s.id, s]));\n\n\t// Removed: no longer in `next`.\n\tfor (const before of prev) {\n\t\tif (!nextById.has(before.id)) evict(before.id);\n\t}\n\n\t// Rotated: same id, different URL or key.\n\tconst prevById = new Map(prev.map((s) => [s.id, s]));\n\tfor (const after of next) {\n\t\tconst before = prevById.get(after.id);\n\t\tif (before && (before.serverUrl !== after.serverUrl || before.apiKey !== after.apiKey)) {\n\t\t\tevict(after.id);\n\t\t}\n\t}\n}\n","/**\n * Shared write-path rules for compute server config.\n *\n * Two routes accept a server set: `/api/admin/compute` (platform scope,\n * `manage_compute`) and `/api/v1/orgs/{orgId}/compute` (org scope,\n * `manage_org_compute`). They differ in who may call them, what extra fields\n * they carry (`sharedWith` vs `ownerOrgId`), and how they validate the default\n * selection — but the field validation and the apiKey merge below must behave\n * identically in both, so they live here rather than in either handler.\n *\n * The apiKey merge is why this file exists: if the two copies disagree, a\n * stored credential silently gets cleared or leaked, and nothing fails at\n * build time.\n */\n\nimport { GuidSchema, trimTrailing } from '@selvajs/platform';\nimport { isEncryptedSecret } from '@selvajs/platform/computeServer';\nimport { isLinkLocalUrl } from './safe-url.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\n\n/**\n * A stored `serverUrl` is fetched server-side on every status probe, every\n * purge/shutdown action, and every solve, so an unfiltered one is an SSRF\n * primitive handed to whoever holds `manage_compute`. Two rules:\n *\n * - Scheme allowlist: `http`/`https`. `file:`, `gopher:` and friends are never\n * a Rhino.Compute endpoint.\n * - Link-local (`169.254.0.0/16`) is refused. That range carries the cloud\n * metadata service at `169.254.169.254`, which hands out the host's own IAM\n * credentials to anything running on the box.\n *\n * **Loopback and RFC1918 are deliberately allowed.** Running compute on\n * `localhost:6500` or a LAN box is the ordinary self-hosted layout, not an\n * attack — most deployments reach their compute server over exactly those\n * addresses. Blocking them by default would break those instances on upgrade\n * and push every operator toward an opt-out flag, and a guard that everyone\n * disables protects nobody. So the check is narrowed to the range where no\n * legitimate compute server ever lives.\n *\n * What this does not stop: a privileged admin pointing the app at an internal\n * host to probe it. That is a real but much weaker concern than credential\n * theft, it needs `manage_compute` already, and it is inseparable from the\n * legitimate case. Revisit if `manage_org_compute` is ever delegated widely on\n * a multi-tenant instance.\n *\n * `isLinkLocalUrl` is reused rather than hand-rolled because a string compare\n * against `169.254.169.254` misses the encodings that reach the same address:\n * `http://2852039166/`, `http://0xa9fea9fe/`, `http://0251.0376.0251.0376/`.\n */\nfunction assertUsableServerUrl(serverUrl: string): void {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(serverUrl);\n\t} catch {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid serverUrl: ${serverUrl}`);\n\t}\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `serverUrl must use http or https: ${serverUrl}`);\n\t}\n\tif (isLinkLocalUrl(serverUrl)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`serverUrl points at the link-local range, which carries the cloud metadata service: ${serverUrl}`\n\t\t);\n\t}\n}\n\n/** The fields every incoming server carries, whatever its scope. */\nexport interface IncomingServerBase {\n\tid: string;\n\tlabel: string;\n\tserverUrl: string;\n\t/**\n\t * `undefined` → preserve the stored key; `null` → clear it;\n\t * non-empty string → replace it. See {@link resolveApiKey}.\n\t */\n\tapiKey?: string | null;\n}\n\n/**\n * Validates the scope-independent fields of every submitted server. Throws the\n * first failure as a 400; scope-specific fields (`sharedWith`, `ownerOrgId`)\n * are the caller's business.\n */\nexport function validateIncomingServers(servers: readonly IncomingServerBase[]): void {\n\tconst seen = new Set<string>();\n\tfor (const s of servers) {\n\t\tif (!s.id || typeof s.id !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs an id');\n\t\tif (!GuidSchema.safeParse(s.id).success)\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id must be a UUID: ${s.id}`);\n\t\tif (seen.has(s.id))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id appears more than once: ${s.id}`);\n\t\tseen.add(s.id);\n\t\tif (!s.label || typeof s.label !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a label');\n\t\tif (!s.serverUrl || typeof s.serverUrl !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a serverUrl');\n\t\tassertUsableServerUrl(s.serverUrl);\n\t\tif (s.apiKey !== undefined && s.apiKey !== null && typeof s.apiKey !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a string, null, or omitted');\n\t\t// Clients never receive stored keys, so an envelope here is someone else's\n\t\t// ciphertext being replayed against a URL they control.\n\t\tif (s.apiKey && isEncryptedSecret(s.apiKey))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a plaintext key');\n\t}\n}\n\n/**\n * A key that failed to decrypt reads as `hasApiKey` with no `apiKey`. Saving with\n * the field omitted would write `undefined` over the ciphertext, destroying the\n * key the logs tell the operator to recover by restoring `SELVA_AT_REST_KEY`.\n * Replacing or clearing it is a decision, so those pass.\n */\nexport function assertStoredKeysReadable(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'apiKey'>[],\n\tstored: readonly { id: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst unreadable = new Set(stored.filter((s) => s.hasApiKey && !s.apiKey).map((s) => s.id));\n\tfor (const s of incoming) {\n\t\tif (unreadable.has(s.id) && (s.apiKey === undefined || s.apiKey === '')) {\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t`The stored key for server ${s.id} cannot be decrypted. Restore the original SELVA_AT_REST_KEY, or re-enter the key.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * An omitted key is kept, so without this check anyone who may save the config\n * could point a server at their own host and have the next solve send them the\n * stored key, which they never saw. Moving a server needs the key re-entered or\n * cleared.\n */\nexport function assertKeyNotRetargeted(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tstored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst byId = new Map(stored.map((s) => [s.id, s]));\n\tfor (const s of incoming) {\n\t\tconst prev = byId.get(s.id);\n\t\tif (!prev || !(prev.hasApiKey || prev.apiKey)) continue;\n\t\tif (s.apiKey === null || (typeof s.apiKey === 'string' && s.apiKey !== '')) continue;\n\t\tif (sameServerUrl(prev.serverUrl, s.serverUrl)) continue;\n\t\tapiError(\n\t\t\t409,\n\t\t\tApiErrorCode.CONFLICT,\n\t\t\t`Server ${s.id} has a new URL. Re-enter its API key, or clear it, to save.`\n\t\t);\n\t}\n}\n\nfunction sameServerUrl(a: string, b: string): boolean {\n\tconst normalize = (u: string) => {\n\t\ttry {\n\t\t\treturn trimTrailing(new URL(u.trim()).href, '/');\n\t\t} catch {\n\t\t\treturn trimTrailing(u.trim(), '/');\n\t\t}\n\t};\n\treturn normalize(a) === normalize(b);\n}\n\n/**\n * The UI never receives stored keys — it sends back `hasApiKey` and omits the\n * field for servers the operator didn't touch. So \"omitted\" cannot mean \"clear\":\n * it has to preserve, or every save through the settings form would wipe the\n * keys of every server the operator left alone. Clearing is explicit (`null`);\n * an empty string is treated as \"not provided\" since that's what an untouched\n * password input submits.\n */\nexport function resolveApiKey(\n\tsubmitted: string | null | undefined,\n\tstoredKey: string | undefined\n): string | undefined {\n\tif (submitted === null) return undefined;\n\treturn submitted ? submitted : storedKey;\n}\n\n/**\n * Builds the id → stored-key lookup the merge reads. The caller passes only the\n * servers in its own scope, so one scope's write can never resolve a key from\n * another's rows.\n */\nexport function storedKeysById(\n\tscopedServers: readonly { id: string; apiKey?: string }[]\n): Map<string, string | undefined> {\n\treturn new Map(scopedServers.map((s) => [s.id, s.apiKey]));\n}\n\n/**\n * The whole apiKey merge for one scope's write: refuses an unreadable or\n * retargeted key with 409, then returns the key to store for each submitted id.\n * `scopedStored` must be read with `includeApiKeys` and hold only the caller's\n * scope.\n */\nexport function mergeApiKeys(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tscopedStored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): Map<string, string | undefined> {\n\tassertStoredKeysReadable(incoming, scopedStored);\n\tassertKeyNotRetargeted(incoming, scopedStored);\n\tconst stored = storedKeysById(scopedStored);\n\treturn new Map(incoming.map((s) => [s.id, resolveApiKey(s.apiKey, stored.get(s.id))]));\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,oBACf,MACA,MACA,OACO;CACP,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CAGnD,KAAK,MAAM,UAAU,MACpB,IAAI,CAAC,SAAS,IAAI,OAAO,EAAE,GAAG,MAAM,OAAO,EAAE;CAI9C,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CACnD,KAAK,MAAM,SAAS,MAAM;EACzB,MAAM,SAAS,SAAS,IAAI,MAAM,EAAE;EACpC,IAAI,WAAW,OAAO,cAAc,MAAM,aAAa,OAAO,WAAW,MAAM,SAC9E,MAAM,MAAM,EAAE;CAEhB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOA,SAAS,sBAAsB,WAAyB;CACvD,IAAI;CACJ,IAAI;EACH,SAAS,IAAI,IAAI,SAAS;CAC3B,QAAQ;EACP,SAAS,KAAK,aAAa,mBAAmB,sBAAsB,WAAW;CAChF;CACA,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACtD,SAAS,KAAK,aAAa,mBAAmB,qCAAqC,WAAW;CAE/F,IAAI,eAAe,SAAS,G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A,QACO;CACP,MAAM,OAAO,IAAI,IAAI,OAAO,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CACjD,KAAK,MAAM,KAAK,UAAU;EACzB,MAAM,OAAO,KAAK,IAAI,EAAE,EAAE;EAC1B,IAAI,CAAC,QAAQ,EAAE,KAAK,aAAa,KAAK,SAAS;EAC/C,IAAI,EAAE,WAAW,QAAS,OAAO,EAAE,WAAW,YAAY,EAAE,WAAW,IAAK;EAC5E,IAAI,cAAc,KAAK,WAAW,EAAE,SAAS,GAAG;EAChD,SACC,KACA,aAAa,UACb,UAAU,EAAE,GAAG,4DAChB;CACD;AACD;AAEA,SAAS,cAAc,GAAW,GAAoB;CACrD,MAAM,aAAa,MAAc;EAChC,IAAI;GACH,OAAO,aAAa,IAAI,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG;EAChD,QAAQ;GACP,OAAO,aAAa,EAAE,KAAK,GAAG,GAAG;EAClC;CACD;CACA,OAAO,UAAU,CAAC,MAAM,UAAU,CAAC;AACpC;;;;;;;;;AAUA,SAAgB,cACf,WACA,WACqB;CACrB,IAAI,cAAc,MAAM,OAAO,KAAA;CAC/B,OAAO,YAAY,YAAY;AAChC;;;;;;AAOA,SAAgB,eACf,eACkC;CAClC,OAAO,IAAI,IAAI,cAAc,KAAK,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1D;;;;;;;AAQA,SAAgB,aACf,UACA,cACkC;CAClC,yBAAyB,UAAU,YAAY;CAC/C,uBAAuB,UAAU,YAAY;CAC7C,MAAM,SAAS,eAAe,YAAY;CAC1C,OAAO,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,EAAE,IAAI,cAAc,EAAE,QAAQ,OAAO,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACtF"}
@@ -67,6 +67,12 @@ function readRemoteInputs(inputs) {
67
67
  if (!(Array.isArray(inputs) && inputs.every((input) => typeof input === "object" && input !== null && typeof input.id === "string" && typeof input.nickname === "string"))) apiError(400, ApiErrorCode.VALIDATION_FAILED, "A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.");
68
68
  return inputs;
69
69
  }
70
+ function admittedSolveInputs(schema, inputs, values) {
71
+ const solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);
72
+ const serverOnly = postedServerSourcedIds(solveInputs, values);
73
+ if (serverOnly.length > 0) apiError(400, ApiErrorCode.VALIDATION_FAILED, `These inputs are filled on the server and may not be posted in values: ${serverOnly.join(", ")}.`);
74
+ return solveInputs;
75
+ }
70
76
  /**
71
77
  * Run a solve and return the HTTP response.
72
78
  *
@@ -203,6 +209,7 @@ async function runSolve(params) {
203
209
  mark("remoteDef");
204
210
  }
205
211
  const defLoadMs = performance.now() - loadStart;
212
+ let solveInputs = storedSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;
206
213
  if (sharedAccess) {
207
214
  if (await providers.data.shareLinks.tryIncrementSolveCount(solveCtx, sharedAccess.link.id) === null) {
208
215
  recordMetric("share_cap");
@@ -228,9 +235,7 @@ async function runSolve(params) {
228
235
  mark("schemaBackfill");
229
236
  }
230
237
  if (isLocal && !storedSchema) apiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, "This version's inputs could not be read. Retry shortly.");
231
- const solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : readRemoteInputs(inputs);
232
- const serverOnly = postedServerSourcedIds(solveInputs, values);
233
- if (serverOnly.length > 0) apiError(400, ApiErrorCode.VALIDATION_FAILED, `These inputs are filled on the server and may not be posted in values: ${serverOnly.join(", ")}.`);
238
+ solveInputs ??= admittedSolveInputs(storedSchema, inputs, values);
234
239
  const live = bindLiveSolve({
235
240
  ownerKey: liveOwnerKey(access.kind === "user" ? access.ctx.userId : null),
236
241
  streamId,
@@ -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\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// 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\tconst solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : 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\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,OAA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3C,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"}
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,EA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;;;;AAOA,SAAS,kBACR,QACA,SACA,SACA,WACA,WACO;CACP,MAAM,EAAE,YAAY,QAAQ;CAC5B,OAAO,IAAI,MAAM,qCAAqC;EACrD,WAAW;EACX,QAAQ,KAAK,MAAM,SAAS;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"}
@@ -1,11 +1,11 @@
1
1
  import { a as getComputeServerConfigStore } from "../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, y as requireManageCompute } from "../../../../../chunks/access.js";
3
3
  import { i as platformServers } from "../../../../../chunks/utils.js";
4
- import { a as validateIncomingServers, i as storedKeysById, n as assertStoredKeysReadable, o as evictChangedServers$1, r as resolveApiKey, t as assertKeyNotRetargeted } from "../../../../../chunks/server-config-write.js";
4
+ import { n as validateIncomingServers, r as evictChangedServers$1, t as mergeApiKeys } from "../../../../../chunks/server-config-write.js";
5
5
  import "../../../../../chunks/compute.js";
6
- import { n as renderThrown } from "../../../../../chunks/definitions.js";
7
6
  import { t as apiError } from "../../../../../chunks/api-errors.js";
8
7
  import "../../../../../chunks/access2.server.js";
8
+ import { r as noContent, t as apiRoute } from "../../../../../chunks/http2.js";
9
9
  import { s as evictComputeClient } from "../../../../../chunks/engine.server.js";
10
10
  import { t as serverResolver } from "../../../../../chunks/serverResolver.server.js";
11
11
  import { json } from "@sveltejs/kit";
@@ -21,27 +21,19 @@ function evictChangedServers(prev, next) {
21
21
  evictChangedServers$1(prev, next, evictComputeClient);
22
22
  }
23
23
  // src/routes/api/admin/compute/+server.ts
24
- var GET = async ({ locals }) => {
24
+ var GET = apiRoute("Failed to load compute config", async ({ locals }) => {
25
25
  requireManageCompute(locals);
26
- try {
27
- const config = await getComputeServerConfigStore().getConfig(locals.ctx);
28
- const servers = platformServers(config).map(({ apiKey: _apiKey, hasApiKey, ...rest }) => ({
29
- ...rest,
30
- hasApiKey: !!hasApiKey
31
- }));
32
- return json({
33
- servers,
34
- defaultServerId: config.defaultServerId
35
- });
36
- } catch (err) {
37
- locals.log.error("Failed to load compute config", {
38
- component: "Compute GET",
39
- err: renderThrown(err)
40
- });
41
- apiError(500, ApiErrorCode.INTERNAL, "Failed to load compute config");
42
- }
43
- };
44
- var PUT = async ({ request, locals }) => {
26
+ const config = await getComputeServerConfigStore().getConfig(locals.ctx);
27
+ const servers = platformServers(config).map(({ apiKey: _apiKey, hasApiKey, ...rest }) => ({
28
+ ...rest,
29
+ hasApiKey: !!hasApiKey
30
+ }));
31
+ return json({
32
+ servers,
33
+ defaultServerId: config.defaultServerId
34
+ });
35
+ });
36
+ var PUT = apiRoute("Failed to save compute config", async ({ request, locals }) => {
45
37
  requireManageCompute(locals);
46
38
  const body = await request.json().catch(() => null);
47
39
  if (!body || typeof body !== "object") apiError(400, ApiErrorCode.VALIDATION_FAILED, "Invalid request body");
@@ -55,32 +47,22 @@ var PUT = async ({ request, locals }) => {
55
47
  if (incoming.defaultServerId) {
56
48
  if (!incoming.servers.find((s) => s.id === incoming.defaultServerId)) apiError(400, ApiErrorCode.VALIDATION_FAILED, "defaultServerId must reference one of the submitted servers");
57
49
  }
58
- try {
59
- const provider = getComputeServerConfigStore();
60
- const existing = await provider.getConfig(locals.ctx, { includeApiKeys: true });
61
- assertStoredKeysReadable(incoming.servers, platformServers(existing));
62
- assertKeyNotRetargeted(incoming.servers, platformServers(existing));
63
- const storedKeys = storedKeysById(platformServers(existing));
64
- const next = incoming.servers.map(({ id, label, serverUrl, apiKey, sharedWith }) => ({
65
- id,
66
- label,
67
- serverUrl,
68
- scope: "platform",
69
- sharedWith: sharedWith === "all" ? "all" : [...sharedWith],
70
- apiKey: resolveApiKey(apiKey, storedKeys.get(id))
71
- }));
72
- await provider.savePlatformServers(locals.ctx, next, incoming.defaultServerId);
73
- serverResolver.forget();
74
- evictChangedServers(platformServers(existing), next);
75
- return new Response(null, { status: 204 });
76
- } catch (err) {
77
- locals.log.error("Failed to save compute config", {
78
- component: "Compute PUT",
79
- err: renderThrown(err)
80
- });
81
- apiError(500, ApiErrorCode.INTERNAL, "Failed to save compute config");
82
- }
83
- };
50
+ const provider = getComputeServerConfigStore();
51
+ const existing = await provider.getConfig(locals.ctx, { includeApiKeys: true });
52
+ const apiKeys = mergeApiKeys(incoming.servers, platformServers(existing));
53
+ const next = incoming.servers.map(({ id, label, serverUrl, sharedWith }) => ({
54
+ id,
55
+ label,
56
+ serverUrl,
57
+ scope: "platform",
58
+ sharedWith: sharedWith === "all" ? "all" : [...sharedWith],
59
+ apiKey: apiKeys.get(id)
60
+ }));
61
+ await provider.savePlatformServers(locals.ctx, next, incoming.defaultServerId);
62
+ serverResolver.forget();
63
+ evictChangedServers(platformServers(existing), next);
64
+ return noContent();
65
+ });
84
66
  export { GET, PUT };
85
67
 
86
68
  //# sourceMappingURL=_server.ts.js.map