@selvajs/selva 4.20.1-beta.2 → 4.20.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/chunks/{D-SwRD80.js → D-uUm_OB.js} +43 -43
- package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
- package/build/client/_app/immutable/chunks/{D-SwRD80.js.gz → D-uUm_OB.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js +1 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js.br +1 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.hg2qyLJU.js → app.BpT6WkO1.js} +2 -2
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js +1 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/runtime-meta.json +1 -1
- package/build/server/.vite/manifest.json +9 -2
- package/build/server/chunks/access.js +0 -3
- package/build/server/chunks/access.js.map +1 -1
- package/build/server/chunks/definitions.js +178 -1
- package/build/server/chunks/definitions.js.map +1 -1
- package/build/server/chunks/handlers.js +4 -5
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +111 -202
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/registry.js +3 -3
- package/build/server/chunks/registry.js.map +1 -1
- package/build/server/chunks/resolve.server.js +1 -1
- package/build/server/chunks/server-config-write.js +13 -1
- package/build/server/chunks/server-config-write.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +30 -48
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +6 -2
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +8 -8
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +1 -1
- package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
- package/build/server/entries/hooks.server.js +34 -10
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +16 -3
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +132 -89
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +11 -11
- package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js +0 -1
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +0 -1
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +0 -1
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +0 -1
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id with a definition-guid affinity header. */\n\tgetClient: (\n\t\tserver: ComputeServerConfig,\n\t\topts: { definitionGuid: string }\n\t) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer, { definitionGuid: record.guid })).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA0CA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AA2D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AS;GAC7D;EAED;EAEA,IAAI,eAAe,OAAO;GACzB,OAAO,IAAI,KAAK,6BAA6B;IAC5C,WAAW;IACX;IACA,KAAK,aAAa,GAAG;GACtB,CAAC;GACD,MAAM,MAAM,KAAK,8BAA8B,KAAK,KAAK,IAAI,SAAS;EACvE;EACA,MAAM;CACP;AACD;;;;;;AAOA,eAAe,eACd,KACA,WACA,KACyB;CACzB,IAAI;EACH,MAAM,UAAU,MAAM,mBAAmB,CAAC,CAAC,WAAW,KAAK,SAAS;EACpE,IAAI,CAAC,SAAS,OAAO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
|
|
1
|
+
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id with a definition-guid affinity header. */\n\tgetClient: (\n\t\tserver: ComputeServerConfig,\n\t\topts: { definitionGuid: string }\n\t) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer, { definitionGuid: record.guid })).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AA2DA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,OACf,QACA,SAAS,IAAI,WAAW,MACrB;CAEJ,OAAO,eAAe,wBAAwB,KAAK,QAAQ,SAAS,mBAAmB,SAAS;EAC/F,MAAM,YACL,sBAAsB,YAAY,UAAU,OAAO,iBAAiB,OAAO;EAC5E,IAAI,CAAC,WACJ,MAAM,IAAI,oBACT,QACA,eAAe,OAAO,KAAK,WAAW,QAAQ,SAC/C;EAID,MAAM,iBAAiB,YAA0C;GAChE,MAAM,UAAU,MAAM,SAAS,WAAW,KAAK,OAAO,SAAS;GAC/D,IAAI;IACH,OAAO,MAAM,cAAc,KAAK,SAAS,SAAS,MAAM,EACvD,eAAe,OAAO,mBAAmB,KAC1C,CAAC;GACF,SAAS,KAAK;IACb,MAAM,IAAI,o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ACR,SAAS,KAAK;EACb,IAAI,WAAW,GAAG,GAAG,OAAO;EAC5B,MAAM;CACP;AACD;;;;;;AAOA,eAAe,eACd,KACA,WACA,KACyB;CACzB,IAAI;EACH,MAAM,UAAU,MAAM,mBAAmB,CAAC,CAAC,WAAW,KAAK,SAAS;EACpE,IAAI,CAAC,SAAS,OAAO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
|
|
@@ -3647,7 +3647,7 @@ function Scroll_area($$renderer, $$props) {
|
|
|
3647
3647
|
function isFunction(value) {
|
|
3648
3648
|
return typeof value === "function";
|
|
3649
3649
|
}
|
|
3650
|
-
function isObject$
|
|
3650
|
+
function isObject$2(value) {
|
|
3651
3651
|
return value !== null && typeof value === "object";
|
|
3652
3652
|
}
|
|
3653
3653
|
var CLASS_VALUE_PRIMITIVE_TYPES = [
|
|
@@ -3670,7 +3670,7 @@ function isClassValue(value) {
|
|
|
3670
3670
|
var BoxSymbol = Symbol("box");
|
|
3671
3671
|
var isWritableSymbol = Symbol("is-writable");
|
|
3672
3672
|
function isBox(value) {
|
|
3673
|
-
return isObject$
|
|
3673
|
+
return isObject$2(value) && BoxSymbol in value;
|
|
3674
3674
|
}
|
|
3675
3675
|
/**
|
|
3676
3676
|
* @returns Whether the value is a WritableBox
|
|
@@ -4286,10 +4286,10 @@ function afterTick(fn) {
|
|
|
4286
4286
|
// ../../node_modules/.pnpm/svelte-toolbelt@0.9.3_svelte@5.57.3_@typescript-eslint+types@8.72.1_/node_modules/svelte-toolbelt/dist/utils/dom.js
|
|
4287
4287
|
var DOCUMENT_NODE = 9;
|
|
4288
4288
|
function isDocument(node) {
|
|
4289
|
-
return isObject$
|
|
4289
|
+
return isObject$2(node) && node.nodeType === DOCUMENT_NODE;
|
|
4290
4290
|
}
|
|
4291
4291
|
function isWindow(node) {
|
|
4292
|
-
return isObject$
|
|
4292
|
+
return isObject$2(node) && node.constructor?.name === "VisualViewport";
|
|
4293
4293
|
}
|
|
4294
4294
|
function getDocument(node) {
|
|
4295
4295
|
if (isDocument(node)) return node;
|
|
@@ -7010,6 +7010,94 @@ function textureToDataUri(payload) {
|
|
|
7010
7010
|
for (let i = 0; i < data.byteLength; i += step) binary += String.fromCharCode(...data.subarray(i, i + step));
|
|
7011
7011
|
return `data:${mime};base64,${btoa(binary)}`;
|
|
7012
7012
|
}
|
|
7013
|
+
function metadataFail(message, context) {
|
|
7014
|
+
return new VisualizationError(message, ErrorCodes.VALIDATION_ERROR, { context });
|
|
7015
|
+
}
|
|
7016
|
+
var isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7017
|
+
/**
|
|
7018
|
+
* Validates the batch's material and group/mesh metadata against the decoded geometry buffers
|
|
7019
|
+
* before any of it is used arithmetically. Throws on the first inconsistency — a material, group or
|
|
7020
|
+
* mesh that isn't an object, out-of-range `materialId`, non-integer or negative offsets/counts, or a
|
|
7021
|
+
* vertex/index window that overruns the buffers — so malformed or version-skewed metadata fails the
|
|
7022
|
+
* parse loudly instead of corrupting the render.
|
|
7023
|
+
*/
|
|
7024
|
+
function validateBatchMetadata(materials, groups, totalVertexCount, totalIndexCount) {
|
|
7025
|
+
if (!Array.isArray(materials)) throw metadataFail("Batch materials must be an array.", { materials: typeof materials });
|
|
7026
|
+
const badMaterial = materials.findIndex((material) => !isObject$1(material));
|
|
7027
|
+
if (badMaterial !== -1) throw metadataFail("Each material entry must be an object.", { materialIndex: badMaterial });
|
|
7028
|
+
const materialCount = materials.length;
|
|
7029
|
+
if (!Array.isArray(groups)) throw metadataFail("Batch groups must be an array.", { groups: typeof groups });
|
|
7030
|
+
groups.forEach((group, groupIndex) => {
|
|
7031
|
+
if (!isObject$1(group) || !Array.isArray(group.meshes)) throw metadataFail("Each group must be an object with a meshes array.", { groupIndex });
|
|
7032
|
+
if (!group.meshes.every(isObject$1)) throw metadataFail("Each mesh entry must be an object.", { groupIndex });
|
|
7033
|
+
});
|
|
7034
|
+
for (const group of groups) {
|
|
7035
|
+
if (!Number.isInteger(group.materialId) || group.materialId < 0 || group.materialId >= materialCount) throw metadataFail("Group materialId out of range of the materials array.", {
|
|
7036
|
+
materialId: group.materialId,
|
|
7037
|
+
materialCount
|
|
7038
|
+
});
|
|
7039
|
+
for (const mesh of group.meshes) {
|
|
7040
|
+
const fields = {
|
|
7041
|
+
vertexStart: mesh.vertexStart,
|
|
7042
|
+
vertexCount: mesh.vertexCount,
|
|
7043
|
+
indexStart: mesh.indexStart,
|
|
7044
|
+
indexCount: mesh.indexCount
|
|
7045
|
+
};
|
|
7046
|
+
for (const [field, value] of Object.entries(fields)) if (!Number.isInteger(value) || value < 0) throw metadataFail(`Mesh metadata field "${field}" must be a non-negative integer.`, {
|
|
7047
|
+
meshName: mesh.name,
|
|
7048
|
+
field,
|
|
7049
|
+
value
|
|
7050
|
+
});
|
|
7051
|
+
if (mesh.vertexStart + mesh.vertexCount > totalVertexCount) throw metadataFail("Mesh vertex window exceeds the batch vertex buffer.", {
|
|
7052
|
+
meshName: mesh.name,
|
|
7053
|
+
vertexStart: mesh.vertexStart,
|
|
7054
|
+
vertexCount: mesh.vertexCount,
|
|
7055
|
+
totalVertexCount
|
|
7056
|
+
});
|
|
7057
|
+
if (mesh.indexStart + mesh.indexCount > totalIndexCount) throw metadataFail("Mesh index window exceeds the batch index buffer.", {
|
|
7058
|
+
meshName: mesh.name,
|
|
7059
|
+
indexStart: mesh.indexStart,
|
|
7060
|
+
indexCount: mesh.indexCount,
|
|
7061
|
+
totalIndexCount
|
|
7062
|
+
});
|
|
7063
|
+
}
|
|
7064
|
+
}
|
|
7065
|
+
}
|
|
7066
|
+
/**
|
|
7067
|
+
* Error for an index outside its mesh's declared vertex window
|
|
7068
|
+
* `[vertexStart, vertexStart + vertexCount)`. Rebasing (`index - vertexStart`) writes into an
|
|
7069
|
+
* unsigned array, so an out-of-window index would otherwise wrap to ~4 billion and corrupt the
|
|
7070
|
+
* geometry. Range checks live inline in the copy loops (a function call per index measured
|
|
7071
|
+
* noticeably slower at millions of indices) — this only builds the failure.
|
|
7072
|
+
*/
|
|
7073
|
+
function indexOutOfWindow(indexValue, meshMeta) {
|
|
7074
|
+
return metadataFail("Index references a vertex outside its mesh's vertex window.", {
|
|
7075
|
+
meshName: meshMeta.name,
|
|
7076
|
+
indexValue,
|
|
7077
|
+
vertexStart: meshMeta.vertexStart,
|
|
7078
|
+
vertexCount: meshMeta.vertexCount
|
|
7079
|
+
});
|
|
7080
|
+
}
|
|
7081
|
+
/**
|
|
7082
|
+
* Reconstructs world-unit float32 positions from int16 quantized values:
|
|
7083
|
+
* `world = origin + (q + 32767) * scale`. No rotation — the Three scene uses Rhino's Z-up frame,
|
|
7084
|
+
* so vertices pass through as they arrived.
|
|
7085
|
+
*/
|
|
7086
|
+
function dequantizeInt16(q, origin, scale) {
|
|
7087
|
+
const out = new Float32Array(q.length);
|
|
7088
|
+
const ox = origin[0];
|
|
7089
|
+
const oy = origin[1];
|
|
7090
|
+
const oz = origin[2];
|
|
7091
|
+
const sx = scale[0];
|
|
7092
|
+
const sy = scale[1];
|
|
7093
|
+
const sz = scale[2];
|
|
7094
|
+
for (let i = 0; i < q.length; i += 3) {
|
|
7095
|
+
out[i] = ox + (q[i] + 32767) * sx;
|
|
7096
|
+
out[i + 1] = oy + (q[i + 1] + 32767) * sy;
|
|
7097
|
+
out[i + 2] = oz + (q[i + 2] + 32767) * sz;
|
|
7098
|
+
}
|
|
7099
|
+
return out;
|
|
7100
|
+
}
|
|
7013
7101
|
/** Second half of {@link parseBinaryMeshBatch}, for a caller that already holds the raw view. */
|
|
7014
7102
|
function decodeRawMeshBatch(raw) {
|
|
7015
7103
|
let vertices;
|
|
@@ -7080,6 +7168,7 @@ function parseBinaryMeshBatchRaw(input) {
|
|
|
7080
7168
|
} catch (error) {
|
|
7081
7169
|
throw fail(`Failed to parse metadata JSON: ${error instanceof Error ? error.message : String(error)}`, { metadataLen });
|
|
7082
7170
|
}
|
|
7171
|
+
if (!isMetadataShape(metadata)) throw fail("Metadata JSON must be an object whose materials and groups are arrays.", { metadataLen });
|
|
7083
7172
|
if (offset + 56 > bytes.byteLength) throw fail("Insufficient data to read geometry header.", {
|
|
7084
7173
|
expectedBytes: 56,
|
|
7085
7174
|
availableBytes: bytes.byteLength - offset,
|
|
@@ -7170,6 +7259,12 @@ function parseBinaryMeshBatchRaw(input) {
|
|
|
7170
7259
|
colors
|
|
7171
7260
|
};
|
|
7172
7261
|
}
|
|
7262
|
+
/** Missing `materials`/`groups` are allowed: the JSON envelope's copies fill them in. */
|
|
7263
|
+
function isMetadataShape(value) {
|
|
7264
|
+
if (!isObject$1(value)) return false;
|
|
7265
|
+
const { materials, groups } = value;
|
|
7266
|
+
return (materials === void 0 || Array.isArray(materials)) && (groups === void 0 || Array.isArray(groups));
|
|
7267
|
+
}
|
|
7173
7268
|
/**
|
|
7174
7269
|
* True when every member of a geometry is a closed, consistently wound, outward-facing triangle
|
|
7175
7270
|
* surface, so its back faces can never be seen and the material can cull them.
|
|
@@ -8525,83 +8620,6 @@ function applyVertexColorSRGBDecode(material) {
|
|
|
8525
8620
|
#endif`);
|
|
8526
8621
|
});
|
|
8527
8622
|
}
|
|
8528
|
-
function metadataFail(message, context) {
|
|
8529
|
-
return new VisualizationError(message, ErrorCodes.VALIDATION_ERROR, { context });
|
|
8530
|
-
}
|
|
8531
|
-
/**
|
|
8532
|
-
* Validates the batch's group/mesh metadata against the decoded geometry buffers before any of it
|
|
8533
|
-
* is used arithmetically. Throws on the first inconsistency — out-of-range `materialId`,
|
|
8534
|
-
* non-integer or negative offsets/counts, or a vertex/index window that overruns the buffers — so
|
|
8535
|
-
* malformed or version-skewed metadata fails the parse loudly instead of corrupting the render.
|
|
8536
|
-
*/
|
|
8537
|
-
function validateGroupMetadata(groups, materialCount, totalVertexCount, totalIndexCount) {
|
|
8538
|
-
for (const group of groups) {
|
|
8539
|
-
if (!Number.isInteger(group.materialId) || group.materialId < 0 || group.materialId >= materialCount) throw metadataFail("Group materialId out of range of the materials array.", {
|
|
8540
|
-
materialId: group.materialId,
|
|
8541
|
-
materialCount
|
|
8542
|
-
});
|
|
8543
|
-
for (const mesh of group.meshes) {
|
|
8544
|
-
const fields = {
|
|
8545
|
-
vertexStart: mesh.vertexStart,
|
|
8546
|
-
vertexCount: mesh.vertexCount,
|
|
8547
|
-
indexStart: mesh.indexStart,
|
|
8548
|
-
indexCount: mesh.indexCount
|
|
8549
|
-
};
|
|
8550
|
-
for (const [field, value] of Object.entries(fields)) if (!Number.isInteger(value) || value < 0) throw metadataFail(`Mesh metadata field "${field}" must be a non-negative integer.`, {
|
|
8551
|
-
meshName: mesh.name,
|
|
8552
|
-
field,
|
|
8553
|
-
value
|
|
8554
|
-
});
|
|
8555
|
-
if (mesh.vertexStart + mesh.vertexCount > totalVertexCount) throw metadataFail("Mesh vertex window exceeds the batch vertex buffer.", {
|
|
8556
|
-
meshName: mesh.name,
|
|
8557
|
-
vertexStart: mesh.vertexStart,
|
|
8558
|
-
vertexCount: mesh.vertexCount,
|
|
8559
|
-
totalVertexCount
|
|
8560
|
-
});
|
|
8561
|
-
if (mesh.indexStart + mesh.indexCount > totalIndexCount) throw metadataFail("Mesh index window exceeds the batch index buffer.", {
|
|
8562
|
-
meshName: mesh.name,
|
|
8563
|
-
indexStart: mesh.indexStart,
|
|
8564
|
-
indexCount: mesh.indexCount,
|
|
8565
|
-
totalIndexCount
|
|
8566
|
-
});
|
|
8567
|
-
}
|
|
8568
|
-
}
|
|
8569
|
-
}
|
|
8570
|
-
/**
|
|
8571
|
-
* Error for an index outside its mesh's declared vertex window
|
|
8572
|
-
* `[vertexStart, vertexStart + vertexCount)`. Rebasing (`index - vertexStart`) writes into an
|
|
8573
|
-
* unsigned array, so an out-of-window index would otherwise wrap to ~4 billion and corrupt the
|
|
8574
|
-
* geometry. Range checks live inline in the copy loops (a function call per index measured
|
|
8575
|
-
* noticeably slower at millions of indices) — this only builds the failure.
|
|
8576
|
-
*/
|
|
8577
|
-
function indexOutOfWindow(indexValue, meshMeta) {
|
|
8578
|
-
return metadataFail("Index references a vertex outside its mesh's vertex window.", {
|
|
8579
|
-
meshName: meshMeta.name,
|
|
8580
|
-
indexValue,
|
|
8581
|
-
vertexStart: meshMeta.vertexStart,
|
|
8582
|
-
vertexCount: meshMeta.vertexCount
|
|
8583
|
-
});
|
|
8584
|
-
}
|
|
8585
|
-
/**
|
|
8586
|
-
* Reconstructs world-unit float32 positions from int16 quantized values:
|
|
8587
|
-
* `world = origin + (q + 32767) * scale`. No rotation — the Three scene uses Rhino's Z-up frame,
|
|
8588
|
-
* so vertices pass through as they arrived.
|
|
8589
|
-
*/
|
|
8590
|
-
function dequantizeInt16(q, origin, scale) {
|
|
8591
|
-
const out = new Float32Array(q.length);
|
|
8592
|
-
const ox = origin[0];
|
|
8593
|
-
const oy = origin[1];
|
|
8594
|
-
const oz = origin[2];
|
|
8595
|
-
const sx = scale[0];
|
|
8596
|
-
const sy = scale[1];
|
|
8597
|
-
const sz = scale[2];
|
|
8598
|
-
for (let i = 0; i < q.length; i += 3) {
|
|
8599
|
-
out[i] = ox + (q[i] + 32767) * sx;
|
|
8600
|
-
out[i + 1] = oy + (q[i + 1] + 32767) * sy;
|
|
8601
|
-
out[i + 2] = oz + (q[i + 2] + 32767) * sz;
|
|
8602
|
-
}
|
|
8603
|
-
return out;
|
|
8604
|
-
}
|
|
8605
8623
|
/**
|
|
8606
8624
|
* Split a material group into one sub-group per layer, preserving mesh order.
|
|
8607
8625
|
*
|
|
@@ -8945,7 +8963,7 @@ function buildMeshesFromParsed(parsed, opts) {
|
|
|
8945
8963
|
const materialsSrc = parsed.metadata.materials ?? fallback?.materials ?? [];
|
|
8946
8964
|
const groups = parsed.metadata.groups ?? fallback?.groups ?? [];
|
|
8947
8965
|
const isFloat32 = (parsed.flags & 1) !== 0;
|
|
8948
|
-
|
|
8966
|
+
validateBatchMetadata(materialsSrc, groups, parsed.vertices.length / 3, parsed.indices.length);
|
|
8949
8967
|
const worldVertices = isFloat32 ? parsed.vertices : dequantizeInt16(parsed.vertices, parsed.origin, parsed.scale);
|
|
8950
8968
|
if (debug) {
|
|
8951
8969
|
const wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;
|
|
@@ -9033,7 +9051,7 @@ function buildFromFinishedCache(container, opts) {
|
|
|
9033
9051
|
const { jobs, jobRefs } = planJobs(groups, opts.mergeByMaterial);
|
|
9034
9052
|
const cached = getFinishedBatch(container.geometryBlob, jobs);
|
|
9035
9053
|
if (!cached) return null;
|
|
9036
|
-
|
|
9054
|
+
validateBatchMetadata(materialsSrc, groups, cached.vertexCount, cached.indexCount);
|
|
9037
9055
|
return meshesFromBuilt(cached, jobRefs, materialsSrc, opts.material);
|
|
9038
9056
|
}
|
|
9039
9057
|
/** One job per merged group or per unmerged mesh, with a parallel ref list to unwrap results by index. */
|
|
@@ -9085,7 +9103,7 @@ async function tryBuildViaAssembly(opened, opts) {
|
|
|
9085
9103
|
if (indexCount / 3 < 5e4) return null;
|
|
9086
9104
|
const materialsSrc = raw.metadata.materials ?? opts.fallback?.materials ?? [];
|
|
9087
9105
|
const groups = raw.metadata.groups ?? opts.fallback?.groups ?? [];
|
|
9088
|
-
|
|
9106
|
+
validateBatchMetadata(materialsSrc, groups, raw.vertexCount, indexCount);
|
|
9089
9107
|
const { jobs, jobRefs } = planJobs(groups, opts.mergeByMaterial);
|
|
9090
9108
|
const assembled = await assemble(raw, jobs, opened.source);
|
|
9091
9109
|
if (!assembled) {
|
|
@@ -9125,7 +9143,15 @@ async function assemble(raw, jobs, source) {
|
|
|
9125
9143
|
colors: raw.colors,
|
|
9126
9144
|
jobs
|
|
9127
9145
|
};
|
|
9128
|
-
if (!worker)
|
|
9146
|
+
if (!worker) {
|
|
9147
|
+
let geometries;
|
|
9148
|
+
try {
|
|
9149
|
+
geometries = assembleGeometries(input);
|
|
9150
|
+
} catch (error) {
|
|
9151
|
+
throw new VisualizationError(error instanceof Error ? error.message : String(error), ErrorCodes.VALIDATION_ERROR, { originalError: error instanceof Error ? error : void 0 });
|
|
9152
|
+
}
|
|
9153
|
+
return geometries.map((geometry, i) => finishGeometry(geometry, jobs[i].windows));
|
|
9154
|
+
}
|
|
9129
9155
|
if (!ownsBuffer(raw, source)) {
|
|
9130
9156
|
input.vertexData = raw.vertexData.slice();
|
|
9131
9157
|
input.indexData = raw.indexData.slice();
|
|
@@ -10953,6 +10979,7 @@ function createComputeFetchSolveFn(opts) {
|
|
|
10953
10979
|
const channel = opts.channel?.();
|
|
10954
10980
|
const versionId = opts.versionId?.();
|
|
10955
10981
|
const streamId = opts.streamId?.();
|
|
10982
|
+
const bearerToken = opts.bearerToken?.();
|
|
10956
10983
|
const payload = JSON.stringify({
|
|
10957
10984
|
inputs,
|
|
10958
10985
|
values,
|
|
@@ -10964,7 +10991,10 @@ function createComputeFetchSolveFn(opts) {
|
|
|
10964
10991
|
try {
|
|
10965
10992
|
res = await fetch(opts.endpoint, {
|
|
10966
10993
|
method: "POST",
|
|
10967
|
-
headers: {
|
|
10994
|
+
headers: {
|
|
10995
|
+
"Content-Type": "application/json",
|
|
10996
|
+
...bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}
|
|
10997
|
+
},
|
|
10968
10998
|
body: payload,
|
|
10969
10999
|
signal
|
|
10970
11000
|
});
|
|
@@ -16745,6 +16775,19 @@ function createSolvingIndicator(isSolving, options = {}) {
|
|
|
16745
16775
|
}
|
|
16746
16776
|
};
|
|
16747
16777
|
}
|
|
16778
|
+
// ../ui/src/lib/compute/computeDriver.ts
|
|
16779
|
+
/**
|
|
16780
|
+
* The request/response driver `ComputeApp` solves through. Its memo caches whole solve results,
|
|
16781
|
+
* meshes included, and the viewer disposes what it renders on the next scene update.
|
|
16782
|
+
* `@selvajs/solve` keeps meshes opaque, so the three.js clone/dispose rules come from the renderer
|
|
16783
|
+
* that owns them: without `meshPolicy`, a memo hit serves an already-disposed mesh.
|
|
16784
|
+
*/
|
|
16785
|
+
function createComputeDriver(onSolve, getReporter, options) {
|
|
16786
|
+
return createRequestResponseDriver(onSolve, getReporter, {
|
|
16787
|
+
...options,
|
|
16788
|
+
meshPolicy
|
|
16789
|
+
});
|
|
16790
|
+
}
|
|
16748
16791
|
// ../ui/src/lib/components/compute/SolveMessages.svelte
|
|
16749
16792
|
function SolveMessages($$renderer, $$props) {
|
|
16750
16793
|
$$renderer.component(($$renderer) => {
|
|
@@ -17095,9 +17138,8 @@ function ComputeApp($$renderer, $$props) {
|
|
|
17095
17138
|
const locale = layerLocaleContext(() => lang, () => messages);
|
|
17096
17139
|
const t = derived(() => locale.messages);
|
|
17097
17140
|
derived(() => externalScopeKey || definitionKey || schema?.id || "");
|
|
17098
|
-
const driver =
|
|
17141
|
+
const driver = createComputeDriver(onSolve, () => session, {
|
|
17099
17142
|
solveDeadlineMs,
|
|
17100
|
-
meshPolicy,
|
|
17101
17143
|
onChange: () => session.notify(),
|
|
17102
17144
|
events
|
|
17103
17145
|
});
|
|
@@ -17242,7 +17284,7 @@ function _page($$renderer, $$props) {
|
|
|
17242
17284
|
function shouldShowViewer() {
|
|
17243
17285
|
return Boolean(data.schema.viewerOptions?.enableRemote);
|
|
17244
17286
|
}
|
|
17245
|
-
const liveEvents = run(() => isAuthed()) ? createSolveEventStream({
|
|
17287
|
+
const liveEvents = run(() => isAuthed() && !data.shareToken) ? createSolveEventStream({
|
|
17246
17288
|
endpoint: "/api/v1/solve-events",
|
|
17247
17289
|
cancelEndpoint: (solveId) => `/api/v1/solve/${solveId}/cancel`
|
|
17248
17290
|
}) : null;
|
|
@@ -17254,6 +17296,7 @@ function _page($$renderer, $$props) {
|
|
|
17254
17296
|
channel: () => data.channel === "draft" ? "draft" : void 0,
|
|
17255
17297
|
versionId: () => data.versionId,
|
|
17256
17298
|
streamId: () => liveEvents?.streamId ?? null,
|
|
17299
|
+
bearerToken: () => data.shareToken,
|
|
17257
17300
|
meshes: shouldShowViewer() ? { extract: (response, opts) => getThreeObjectsFromComputeResponse(response, opts) } : void 0,
|
|
17258
17301
|
debug: true
|
|
17259
17302
|
});
|