@imgly/codesign-mcp 0.1.10 → 0.1.11-next.20260727132311.gbce42f2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/runtime-support.d.ts +17 -0
- package/dist/cli/runtime-support.d.ts.map +1 -0
- package/dist/cli/runtime-support.js +29 -0
- package/dist/cli/runtime-support.js.map +1 -0
- package/dist/cli/trial-license.generated.d.ts +1 -1
- package/dist/cli/trial-license.generated.js +1 -1
- package/dist/cli/trial-license.generated.js.map +1 -1
- package/dist/cli.js +12 -10
- package/dist/cli.js.map +1 -1
- package/dist/engine/cesdk-adapter.d.ts +4 -1
- package/dist/engine/cesdk-adapter.d.ts.map +1 -1
- package/dist/engine/cesdk-adapter.js +7 -2
- package/dist/engine/cesdk-adapter.js.map +1 -1
- package/dist/engine/scene-compression.d.ts +5 -0
- package/dist/engine/scene-compression.d.ts.map +1 -0
- package/dist/engine/scene-compression.js +5 -0
- package/dist/engine/scene-compression.js.map +1 -0
- package/dist/engine/scene-file-uri-guard.d.ts.map +1 -1
- package/dist/engine/scene-file-uri-guard.js +65 -10
- package/dist/engine/scene-file-uri-guard.js.map +1 -1
- package/dist/tools/load.d.ts.map +1 -1
- package/dist/tools/load.js +9 -4
- package/dist/tools/load.js.map +1 -1
- package/dist/viewer/spa-assets.generated.d.ts.map +1 -1
- package/dist/viewer/spa-assets.generated.js +7 -1
- package/dist/viewer/spa-assets.generated.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An error message describing why this runtime can't run codesign-mcp, or
|
|
3
|
+
* `undefined` when it can.
|
|
4
|
+
*
|
|
5
|
+
* - `cryptoRandom` — the CE.SDK engine seeds its randomness from a global
|
|
6
|
+
* `crypto.getRandomValues`; without it the engine dies deep inside its WASM
|
|
7
|
+
* runtime with a cryptic `ReferenceError`, often taking the MCP connection
|
|
8
|
+
* down with it.
|
|
9
|
+
* - `zstd` — `zlib.zstdDecompressSync` (Node 22.15+) decodes the compressed
|
|
10
|
+
* `UBQ2` scenes the edit commit now writes; the file:// commit guard cannot
|
|
11
|
+
* scan a scene it cannot decompress.
|
|
12
|
+
*/
|
|
13
|
+
export declare function unsupportedRuntimeReason(caps: {
|
|
14
|
+
cryptoRandom: boolean;
|
|
15
|
+
zstd: boolean;
|
|
16
|
+
}): string | undefined;
|
|
17
|
+
//# sourceMappingURL=runtime-support.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-support.d.ts","sourceRoot":"","sources":["../../src/cli/runtime-support.ts"],"names":[],"mappings":"AAUA;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC7C,YAAY,EAAE,OAAO,CAAC;IACtB,IAAI,EAAE,OAAO,CAAC;CACf,GAAG,MAAM,GAAG,SAAS,CAMrB"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// packages/codesign-mcp/src/cli/runtime-support.ts
|
|
2
|
+
//
|
|
3
|
+
// The capability floor for running codesign-mcp, as a pure predicate so it is
|
|
4
|
+
// unit-testable — cli.ts owns the process.exit wiring.
|
|
5
|
+
//
|
|
6
|
+
// Feature-detects rather than parsing `process.version`: sandboxes strip
|
|
7
|
+
// globals, and a stripped capability is exactly as fatal as an old runtime.
|
|
8
|
+
// Both capabilities land in Node 22.15 or earlier, so the message names one
|
|
9
|
+
// floor rather than a per-capability version.
|
|
10
|
+
/**
|
|
11
|
+
* An error message describing why this runtime can't run codesign-mcp, or
|
|
12
|
+
* `undefined` when it can.
|
|
13
|
+
*
|
|
14
|
+
* - `cryptoRandom` — the CE.SDK engine seeds its randomness from a global
|
|
15
|
+
* `crypto.getRandomValues`; without it the engine dies deep inside its WASM
|
|
16
|
+
* runtime with a cryptic `ReferenceError`, often taking the MCP connection
|
|
17
|
+
* down with it.
|
|
18
|
+
* - `zstd` — `zlib.zstdDecompressSync` (Node 22.15+) decodes the compressed
|
|
19
|
+
* `UBQ2` scenes the edit commit now writes; the file:// commit guard cannot
|
|
20
|
+
* scan a scene it cannot decompress.
|
|
21
|
+
*/
|
|
22
|
+
export function unsupportedRuntimeReason(caps) {
|
|
23
|
+
if (!caps.cryptoRandom)
|
|
24
|
+
return 'Node.js >= 22.15 is required (this runtime has no crypto.getRandomValues).';
|
|
25
|
+
if (!caps.zstd)
|
|
26
|
+
return 'Node.js >= 22.15 is required (this runtime has no zlib.zstdDecompressSync).';
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=runtime-support.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-support.js","sourceRoot":"","sources":["../../src/cli/runtime-support.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,EAAE;AACF,8EAA8E;AAC9E,uDAAuD;AACvD,EAAE;AACF,yEAAyE;AACzE,4EAA4E;AAC5E,4EAA4E;AAC5E,8CAA8C;AAE9C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAGxC;IACC,IAAI,CAAC,IAAI,CAAC,YAAY;QACpB,OAAO,4EAA4E,CAAC;IACtF,IAAI,CAAC,IAAI,CAAC,IAAI;QACZ,OAAO,6EAA6E,CAAC;IACvF,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// packages/codesign-mcp/src/cli/runtime-support.ts\n//\n// The capability floor for running codesign-mcp, as a pure predicate so it is\n// unit-testable — cli.ts owns the process.exit wiring.\n//\n// Feature-detects rather than parsing `process.version`: sandboxes strip\n// globals, and a stripped capability is exactly as fatal as an old runtime.\n// Both capabilities land in Node 22.15 or earlier, so the message names one\n// floor rather than a per-capability version.\n\n/**\n * An error message describing why this runtime can't run codesign-mcp, or\n * `undefined` when it can.\n *\n * - `cryptoRandom` — the CE.SDK engine seeds its randomness from a global\n * `crypto.getRandomValues`; without it the engine dies deep inside its WASM\n * runtime with a cryptic `ReferenceError`, often taking the MCP connection\n * down with it.\n * - `zstd` — `zlib.zstdDecompressSync` (Node 22.15+) decodes the compressed\n * `UBQ2` scenes the edit commit now writes; the file:// commit guard cannot\n * scan a scene it cannot decompress.\n */\nexport function unsupportedRuntimeReason(caps: {\n cryptoRandom: boolean;\n zstd: boolean;\n}): string | undefined {\n if (!caps.cryptoRandom)\n return 'Node.js >= 22.15 is required (this runtime has no crypto.getRandomValues).';\n if (!caps.zstd)\n return 'Node.js >= 22.15 is required (this runtime has no zlib.zstdDecompressSync).';\n return undefined;\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const TRIAL_CESDK_LICENSE = "
|
|
1
|
+
export declare const TRIAL_CESDK_LICENSE = "WeWY94Mh0GY4XO4W3FiQWB2zM28B-ghnF4jGORIl8A12YwEnz3WZQ1l7EGpcnRap";
|
|
2
2
|
//# sourceMappingURL=trial-license.generated.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// AUTO-GENERATED by scripts/generate-trial-license.mjs — do not edit.
|
|
2
2
|
// Empty unless IMGLY_TRIAL_CESDK_LICENSE was set at build/publish time.
|
|
3
|
-
export const TRIAL_CESDK_LICENSE = "
|
|
3
|
+
export const TRIAL_CESDK_LICENSE = "WeWY94Mh0GY4XO4W3FiQWB2zM28B-ghnF4jGORIl8A12YwEnz3WZQ1l7EGpcnRap";
|
|
4
4
|
//# sourceMappingURL=trial-license.generated.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trial-license.generated.js","sourceRoot":"","sources":["../../src/cli/trial-license.generated.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,wEAAwE;AACxE,MAAM,CAAC,MAAM,mBAAmB,GAAG,kEAAkE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-trial-license.mjs — do not edit.\n// Empty unless IMGLY_TRIAL_CESDK_LICENSE was set at build/publish time.\nexport const TRIAL_CESDK_LICENSE = \"
|
|
1
|
+
{"version":3,"file":"trial-license.generated.js","sourceRoot":"","sources":["../../src/cli/trial-license.generated.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,wEAAwE;AACxE,MAAM,CAAC,MAAM,mBAAmB,GAAG,kEAAkE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-trial-license.mjs — do not edit.\n// Empty unless IMGLY_TRIAL_CESDK_LICENSE was set at build/publish time.\nexport const TRIAL_CESDK_LICENSE = \"WeWY94Mh0GY4XO4W3FiQWB2zM28B-ghnF4jGORIl8A12YwEnz3WZQ1l7EGpcnRap\";\n"]}
|
package/dist/cli.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
//
|
|
11
11
|
// Lazy imports per subcommand: stdio mode never loads express; http mode
|
|
12
12
|
// never loads StdioServerTransport. Smaller crash surface, faster start.
|
|
13
|
+
import zlib from 'node:zlib';
|
|
14
|
+
import { unsupportedRuntimeReason } from './cli/runtime-support.js';
|
|
13
15
|
const USAGE = `Usage: codesign-mcp <stdio|http|diagnose|login|logout> [flags]
|
|
14
16
|
|
|
15
17
|
Subcommands:
|
|
@@ -38,16 +40,17 @@ Common env:
|
|
|
38
40
|
IMGLY_DEMO_ASSETS_BASE_URL manifest root for the demo asset sources
|
|
39
41
|
(default: IMG.LY CDN).
|
|
40
42
|
`;
|
|
41
|
-
// The
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
// inside
|
|
45
|
-
// defined`, often taking the whole process (and the MCP connection) down with
|
|
46
|
-
// it. Feature-detect the capability up front and fail with a clear message.
|
|
43
|
+
// The runtime floor is Node 22.15 — see src/cli/runtime-support.ts for what
|
|
44
|
+
// each capability is needed for. Checked here, before any subcommand loads, so
|
|
45
|
+
// an unsupported runtime gets one clear line instead of a crash from deep
|
|
46
|
+
// inside the WASM engine or the edit-commit guard.
|
|
47
47
|
function assertSupportedRuntime() {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
const reason = unsupportedRuntimeReason({
|
|
49
|
+
cryptoRandom: typeof globalThis.crypto?.getRandomValues === 'function',
|
|
50
|
+
zstd: typeof zlib.zstdDecompressSync === 'function'
|
|
51
|
+
});
|
|
52
|
+
if (reason !== undefined) {
|
|
53
|
+
process.stderr.write(`codesign-mcp: unsupported Node.js runtime (${process.version}). ${reason}\n`);
|
|
51
54
|
process.exit(1);
|
|
52
55
|
}
|
|
53
56
|
}
|
|
@@ -98,5 +101,4 @@ main().catch((err) => {
|
|
|
98
101
|
process.stderr.write(`codesign-mcp: fatal — ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
|
|
99
102
|
process.exit(1);
|
|
100
103
|
});
|
|
101
|
-
export {};
|
|
102
104
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,6CAA6C;AAC7C,EAAE;AACF,2EAA2E;AAC3E,wEAAwE;AACxE,8CAA8C;AAC9C,EAAE;AACF,0EAA0E;AAC1E,4EAA4E;AAC5E,EAAE;AACF,yEAAyE;AACzE,yEAAyE;AAEzE,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2Bb,CAAC;AAEF,
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,6CAA6C;AAC7C,EAAE;AACF,2EAA2E;AAC3E,wEAAwE;AACxE,8CAA8C;AAC9C,EAAE;AACF,0EAA0E;AAC1E,4EAA4E;AAC5E,EAAE;AACF,yEAAyE;AACzE,yEAAyE;AAEzE,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAEpE,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2Bb,CAAC;AAEF,4EAA4E;AAC5E,+EAA+E;AAC/E,0EAA0E;AAC1E,mDAAmD;AACnD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AAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,eAAe,CAAC,CAAC;YACnD,MAAM,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACtC,OAAO;QACT,CAAC;QACD,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,eAAe,CAAC,CAAC;YACpD,MAAM,SAAS,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QACD,KAAK,IAAI,CAAC;QACV,KAAK,QAAQ;YACX,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC5B,OAAO;QACT,KAAK,SAAS;YACZ,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,sCAAsC,KAAK,EAAE,CAAC,CAAC;YACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,OAAO;QACT;YACE,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,qCAAqC,GAAG,OAAO,KAAK,EAAE,CACvD,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,yBAAyB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAC7F,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// codesign-mcp — single bin, two transports.\n//\n// codesign-mcp stdio MCP server over stdin/stdout. Spawned by hosts\n// like Claude Desktop / Claude Code via their\n// `command` config.\n//\n// codesign-mcp http MCP server over Streamable HTTP. Long-running\n// listener; hosts connect via their `url` config.\n//\n// Lazy imports per subcommand: stdio mode never loads express; http mode\n// never loads StdioServerTransport. Smaller crash surface, faster start.\n\nimport zlib from 'node:zlib';\nimport { unsupportedRuntimeReason } from './cli/runtime-support.js';\n\nconst USAGE = `Usage: codesign-mcp <stdio|http|diagnose|login|logout> [flags]\n\nSubcommands:\n stdio MCP server over stdin/stdout. Spawned by hosts\n like Claude Desktop / Claude Code via their\n \\`command\\` config.\n\n http [--port <n>] MCP server over Streamable HTTP. Long-running\n [--host <ip>] listener; hosts connect via their \\`url\\` config.\n [--max-sessions <n>] Defaults: --port 3030 --host 127.0.0.1\n [--idle-timeout-ms <n>] --max-sessions 10 --idle-timeout-ms 1800000\n\n diagnose Collect local diagnostics logs into a redacted\n .zip you can send to IMG.LY. No network.\n\n login Sign in with your IMG.LY account (opens the\n system browser). Needed only for AI generation.\n\n logout Sign out and clear local credentials.\n\nCommon env:\n CESDK_LICENSE required for both modes (CE.SDK headless\n engine license).\n IMGLY_DEFAULT_ASSETS_BASE_URL manifest root for the default asset sources\n (self-hosted deployments; default: IMG.LY CDN).\n IMGLY_DEMO_ASSETS_BASE_URL manifest root for the demo asset sources\n (default: IMG.LY CDN).\n`;\n\n// The runtime floor is Node 22.15 — see src/cli/runtime-support.ts for what\n// each capability is needed for. Checked here, before any subcommand loads, so\n// an unsupported runtime gets one clear line instead of a crash from deep\n// inside the WASM engine or the edit-commit guard.\nfunction assertSupportedRuntime(): void {\n const reason = unsupportedRuntimeReason({\n cryptoRandom: typeof globalThis.crypto?.getRandomValues === 'function',\n zstd: typeof zlib.zstdDecompressSync === 'function'\n });\n if (reason !== undefined) {\n process.stderr.write(\n `codesign-mcp: unsupported Node.js runtime (${process.version}). ${reason}\\n`\n );\n process.exit(1);\n }\n}\n\nasync function main(): Promise<void> {\n assertSupportedRuntime();\n const sub = process.argv[2];\n switch (sub) {\n case 'stdio': {\n const { runStdio } = await import('./cli/stdio.js');\n await runStdio();\n return;\n }\n case 'http': {\n const { runHttp } = await import('./cli/http.js');\n await runHttp(process.argv.slice(3));\n return;\n }\n case 'diagnose': {\n const { runDiagnose } = await import('./diagnostics/bundle.js');\n const zipPath = await runDiagnose();\n process.stdout.write(\n `codesign-mcp: diagnostics bundle written to\\n ${zipPath}\\nAttach this file to your issue or email support — it is redacted and local-only.\\n`\n );\n return;\n }\n case 'login': {\n const { runLogin } = await import('./auth/cli.js');\n await runLogin(process.argv.slice(3));\n return;\n }\n case 'logout': {\n const { runLogout } = await import('./auth/cli.js');\n await runLogout();\n return;\n }\n case '-h':\n case '--help':\n process.stdout.write(USAGE);\n return;\n case undefined:\n process.stderr.write(`codesign-mcp: missing subcommand.\\n${USAGE}`);\n process.exit(2);\n return;\n default:\n process.stderr.write(\n `codesign-mcp: unknown subcommand \"${sub}\".\\n${USAGE}`\n );\n process.exit(2);\n }\n}\n\nmain().catch((err) => {\n process.stderr.write(\n `codesign-mcp: fatal — ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\\n`\n );\n process.exit(1);\n});\n"]}
|
|
@@ -2,7 +2,7 @@ import type CreativeEngine from '@cesdk/engine';
|
|
|
2
2
|
import type { EngineAdapter } from './session.js';
|
|
3
3
|
/**
|
|
4
4
|
* Adapts a `@cesdk/engine` CreativeEngine instance to the EngineSession's
|
|
5
|
-
* generic EngineAdapter shape. One-to-one mapping;
|
|
5
|
+
* generic EngineAdapter shape. One-to-one mapping; four quirks. First,
|
|
6
6
|
* `reset` (CE.SDK has no `reset()` — we wipe by creating a new scene via the
|
|
7
7
|
* same patched create path `ensureHeadlessEngine` installed for the
|
|
8
8
|
* design-unit fix). Second, `saveToString` passes an explicit
|
|
@@ -18,6 +18,9 @@ import type { EngineAdapter } from './session.js';
|
|
|
18
18
|
* unreachable URL) — and an unloadable asset must never block committing:
|
|
19
19
|
* serialization itself needs no loaded resources; `preview`/`export` surface
|
|
20
20
|
* the load failure legibly instead.
|
|
21
|
+
* Fourth, `saveToString` compresses: persisted scenes are zstd-framed 'UBQ2'
|
|
22
|
+
* rather than plain 'UBQ1' (see scene-compression.ts). The file:// guard below
|
|
23
|
+
* decodes both.
|
|
21
24
|
*
|
|
22
25
|
* `engine` may be a Promise: the stdio transport defers engine init off the
|
|
23
26
|
* MCP-handshake path and hands the in-flight promise here. EngineSession only
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cesdk-adapter.d.ts","sourceRoot":"","sources":["../../src/engine/cesdk-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,cAAc,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"cesdk-adapter.d.ts","sourceRoot":"","sources":["../../src/engine/cesdk-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,cAAc,MAAM,eAAe,CAAC;AAOhD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EACF,cAAc,GACd,OAAO,CAAC,cAAc,CAAC,GACvB,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,GACnD,aAAa,CAAC,cAAc,CAAC,CAoC/B"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { findFileUrisInScene, SceneFileUriError } from './scene-file-uri-guard.js';
|
|
2
2
|
import { SCENE_ALLOWED_RESOURCE_SCHEMES } from './scene-resource-schemes.js';
|
|
3
|
+
import { SCENE_COMPRESSION } from './scene-compression.js';
|
|
3
4
|
/**
|
|
4
5
|
* Adapts a `@cesdk/engine` CreativeEngine instance to the EngineSession's
|
|
5
|
-
* generic EngineAdapter shape. One-to-one mapping;
|
|
6
|
+
* generic EngineAdapter shape. One-to-one mapping; four quirks. First,
|
|
6
7
|
* `reset` (CE.SDK has no `reset()` — we wipe by creating a new scene via the
|
|
7
8
|
* same patched create path `ensureHeadlessEngine` installed for the
|
|
8
9
|
* design-unit fix). Second, `saveToString` passes an explicit
|
|
@@ -18,6 +19,9 @@ import { SCENE_ALLOWED_RESOURCE_SCHEMES } from './scene-resource-schemes.js';
|
|
|
18
19
|
* unreachable URL) — and an unloadable asset must never block committing:
|
|
19
20
|
* serialization itself needs no loaded resources; `preview`/`export` surface
|
|
20
21
|
* the load failure legibly instead.
|
|
22
|
+
* Fourth, `saveToString` compresses: persisted scenes are zstd-framed 'UBQ2'
|
|
23
|
+
* rather than plain 'UBQ1' (see scene-compression.ts). The file:// guard below
|
|
24
|
+
* decodes both.
|
|
21
25
|
*
|
|
22
26
|
* `engine` may be a Promise: the stdio transport defers engine init off the
|
|
23
27
|
* MCP-handshake path and hands the in-flight promise here. EngineSession only
|
|
@@ -48,7 +52,8 @@ export function cesdkAdapter(engine) {
|
|
|
48
52
|
.forceLoadResources(eng.scene.getPages())
|
|
49
53
|
.catch(() => undefined);
|
|
50
54
|
const scene = await eng.scene.saveToString({
|
|
51
|
-
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES
|
|
55
|
+
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,
|
|
56
|
+
compression: SCENE_COMPRESSION
|
|
52
57
|
});
|
|
53
58
|
// CODE-113: reject a commit whose scene references file:// assets — see
|
|
54
59
|
// scene-file-uri-guard.ts. Only the edit commit runs through this
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cesdk-adapter.js","sourceRoot":"","sources":["../../src/engine/cesdk-adapter.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"cesdk-adapter.js","sourceRoot":"","sources":["../../src/engine/cesdk-adapter.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAA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C;YACvE,CAAC;YACD,MAAM,QAAQ,GAAG,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YACtD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,iBAAiB,CAAC,QAAQ,CAAC,CAAC;YAC/D,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type CreativeEngine from '@cesdk/engine';\nimport {\n findFileUrisInScene,\n SceneFileUriError\n} from './scene-file-uri-guard.js';\nimport { SCENE_ALLOWED_RESOURCE_SCHEMES } from './scene-resource-schemes.js';\nimport { SCENE_COMPRESSION } from './scene-compression.js';\nimport type { EngineAdapter } from './session.js';\n\n/**\n * Adapts a `@cesdk/engine` CreativeEngine instance to the EngineSession's\n * generic EngineAdapter shape. One-to-one mapping; four quirks. First,\n * `reset` (CE.SDK has no `reset()` — we wipe by creating a new scene via the\n * same patched create path `ensureHeadlessEngine` installed for the\n * design-unit fix). Second, `saveToString` passes an explicit\n * `allowedResourceSchemes`: the engine default rejects our durable\n * `workspace://` scheme, so an edit commit of a scene referencing workspace\n * assets would fail without it (see scene-resource-schemes.ts, CODE-3).\n * Third, `saveToString` lets every page's in-flight resource loads settle\n * first (best-effort forceLoadResources): the agent's edit code fires\n * font/image fetches that may still be pending when it returns, and the\n * thumbnail render right after the commit races them into\n * ENCODE.NOT_ALL_RESOURCES_LOADED (CODE-94). Best-effort because\n * forceLoadResources REJECTS when a resource fails to load (e.g. an\n * unreachable URL) — and an unloadable asset must never block committing:\n * serialization itself needs no loaded resources; `preview`/`export` surface\n * the load failure legibly instead.\n * Fourth, `saveToString` compresses: persisted scenes are zstd-framed 'UBQ2'\n * rather than plain 'UBQ1' (see scene-compression.ts). The file:// guard below\n * decodes both.\n *\n * `engine` may be a Promise: the stdio transport defers engine init off the\n * MCP-handshake path and hands the in-flight promise here. EngineSession only\n * calls `create()` on the first slot (first edit), awaiting it then — by which\n * point init is usually already settled. The other methods receive the resolved\n * engine from EngineSession, so they never touch the promise.\n *\n * `engine` may also be a thunk `() => Promise<CreativeEngine>`: the stdio\n * transport passes a lazy, slot-gated boot so no engine initializes until the\n * first edit calls create().\n */\nexport function cesdkAdapter(\n engine:\n | CreativeEngine\n | Promise<CreativeEngine>\n | (() => CreativeEngine | Promise<CreativeEngine>)\n): EngineAdapter<CreativeEngine> {\n return {\n // Value/promise: always the same instance. Thunk: the stdio transport passes\n // a lazy slot-gated boot (CODE-59) so nothing initializes until the first\n // edit; EngineSession(size:1) calls create() only once, on that first edit.\n create: () => (typeof engine === 'function' ? engine() : engine),\n reset: async (eng) => {\n eng.scene.create(); // wipes the active scene; design-unit patch from tools/engine.ts re-applies\n },\n loadFromString: async (eng, scene) => {\n await eng.scene.loadFromString(scene);\n },\n saveToString: async (eng) => {\n // Settle in-flight loads, but never fail the commit over an unloadable\n // resource — see the header comment (CODE-94).\n await eng.block\n .forceLoadResources(eng.scene.getPages())\n .catch(() => undefined);\n const scene = await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n compression: SCENE_COMPRESSION\n });\n // CODE-113: reject a commit whose scene references file:// assets — see\n // scene-file-uri-guard.ts. Only the edit commit runs through this\n // adapter; load's explode serializes directly and stays unguarded.\n let basePath: string | undefined;\n try {\n basePath = eng.editor.getSettingString('basePath');\n } catch {\n basePath = undefined; // guard still holds via the directory-URI rule\n }\n const fileUris = findFileUrisInScene(scene, basePath);\n if (fileUris.length > 0) throw new SceneFileUriError(fileUris);\n return scene;\n }\n };\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type CreativeEngine from '@cesdk/engine';
|
|
2
|
+
type SaveToStringOptions = NonNullable<Parameters<CreativeEngine['scene']['saveToString']>[0]>;
|
|
3
|
+
export declare const SCENE_COMPRESSION: NonNullable<SaveToStringOptions['compression']>;
|
|
4
|
+
export {};
|
|
5
|
+
//# sourceMappingURL=scene-compression.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scene-compression.d.ts","sourceRoot":"","sources":["../../src/engine/scene-compression.ts"],"names":[],"mappings":"AA2CA,OAAO,KAAK,cAAc,MAAM,eAAe,CAAC;AAEhD,KAAK,mBAAmB,GAAG,WAAW,CACpC,UAAU,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CACvD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,WAAW,CACzC,mBAAmB,CAAC,aAAa,CAAC,CAInC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scene-compression.js","sourceRoot":"","sources":["../../src/engine/scene-compression.ts"],"names":[],"mappings":"AAiDA,MAAM,CAAC,MAAM,iBAAiB,GAE1B;IACF,MAAM,EAAE,CAAC,EAAE,yBAAyB;IACpC,KAAK,EAAE,CAAC,CAAC,2BAA2B;CACrC,CAAC","sourcesContent":["// packages/codesign-mcp/src/engine/scene-compression.ts\n//\n// Compression options for every PERSISTED scene string. The engine emits\n// 'UBQ2' + base64(zstd(json)) instead of 'UBQ1' + base64(json) — measured 97.6%\n// smaller across a real 105-revision workspace. Output stays pure ASCII, so the\n// revision store is unaffected, and loadFromString auto-detects both framings,\n// so existing revisions keep loading with no migration.\n//\n// Zstd at Default, not Best: Best costs ~100x the CPU (44ms vs 0.4ms per scene)\n// for ~18% further saving, on a path that runs on every edit commit.\n//\n// The values are the engine's CompressionFormat.Zstd and CompressionLevel.Default,\n// written as literals rather than imported. Those enums ARE real runtime exports\n// (of both @cesdk/engine and @cesdk/node), so `CompressionFormat.Zstd` would work\n// — the reasons not to are smaller than they might look, and are recorded here so\n// nobody has to re-derive them:\n//\n// - It is NOT about the lazy engine boot. Importing the module does not start an\n// engine; only ensureHeadlessEngine's CreativeEngine.init() does that. Measured,\n// a value import costs ~16-19ms and ~7MB RSS — real, but not an engine boot.\n// - @cesdk/engine is the BROWSER bundle (425K). Loading it in a Node server to\n// read two integers is the wrong package, however cheap.\n// - @cesdk/node is the right package but the wrong lifetime: tools/engine.ts\n// chooses between @cesdk/node (WASM) and @cesdk/node-native at runtime via\n// createRequire. A static value import pins the WASM wrapper into every\n// process — including native-mode runs that never use it, and `login`,\n// `logout` and `diagnose`, which never touch an engine at all.\n//\n// So the literals stay, and the type carries the safety. Note the engine's own\n// `SaveToStringOptions` interface is NOT usable here: it is unexported despite its\n// @public tag, and its field names don't even match the method it documents\n// (`resourceSchemesAllowed`/`persistenceCallback` vs the real\n// `allowedResourceSchemes`/`onDisallowedResourceScheme`). Deriving the type from\n// the method signature instead keeps the literals honest — a shape change fails\n// here rather than at the call sites.\n//\n// If the bare numbers ever grate, the zero-cost fix is named constants typed\n// against the exported enum types (`const ZSTD: CompressionFormat = 1`), which is\n// also strictly safer: that form rejects an out-of-range literal, while the\n// derived option type below accepts any number.\n//\n// Reading these back needs zlib.zstdDecompressSync (Node 22.15+) — see\n// scene-file-uri-guard.ts and the runtime floor in cli/runtime-support.ts.\nimport type CreativeEngine from '@cesdk/engine';\n\ntype SaveToStringOptions = NonNullable<\n Parameters<CreativeEngine['scene']['saveToString']>[0]\n>;\n\nexport const SCENE_COMPRESSION: NonNullable<\n SaveToStringOptions['compression']\n> = {\n format: 1, // CompressionFormat.Zstd\n level: 1 // CompressionLevel.Default\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scene-file-uri-guard.d.ts","sourceRoot":"","sources":["../../src/engine/scene-file-uri-guard.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"scene-file-uri-guard.d.ts","sourceRoot":"","sources":["../../src/engine/scene-file-uri-guard.ts"],"names":[],"mappings":"AAyBA,kFAAkF;AAClF,qBAAa,iBAAkB,SAAQ,KAAK;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE;gBAAd,IAAI,EAAE,MAAM,EAAE;CAIpC;AAuDD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,GAAG,SAAS,GACjC,MAAM,EAAE,CASV"}
|
|
@@ -8,13 +8,19 @@
|
|
|
8
8
|
// `file` (load stages archives via file://, see scene-resource-schemes.ts), so
|
|
9
9
|
// enforcement lives here, after serialization.
|
|
10
10
|
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
11
|
+
// A serialized scene is either 'UBQ1' + base64(JSON) or, since scenes became
|
|
12
|
+
// compressed, 'UBQ2' + base64(zstd(JSON)) — with resource URIs as plain JSON
|
|
13
|
+
// string values either way, so a quote-bounded scan of the DECODED payload
|
|
14
|
+
// sees every reference regardless of where the schema nests it. Scanning an
|
|
15
|
+
// undecoded UBQ2 body finds nothing and silently passes every scene, so the
|
|
16
|
+
// decode is load-bearing, not a convenience.
|
|
17
|
+
//
|
|
18
|
+
// The engine cannot enumerate these itself: a file:// font surfaces in
|
|
19
|
+
// NEITHER findAllMediaURIs() nor findAllTransientResources() (verified on
|
|
20
|
+
// 1.79.0-rc.0), and the save-time onDisallowedResourceScheme callback
|
|
21
|
+
// deadlocks/hangs under exactly the conditions we'd need it (see load.ts's
|
|
22
|
+
// drain constraints).
|
|
23
|
+
import { zstdDecompressSync } from 'node:zlib';
|
|
18
24
|
/** Thrown by the edit commit when the persisted scene references file:// URIs. */
|
|
19
25
|
export class SceneFileUriError extends Error {
|
|
20
26
|
constructor(uris) {
|
|
@@ -23,6 +29,57 @@ export class SceneFileUriError extends Error {
|
|
|
23
29
|
this.name = 'SceneFileUriError';
|
|
24
30
|
}
|
|
25
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* The scene's JSON payload, whichever framing the engine used. A scene string
|
|
34
|
+
* we can't decode is a genuine fault — the same process serialized it moments
|
|
35
|
+
* ago.
|
|
36
|
+
*
|
|
37
|
+
* For UBQ2, `zstdDecompressSync` does NOT guarantee a corrupt/truncated frame
|
|
38
|
+
* throws: an empty body, or a frame cut anywhere between block boundaries,
|
|
39
|
+
* decompresses to zero bytes or a truncated-but-non-empty result with no
|
|
40
|
+
* error at all (verified empirically on Node 22 — only a garbage/unrecognized
|
|
41
|
+
* body throws). A regex scan over that partial JSON would still "succeed" —
|
|
42
|
+
* it would just miss whatever file:// reference happened to fall in the
|
|
43
|
+
* truncated tail, and the guard would silently pass a scene it exists to
|
|
44
|
+
* reject. So after decompressing we `JSON.parse` the result purely as an
|
|
45
|
+
* integrity check (the parsed value is discarded): a truncated payload fails
|
|
46
|
+
* to parse regardless of where the cut landed, which is the guarantee we
|
|
47
|
+
* actually need. Do not replace this with a "non-empty" or "starts with {"
|
|
48
|
+
* check — partial output is non-empty and can look well-formed at the start.
|
|
49
|
+
* UBQ1 gets no equivalent check because it has no equivalent failure mode —
|
|
50
|
+
* nothing between this function and the engine's own `saveToString` can hand
|
|
51
|
+
* it a truncated base64(JSON) body — but if it ever did, `JSON.parse` would
|
|
52
|
+
* catch that too: zstd truncation yields a byte prefix of the original JSON,
|
|
53
|
+
* and no proper prefix of a top-level JSON object is itself a valid JSON
|
|
54
|
+
* document (the closing brace is always missing), so the same integrity
|
|
55
|
+
* check generalizes to either framing.
|
|
56
|
+
*/
|
|
57
|
+
function scenePayload(scene) {
|
|
58
|
+
if (scene.startsWith('UBQ1'))
|
|
59
|
+
return Buffer.from(scene.slice(4), 'base64').toString('utf8');
|
|
60
|
+
if (scene.startsWith('UBQ2')) {
|
|
61
|
+
const json = zstdDecompressSync(Buffer.from(scene.slice(4), 'base64')).toString('utf8');
|
|
62
|
+
try {
|
|
63
|
+
JSON.parse(json);
|
|
64
|
+
}
|
|
65
|
+
catch (cause) {
|
|
66
|
+
throw new Error('UBQ2 scene decompressed to an incomplete JSON payload', {
|
|
67
|
+
cause
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return json;
|
|
71
|
+
}
|
|
72
|
+
// Any other 'UBQ*' framing is a future engine format this guard doesn't
|
|
73
|
+
// understand yet — scanning it undecoded would silently pass every scene,
|
|
74
|
+
// the exact failure this guard exists to prevent (see the UBQ2 case above).
|
|
75
|
+
// Fail loudly instead of falling through to a raw scan. Genuine non-UBQ
|
|
76
|
+
// strings (tests' fake scene fixtures, or the odd caller that hands the
|
|
77
|
+
// guard something that was never serialized by the engine) still take the
|
|
78
|
+
// raw-scan fallback below.
|
|
79
|
+
if (scene.startsWith('UBQ'))
|
|
80
|
+
throw new Error(`unrecognized scene framing: ${scene.slice(0, 4)}`);
|
|
81
|
+
return scene;
|
|
82
|
+
}
|
|
26
83
|
/**
|
|
27
84
|
* Every file:// URI referenced by a serialized scene, minus the engine's own
|
|
28
85
|
* `basePath` setting — a *directory* file:// URI the node engines serialize
|
|
@@ -33,9 +90,7 @@ export class SceneFileUriError extends Error {
|
|
|
33
90
|
* a text block's content) from tripping the guard.
|
|
34
91
|
*/
|
|
35
92
|
export function findFileUrisInScene(scene, engineBasePath) {
|
|
36
|
-
const payload = scene
|
|
37
|
-
? Buffer.from(scene.slice(4), 'base64').toString('utf8')
|
|
38
|
-
: scene;
|
|
93
|
+
const payload = scenePayload(scene);
|
|
39
94
|
const uris = new Set();
|
|
40
95
|
for (const match of payload.matchAll(/"(file:\/\/[^"]+)"/g)) {
|
|
41
96
|
const uri = match[1];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scene-file-uri-guard.js","sourceRoot":"","sources":["../../src/engine/scene-file-uri-guard.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+CAA+C;AAC/C,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,uEAAuE;AACvE,
|
|
1
|
+
{"version":3,"file":"scene-file-uri-guard.js","sourceRoot":"","sources":["../../src/engine/scene-file-uri-guard.ts"],"names":[],"mappings":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C,uDAAuD,EAAE;gBACvE,KAAK;aACN,CAAC,CAAC;QACL,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,wEAAwE;IACxE,0EAA0E;IAC1E,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,0EAA0E;IAC1E,2BAA2B;IAC3B,IAAI,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,+BAA+B,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACtE,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAAa,EACb,cAAkC;IAElC,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,CAAC;QAC5D,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACrB,IAAI,GAAG,KAAK,cAAc,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,SAAS;QAC1D,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC;IACD,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;AACnB,CAAC","sourcesContent":["// packages/codesign-mcp/src/engine/scene-file-uri-guard.ts\n//\n// Guard for the EDIT COMMIT only (CODE-113): a file:// resource URI in a\n// persisted scene renders fine server-side (Node reads the disk, so preview/\n// export/judge all pass green) but always breaks the browser editor — browsers\n// refuse file:// subresources even on the same machine — and the design breaks\n// on every other machine. The engine-level scheme allowlist deliberately keeps\n// `file` (load stages archives via file://, see scene-resource-schemes.ts), so\n// enforcement lives here, after serialization.\n//\n// A serialized scene is either 'UBQ1' + base64(JSON) or, since scenes became\n// compressed, 'UBQ2' + base64(zstd(JSON)) — with resource URIs as plain JSON\n// string values either way, so a quote-bounded scan of the DECODED payload\n// sees every reference regardless of where the schema nests it. Scanning an\n// undecoded UBQ2 body finds nothing and silently passes every scene, so the\n// decode is load-bearing, not a convenience.\n//\n// The engine cannot enumerate these itself: a file:// font surfaces in\n// NEITHER findAllMediaURIs() nor findAllTransientResources() (verified on\n// 1.79.0-rc.0), and the save-time onDisallowedResourceScheme callback\n// deadlocks/hangs under exactly the conditions we'd need it (see load.ts's\n// drain constraints).\n\nimport { zstdDecompressSync } from 'node:zlib';\n\n/** Thrown by the edit commit when the persisted scene references file:// URIs. */\nexport class SceneFileUriError extends Error {\n constructor(readonly uris: string[]) {\n super(`scene references file:// URIs: ${uris.join(', ')}`);\n this.name = 'SceneFileUriError';\n }\n}\n\n/**\n * The scene's JSON payload, whichever framing the engine used. A scene string\n * we can't decode is a genuine fault — the same process serialized it moments\n * ago.\n *\n * For UBQ2, `zstdDecompressSync` does NOT guarantee a corrupt/truncated frame\n * throws: an empty body, or a frame cut anywhere between block boundaries,\n * decompresses to zero bytes or a truncated-but-non-empty result with no\n * error at all (verified empirically on Node 22 — only a garbage/unrecognized\n * body throws). A regex scan over that partial JSON would still \"succeed\" —\n * it would just miss whatever file:// reference happened to fall in the\n * truncated tail, and the guard would silently pass a scene it exists to\n * reject. So after decompressing we `JSON.parse` the result purely as an\n * integrity check (the parsed value is discarded): a truncated payload fails\n * to parse regardless of where the cut landed, which is the guarantee we\n * actually need. Do not replace this with a \"non-empty\" or \"starts with {\"\n * check — partial output is non-empty and can look well-formed at the start.\n * UBQ1 gets no equivalent check because it has no equivalent failure mode —\n * nothing between this function and the engine's own `saveToString` can hand\n * it a truncated base64(JSON) body — but if it ever did, `JSON.parse` would\n * catch that too: zstd truncation yields a byte prefix of the original JSON,\n * and no proper prefix of a top-level JSON object is itself a valid JSON\n * document (the closing brace is always missing), so the same integrity\n * check generalizes to either framing.\n */\nfunction scenePayload(scene: string): string {\n if (scene.startsWith('UBQ1'))\n return Buffer.from(scene.slice(4), 'base64').toString('utf8');\n if (scene.startsWith('UBQ2')) {\n const json = zstdDecompressSync(\n Buffer.from(scene.slice(4), 'base64')\n ).toString('utf8');\n try {\n JSON.parse(json);\n } catch (cause) {\n throw new Error('UBQ2 scene decompressed to an incomplete JSON payload', {\n cause\n });\n }\n return json;\n }\n // Any other 'UBQ*' framing is a future engine format this guard doesn't\n // understand yet — scanning it undecoded would silently pass every scene,\n // the exact failure this guard exists to prevent (see the UBQ2 case above).\n // Fail loudly instead of falling through to a raw scan. Genuine non-UBQ\n // strings (tests' fake scene fixtures, or the odd caller that hands the\n // guard something that was never serialized by the engine) still take the\n // raw-scan fallback below.\n if (scene.startsWith('UBQ'))\n throw new Error(`unrecognized scene framing: ${scene.slice(0, 4)}`);\n return scene;\n}\n\n/**\n * Every file:// URI referenced by a serialized scene, minus the engine's own\n * `basePath` setting — a *directory* file:// URI the node engines serialize\n * into every scene as config (rewritten per environment on load), never an\n * agent asset reference. Directory URIs (trailing `/`) are excluded on the\n * same reasoning, which also keeps the guard safe if the basePath lookup ever\n * fails. Quote-bounded matching keeps prose that merely mentions file:// (in\n * a text block's content) from tripping the guard.\n */\nexport function findFileUrisInScene(\n scene: string,\n engineBasePath: string | undefined\n): string[] {\n const payload = scenePayload(scene);\n const uris = new Set<string>();\n for (const match of payload.matchAll(/\"(file:\\/\\/[^\"]+)\"/g)) {\n const uri = match[1];\n if (uri === engineBasePath || uri.endsWith('/')) continue;\n uris.add(uri);\n }\n return [...uris];\n}\n"]}
|
package/dist/tools/load.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../src/tools/load.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../src/tools/load.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK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'node:url';
|
|
24
24
|
import { SCENE_ALLOWED_RESOURCE_SCHEMES } from '../engine/scene-resource-schemes.js';
|
|
25
|
+
import { SCENE_COMPRESSION } from '../engine/scene-compression.js';
|
|
25
26
|
import { persistAsset } from '../workspace/content-hash.js';
|
|
26
27
|
import { detectDesignFormat } from './design-sniff.js';
|
|
27
28
|
import { detectMedia } from './media-sniff.js';
|
|
@@ -251,7 +252,8 @@ async function explodeArchiveIntoWorkspace(eng, fs) {
|
|
|
251
252
|
try {
|
|
252
253
|
// Common case: every transient relocated cleanly, so no scheme is disallowed.
|
|
253
254
|
return await eng.scene.saveToString({
|
|
254
|
-
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES
|
|
255
|
+
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,
|
|
256
|
+
compression: SCENE_COMPRESSION
|
|
255
257
|
});
|
|
256
258
|
}
|
|
257
259
|
catch (err) {
|
|
@@ -295,7 +297,8 @@ async function explodeArchiveIntoWorkspace(eng, fs) {
|
|
|
295
297
|
};
|
|
296
298
|
let scene = await eng.scene.saveToString({
|
|
297
299
|
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,
|
|
298
|
-
onDisallowedResourceScheme: drain
|
|
300
|
+
onDisallowedResourceScheme: drain,
|
|
301
|
+
compression: SCENE_COMPRESSION
|
|
299
302
|
});
|
|
300
303
|
if (unknown.size > 0) {
|
|
301
304
|
for (const url of unknown) {
|
|
@@ -304,7 +307,8 @@ async function explodeArchiveIntoWorkspace(eng, fs) {
|
|
|
304
307
|
unknown.clear();
|
|
305
308
|
scene = await eng.scene.saveToString({
|
|
306
309
|
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,
|
|
307
|
-
onDisallowedResourceScheme: drain
|
|
310
|
+
onDisallowedResourceScheme: drain,
|
|
311
|
+
compression: SCENE_COMPRESSION
|
|
308
312
|
});
|
|
309
313
|
if (unknown.size > 0) {
|
|
310
314
|
throw new Error(`load: cannot drain transient(s) ${[...unknown].join(', ')} — not persisted during explode.`);
|
|
@@ -422,7 +426,8 @@ const loadImage = async (eng, bytes, fs) => {
|
|
|
422
426
|
await eng.scene.createFromImage(`workspace://${relPath}`);
|
|
423
427
|
return {
|
|
424
428
|
scene: await eng.scene.saveToString({
|
|
425
|
-
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES
|
|
429
|
+
allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,
|
|
430
|
+
compression: SCENE_COMPRESSION
|
|
426
431
|
})
|
|
427
432
|
};
|
|
428
433
|
};
|
package/dist/tools/load.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/tools/load.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,6EAA6E;AAC7E,iEAAiE;AACjE,yEAAyE;AACzE,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,8BAA8B;AAC9B,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,gFAAgF;AAChF,wEAAwE;AAExE,OAAO,EAAE,QAAQ,IAAI,MAAM,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAIrF,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EAAqB,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAgD/C,MAAM,WAAW,GAAG;IAClB,0bA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AAY,EAAE,OAAO,CAAC,EAAE;yBACzB,CAAC,CAAC;oBACL,CAAC;oBACD,OAAO;wBACL,OAAO,EAAE;4BACP;gCACE,IAAI,EAAE,MAAe;gCACrB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;oCACnB,QAAQ,EAAE,OAAO,CAAC,EAAE;oCACpB,4DAA4D;oCAC5D,gDAAgD;oCAChD,KAAK,EAAE,KAAK,IAAI,UAAU;oCAC1B,MAAM;oCACN,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oCAC3C,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iCAC7C,CAAC;6BACH;yBACF;qBACF,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;oBACxB,OAAO,WAAW,CAChB,SAAS,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC3E,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// packages/codesign-mcp/src/tools/load.ts\n//\n// `load` — ingest a design file as a NEW design root revision (the inverse of\n// `save`): a native CE.SDK `.scene` file or `.zip` scene archive, or a foreign\n// design format (Photoshop `.psd`, InDesign `.idml`, PowerPoint `.pptx`, PDF)\n// translated into the engine by a lazily-imported adapter (CODE-11). Archives\n// (and translated foreign designs) are \"exploded\": their asset bytes live in\n// the engine as ephemeral `buffer:` resources (which scene-level\n// `saveToString` rejects — the CODE-3 bug); we extract each one into the\n// content-addressed asset store (`assets/<sha>.<ext>`), relocate it to a\n// durable `workspace://` URI, and only then serialize. Bare `.scene` files\n// carry no asset bytes: they persist as-is, plus a classification report of\n// every referenced asset URI.\n//\n// Both source variants normalize to bytes up front (fetch for `url`, disk\n// read for `path` — Local only), then dispatch on the sniffed content format\n// (design-sniff.ts). Archive bytes are staged to a temp file and loaded via a\n// `file://` URL: scene-level CE.SDK v1.77 has no `loadFromArchive(path/bytes)`,\n// only `loadFromArchiveURL`, and `file` is a first-class engine scheme.\n\nimport { promises as nodeFs } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { Mutex } from '../engine/mutex.js';\nimport { SCENE_ALLOWED_RESOURCE_SCHEMES } from '../engine/scene-resource-schemes.js';\nimport type { EngineSession } from '../engine/session.js';\nimport type { RevisionStore } from '../revisions/store.js';\nimport type { CodesignMcpToolRegistration } from '../server.js';\nimport { persistAsset } from '../workspace/content-hash.js';\nimport type { WorkspaceFS } from '../workspace/types.js';\nimport { type DesignFormat, detectDesignFormat } from './design-sniff.js';\nimport { detectMedia } from './media-sniff.js';\nimport type { EngineFlavor } from './engine.js';\n\n/** The slice of CreativeEngine this tool touches — keeps it testable. */\ninterface MinimalLoadEngine {\n scene: {\n loadFromArchiveURL(\n url: string,\n overrideEditorConfig?: boolean,\n waitForResources?: boolean\n ): Promise<number>;\n loadFromString(\n content: string,\n overrideEditorConfig?: boolean,\n waitForResources?: boolean\n ): Promise<number>;\n /** CODE-98 — subset signature: the optional dpi/layout parameters are\n * unused (engine defaults size the page to the image). */\n createFromImage(url: string): Promise<number>;\n saveToString(options?: {\n allowedResourceSchemes?: string[];\n onDisallowedResourceScheme?: (\n url: string,\n dataHash: string\n ) => Promise<string>;\n }): Promise<string>;\n };\n editor: {\n findAllTransientResources(): Array<{\n URL?: string;\n uri?: string;\n size: number;\n }>;\n findAllMediaURIs(): string[];\n getBufferLength(uri: string): number;\n getBufferData(uri: string, offset: number, length: number): Uint8Array;\n relocateResource(currentUrl: string, relocatedUrl: string): void;\n getMimeType(uri: string): Promise<string>;\n };\n}\n\ntype LoadSource = { url: string } | { path: string };\n\ninterface LoadArgs {\n source: LoadSource;\n title?: string;\n}\n\nconst DESCRIPTION = [\n 'Load a design as a NEW design root revision — a native CE.SDK `.scene` file or `.zip` scene archive; a foreign design file: Photoshop (`.psd`/`.psb`), InDesign (`.idml`), PowerPoint (`.pptx`), or PDF; or a plain image (PNG/JPEG/WebP/GIF) or SVG, which becomes a one-page design sized to the image (`format`: `\"image\"`/`\"svg\"`). The inverse of `save`. (`import` brings media INTO an existing design; `load` creates a new design FROM a file.)',\n '',\n 'Source: `{ url }` (http/https) or `{ path }` (absolute local file path; Local only). Archives are ingested: bundled asset bytes are extracted into the workspace as content-addressed `assets/<sha>.<ext>` files, so the loaded design is durable and behaves exactly like a natively-built one.',\n '',\n 'Returns JSON `{ revision, title, format }` — continue with `edit({ parent: revision, … })`. Foreign-format imports may add `warnings` (importer notes about what did not survive — substituted fonts, unsupported features): treat them as your touch-up list — `preview` the pages, then repair with `edit`; find replacement fonts via `asset_search`. Bare `.scene` loads additionally return `assets`: a classification of every referenced asset URI by scheme (`workspace` / `external` / `bundle` / `transient` / `other`). External URLs are NOT fetched; `transient` entries WILL be lost on the next save — replace or relocate them before committing further work.',\n '',\n 'Engine caveat: InDesign and PDF import need the WASM engine (`IMGLY_CESDK_ENGINE=wasm`) — on the native engine `load` errors cleanly for those two formats; Photoshop and PowerPoint import work on both.'\n].join('\\n');\n\n// Literal dynamic imports — esbuild inlines these in single-file mode (CODE-69\n// SEA bundle) while Node loads them on first use, so an unused (or, for pdf,\n// un-stageable) importer costs nothing at boot.\nconst IMPORTER_MODULES = {\n psd: () => import('./load-importers/psd.js'),\n idml: () => import('./load-importers/idml.js'),\n pptx: () => import('./load-importers/pptx.js'),\n pdf: () => import('./load-importers/pdf.js')\n} as const;\n\nconst SUPPORTED_FORMATS_HINT =\n 'Supported: a CE.SDK `.scene` file, a `.zip` scene archive, a Photoshop `.psd`/`.psb`, InDesign `.idml`, PowerPoint `.pptx`, or PDF (`.pdf`) file, or a plain image (`.png`/`.jpg`/`.jpeg`/`.webp`/`.gif`) or SVG (`.svg`).';\n\n// Formats the sniffer recognizes but load cannot turn into a design: design\n// formats with no importer (sketch/xd) and non-image media (CODE-98). `load`\n// rejects these up front with a clear message instead of letting the byte\n// payload fall through to the engine's archive/scene loader (a cryptic error).\nconst UNSUPPORTED_FORMATS: Record<\n 'sketch' | 'xd' | 'font' | 'audio' | 'video',\n string\n> = {\n sketch: 'Sketch (`.sketch`) files are not supported.',\n xd: 'Adobe XD (`.xd`) files are not supported.',\n font: 'This is a font file — use `import` to add it to an existing design as a brand font.',\n audio: \"This is an audio file — it can't be loaded as a design.\",\n video: \"This is a video file — video designs aren't supported yet.\"\n};\n\n// Type guard, so rejecting an unsupported format also narrows `format` down to\n// the importable set for the dispatch below (keeps IMPORTER_MODULES[format] typed).\nfunction isUnsupportedFormat(\n format: DesignFormat\n): format is keyof typeof UNSUPPORTED_FORMATS {\n return format in UNSUPPORTED_FORMATS;\n}\n\n// Foreign-format import is broken on `@cesdk/node-native` 1.78.0 (engine\n// matrix runs, 2026-07-20, on 1.79.0-nightly.20260715 — an earlier 1.78.0-only\n// native bug that broke ALL formats (saveToString ignoring\n// `allowedResourceSchemes`, ENGINE-637) is fixed on the nightlies, so psd and\n// pptx import fine on native, including the buffer:→workspace:// explode.\n// Still broken on native:\n// - idml: the importer queries the setting 'features/fontLineGapEnabled',\n// which the native engine does not have — fails inside renderPageElements.\n// - pdf: the importer's subset-font buffer survives as a straggler that\n// needs the explode's drain retry, and the drain can never trigger on\n// native because its engine errors carry no `err.code` (see\n// isDisallowedSchemesError) — fails with a disallowed-`buffer:`-scheme\n// error on the FIRST import.\n// Remove a format here once its native run of\n// test/tools/load-foreign.integration.test.ts is green (un-skip it there).\nconst NATIVE_UNSUPPORTED_FORMATS: ReadonlySet<DesignFormat> = new Set([\n 'idml',\n 'pdf'\n]);\n\n// The schema is built per-backend, like `save`'s outPath: the `{ path }`\n// source arm is advertised ONLY where local disk paths exist (Local).\n//\n// `source` is a FLAT object with optional `url`/`path` — deliberately NOT a\n// `oneOf` union. A `oneOf` here is the single construct most likely to break\n// tool calling: OpenAI bans it in strict mode, and weaker models (e.g.\n// openrouter:xiaomi/mimo-v2.5-pro, and Claude per samchon/openapi#88) serialize\n// the whole union value as an escaped JSON string, which then fails validation.\n// The \"exactly one of url/path\" invariant is enforced in `call` below, with a\n// clear error message instead of an opaque oneOf mismatch. This mirrors\n// `import`'s `source` shape. See test/tools/schema-best-practices.test.ts.\nfunction buildLoadInputSchema(allowPath: boolean) {\n const sourceProperties: Record<string, unknown> = {\n url: {\n type: 'string' as const,\n description: 'http(s) URL of the design file to load.'\n }\n };\n if (allowPath) {\n sourceProperties.path = {\n type: 'string' as const,\n description: 'Absolute local file path of the design file. Local-only.'\n };\n }\n return {\n type: 'object' as const,\n properties: {\n source: {\n type: 'object' as const,\n description: allowPath\n ? 'The design to load. Provide exactly one of `url` (http/https) or `path` (absolute local file path; Local only).'\n : 'The design to load. Provide `url` (http/https).',\n properties: sourceProperties,\n additionalProperties: false\n },\n title: {\n type: 'string' as const,\n description:\n \"Display name for the new design. Defaults to the source file's basename.\"\n }\n },\n required: ['source'],\n additionalProperties: false\n };\n}\n\n// Extensions stripped from a derived title, as one named list. The regex is\n// otherwise compiler-invisible — a format added to the importer set but missed\n// here would silently keep its extension in the title (e.g. 'deck.key').\nconst TITLE_EXTENSIONS = [\n 'zip',\n 'scene',\n 'psd',\n 'psb',\n 'idml',\n 'pptx',\n 'pdf',\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg'\n];\nconst TITLE_EXTENSION_RE = new RegExp(\n `\\\\.(${TITLE_EXTENSIONS.join('|')})$`,\n 'i'\n);\n\n/** Basename of the source, minus a known design-file extension. */\nfunction deriveTitle(source: LoadSource): string | undefined {\n let base: string;\n if ('url' in source) {\n const raw = new URL(source.url).pathname.split('/').pop() ?? '';\n try {\n base = decodeURIComponent(raw);\n } catch {\n base = raw; // malformed percent sequence — use the basename as-is\n }\n } else {\n // Local paths are literal filenames — never percent-decode them.\n base = source.path.split('/').pop() ?? '';\n }\n const name = base.replace(TITLE_EXTENSION_RE, '');\n return name === '' ? undefined : name;\n}\n\n// Broad enough for what CE.SDK archives actually bundle (images, fonts,\n// audio/video). Unknown types get a neutral `.bin` — the workspace store and\n// the /r/ route are extension-agnostic.\nconst MIME_EXT: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/wav': 'wav',\n 'audio/x-wav': 'wav',\n 'audio/mp4': 'm4a',\n 'font/ttf': 'ttf',\n 'font/otf': 'otf',\n 'font/woff': 'woff',\n 'font/woff2': 'woff2',\n 'application/x-font-ttf': 'ttf',\n 'application/font-sfnt': 'ttf'\n};\n\nfunction extForMime(mime: string): string {\n return MIME_EXT[mime] ?? 'bin';\n}\n\n/**\n * The buffer URI of a transient resource. @cesdk/node (WASM) exposes it as\n * `.URL`; @cesdk/node-native exposes it as `.uri`.\n */\nfunction transientResourceUri(resource: {\n URL?: string;\n uri?: string;\n}): string {\n const uri = resource.URL ?? resource.uri;\n if (uri === undefined) {\n throw new Error('load: transient resource has neither URL nor uri');\n }\n return uri;\n}\n\n/**\n * Persist one engine resource's bytes into the content-addressed asset store\n * and return its workspace-relative path. Identical bytes land at the\n * identical path regardless of caller (automatic dedup).\n */\nasync function persistResourceBytes(\n eng: MinimalLoadEngine,\n fs: WorkspaceFS,\n uri: string\n): Promise<string> {\n // getBufferLength + getBufferData is the engine-portable way to read a\n // transient (buffer:) resource's bytes: it exists on both @cesdk/node (WASM)\n // and @cesdk/node-native, whereas getResourceData is WASM-only. slice()\n // copies because the engine may reuse the returned buffer.\n const length = eng.editor.getBufferLength(uri);\n const bytes = eng.editor.getBufferData(uri, 0, length).slice();\n const ext = extForMime(await eng.editor.getMimeType(uri));\n return persistAsset(fs, bytes, ext);\n}\n\n/** The engine's error code when a serialized scene still carries a scheme\n * outside `allowedResourceSchemes` (e.g. a lingering `buffer:`). */\nconst DISALLOWED_SCHEMES_CODE = 'SCENE.DISALLOWED_SCHEMES';\n\n// `@cesdk/node-native` (as of 1.79.0-nightly.20260708) does not set `err.code`\n// on engine errors, so this predicate never matches on native and the\n// duplicate-transient drain retry below is effectively WASM-only until the\n// upstream fix lands. The first-save path (which normally succeeds after\n// explode) is unaffected.\nfunction isDisallowedSchemesError(err: unknown): boolean {\n return (\n err instanceof Error &&\n (err as Error & { code?: string }).code === DISALLOWED_SCHEMES_CODE\n );\n}\n\n/**\n * Extract every transient (`buffer:`) resource into the content-addressed\n * asset store and relocate it to its durable `workspace://` URI, then\n * serialize with the shared scene-scheme allowlist (which permits `workspace`\n * but not `buffer` — see scene-resource-schemes.ts), so a missed transient\n * still fails loudly instead of silently persisting an unloadable scene.\n */\nasync function explodeArchiveIntoWorkspace(\n eng: MinimalLoadEngine,\n fs: WorkspaceFS\n): Promise<string> {\n // Persist + relocate every transient, remembering each URL's workspace path.\n const persistedByUrl = new Map<string, string>();\n for (const resource of eng.editor.findAllTransientResources()) {\n const url = transientResourceUri(resource);\n // findAllTransientResources reports everything the engine materialized in\n // memory — on a warm engine that includes durable resources under their\n // real URIs (e.g. a bundle:// fallback font from a previously loaded\n // scene; see classifyAssets, CODE-3). Only a genuine buffer: resource is\n // in-memory-only and needs persisting; durable schemes serialize as-is\n // under the allowlist, and getBufferLength rejects their URIs anyway.\n if (!url.startsWith('buffer:')) continue;\n const relPath = await persistResourceBytes(eng, fs, url);\n persistedByUrl.set(url, relPath);\n eng.editor.relocateResource(url, `workspace://${relPath}`);\n }\n try {\n // Common case: every transient relocated cleanly, so no scheme is disallowed.\n return await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES\n });\n } catch (err) {\n if (!isDisallowedSchemesError(err)) throw err;\n // A straggler survived the relocation pass. Two known ways:\n // - A duplicate-content transient: relocateResource no-ops when two\n // transients share a content-addressed target (seen with duplicated\n // fonts in premium-template archives), so the engine still serializes\n // that straggler's buffer: URL — it IS in persistedByUrl.\n // - An engine-level revival findAllTransientResources never reported:\n // the typeface registry survives scene replacement and re-injects a\n // PREVIOUS import's subset-font buffer whenever the same typeface name\n // recurs (every repeat PDF import on a warm engine, CODE-11). The\n // buffer's bytes stay readable even though it is enumerated nowhere —\n // it is NOT in persistedByUrl.\n //\n // Two engine constraints shape this (CE.SDK v1.77): (1) the callback MUST\n // NOT re-enter the engine — getBufferData/getMimeType from inside it\n // deadlocks saveToString (it holds the engine while awaiting the\n // callback), and a throw from inside it deadlocks the same way, so the\n // callback only looks up / records and never throws; (2) we attach the\n // callback ONLY here, on the failure path — passing\n // onDisallowedResourceScheme when nothing is disallowed hangs\n // saveToString.\n //\n // Drain pass 1 rewrites every known straggler in the OUTPUT to its\n // persisted workspace:// form and records unknown ones. If any were\n // unknown, their bytes are persisted OUTSIDE the save (no re-entry) and\n // pass 2 rewrites them too. A straggler that still cannot be resolved\n // fails loudly AFTER the save returns, rather than silently persisting\n // an unloadable scene.\n const unknown = new Set<string>();\n const drain = async (url: string): Promise<string> => {\n const relPath = persistedByUrl.get(url);\n if (relPath === undefined) {\n unknown.add(url);\n return 'workspace://__unresolved__';\n }\n return `workspace://${relPath}`;\n };\n let scene = await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n onDisallowedResourceScheme: drain\n });\n if (unknown.size > 0) {\n for (const url of unknown) {\n persistedByUrl.set(url, await persistResourceBytes(eng, fs, url));\n }\n unknown.clear();\n scene = await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n onDisallowedResourceScheme: drain\n });\n if (unknown.size > 0) {\n throw new Error(\n `load: cannot drain transient(s) ${[...unknown].join(', ')} — not persisted during explode.`\n );\n }\n }\n // The drain fixed the serialized OUTPUT, but the engine still holds the\n // un-relocatable straggler in memory — its live state now diverges from the\n // persisted scene. `load` commits this slot warm for the next edit, so\n // reload the drained scene to realign: reloading collapses the duplicate\n // typeface onto its single workspace:// URI, leaving no buffer: straggler.\n // Without this, the next edit reuses the warm slot and its plain\n // saveToString (no drain) fails on the lingering buffer: URL.\n await eng.scene.loadFromString(scene, false, true);\n return scene;\n }\n}\n\ntype AssetClass = 'workspace' | 'external' | 'bundle' | 'transient' | 'other';\n\ninterface AssetReportEntry {\n uri: string;\n class: AssetClass;\n}\n\n/**\n * Classify one asset URI by its scheme. Only a `buffer:` URI is genuinely\n * `transient` (in-memory, silently lost on the next save); every scheme in\n * SCENE_ALLOWED_RESOURCE_SCHEMES (workspace/http/https/bundle/file/…) is durable.\n */\nfunction classifyUri(uri: string): AssetClass {\n if (uri.startsWith('workspace://')) return 'workspace';\n if (uri.startsWith('http://') || uri.startsWith('https://'))\n return 'external';\n if (uri.startsWith('bundle://')) return 'bundle';\n if (uri.startsWith('buffer:')) return 'transient';\n return 'other';\n}\n\n/**\n * Classify every asset reference of a bare `.scene` (which carries no asset\n * bytes) by scheme. A referenced asset does NOT reliably surface in\n * `findAllMediaURIs()` alone: durable re-fetchable refs the engine keeps as\n * URLs (e.g. http(s)) come back there, while anything it had to load into\n * memory — `workspace://` (resolved via our URI resolver), `bundle://`\n * fallbacks, and genuine `buffer:` orphans — comes back from\n * `findAllTransientResources()` carrying its real URI. So we read BOTH lists\n * and classify by scheme, deduped by URI.\n *\n * Verified against the real engine (CODE-3): after a waitForResources load a\n * resolved `workspace://` asset appears ONLY as a transient resource (never in\n * findAllMediaURIs), and an UNRESOLVABLE `workspace://` ref is silently dropped\n * and substituted (e.g. a bundled fallback font) — so there is no reliable\n * \"dangling\" signal to report, and no such class exists. External URLs are\n * reported, never fetched.\n */\nfunction classifyAssets(eng: MinimalLoadEngine): AssetReportEntry[] {\n const uris = new Set<string>([\n ...eng.editor.findAllMediaURIs(),\n ...eng.editor.findAllTransientResources().map(transientResourceUri)\n ]);\n return [...uris].map((uri) => ({ uri, class: classifyUri(uri) }));\n}\n\n/** What every format handler produces. `assets` (bare `.scene` only) and\n * `warnings` (foreign imports only) are format-specific extras. */\ninterface LoadResult {\n scene: string;\n assets?: AssetReportEntry[];\n warnings?: string[];\n}\n\n/**\n * Load one already-sniffed format's bytes into `eng` and return the serialized\n * scene (plus format-specific extras). `fs` is used by handlers that explode\n * transient (`buffer:`) resources into the workspace store.\n */\ntype LoadHandler = (\n eng: MinimalLoadEngine,\n bytes: Uint8Array,\n fs: WorkspaceFS\n) => Promise<LoadResult>;\n\n/**\n * Native `.zip` scene archive. Staged to a temp file and loaded via `file://` —\n * scene-level CE.SDK has no `loadFromArchive(bytes/path)`, only\n * `loadFromArchiveURL`. Its bundled asset bytes land as `buffer:` transients,\n * so it explodes them into the workspace before serializing.\n */\nconst loadArchive: LoadHandler = async (eng, bytes, fs) => {\n const stagedDir = await nodeFs.mkdtemp(join(tmpdir(), 'codesign-load-'));\n const staged = join(stagedDir, 'archive.zip');\n try {\n await nodeFs.writeFile(staged, bytes);\n // waitForResources: the archive's bundled bytes must be fully materialized\n // as buffer: resources before we enumerate them.\n await eng.scene.loadFromArchiveURL(pathToFileURL(staged).href, false, true);\n } finally {\n await nodeFs\n .rm(stagedDir, { recursive: true, force: true })\n .catch(() => {});\n }\n return { scene: await explodeArchiveIntoWorkspace(eng, fs) };\n};\n\n/**\n * Bare CE.SDK `.scene` string. Carries no asset bytes — it only references\n * assets by URI — so it persists verbatim (never re-serialized) alongside a\n * scheme classification of every referenced URI. A `buffer:` orphan here is\n * *reported* (see classifyAssets), never rescued.\n */\nconst loadScene: LoadHandler = async (eng, bytes) => {\n const content = new TextDecoder().decode(bytes).trim();\n try {\n await eng.scene.loadFromString(content, false, true);\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new Error(\n `the file is not a loadable design (${detail}). ${SUPPORTED_FORMATS_HINT}`\n );\n }\n return { scene: content, assets: classifyAssets(eng) };\n};\n\n/**\n * Plain image / SVG (CODE-98) — `scene.createFromImage` with engine-default\n * sizing (the page adopts the image's dimensions). Persist-first: the bytes\n * land content-addressed in the workspace BEFORE the engine sees a URI, so\n * the scene only ever references the durable `workspace://` form. No\n * `buffer:` transients exist on this path, hence plain saveToString (no\n * explode); a hypothetical warm-engine straggler would fail the allowlist\n * loudly and mark the slot dirty via the shared catch in `call`.\n */\nconst loadImage: LoadHandler = async (eng, bytes, fs) => {\n // Re-sniff for the canonical extension: detectDesignFormat returns only the\n // coarse format, and detectMedia is a pure few-byte check — re-running it\n // here is cheaper than widening every sniff caller's return type.\n const media = detectMedia(bytes);\n if (media === undefined || media.kind !== 'image') {\n // Unreachable: dispatch guarantees image/svg-classified bytes.\n throw new Error('load: bytes no longer sniff as an image');\n }\n const relPath = await persistAsset(fs, bytes, media.ext);\n await eng.scene.createFromImage(`workspace://${relPath}`);\n return {\n scene: await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES\n })\n };\n};\n\n/**\n * Foreign design format (psd/idml/pptx/pdf). The four differ only by which\n * lazily-imported adapter translates their bytes into the engine; each emits\n * `buffer:` transients, so the result explodes into the workspace like an\n * archive. `parseIntoEngine` types its engine param as `unknown` — passing the\n * `MinimalLoadEngine` (the same object as `slot.engine`) is fine.\n */\nfunction foreignHandler(format: keyof typeof IMPORTER_MODULES): LoadHandler {\n return async (eng, bytes, fs) => {\n const { parseIntoEngine } = await IMPORTER_MODULES[format]();\n const { warnings } = await parseIntoEngine(eng, bytes);\n return { scene: await explodeArchiveIntoWorkspace(eng, fs), warnings };\n };\n}\n\n/** One handler per importable format — `scene` and `archive` are ordinary\n * entries alongside the foreign importers. `sketch`/`xd` are rejected before\n * dispatch (UNSUPPORTED_FORMATS), so they need no entry. */\nconst FORMAT_HANDLERS: Record<\n Exclude<DesignFormat, keyof typeof UNSUPPORTED_FORMATS>,\n LoadHandler\n> = {\n archive: loadArchive,\n scene: loadScene,\n image: loadImage,\n svg: loadImage,\n psd: foreignHandler('psd'),\n idml: foreignHandler('idml'),\n pptx: foreignHandler('pptx'),\n pdf: foreignHandler('pdf')\n};\n\nfunction errorResult(text: string): {\n isError: true;\n content: Array<{ type: 'text'; text: string }>;\n} {\n return { isError: true, content: [{ type: 'text' as const, text }] };\n}\n\nexport interface CreateLoadToolOptions<E = unknown> {\n fs: WorkspaceFS;\n store: RevisionStore;\n session: EngineSession<E>;\n /** Guards the shared engine — load-then-explode must not interleave with another engine-touching call. */\n engineLock: Mutex;\n /** Whether to honour a `{ path }` source (Local: yes; Hosted/sandbox: no). */\n allowPath?: boolean;\n /** Called after the new root revision is written (viewer SSE hook). */\n onLeafWritten?: (event: {\n revision: string;\n rootRevision: string;\n }) => void | Promise<void>;\n /** Render a thumbnail for the new revision. Best-effort: failures are swallowed. */\n renderThumbnail?: (event: {\n revision: string;\n engine: E;\n }) => Promise<Uint8Array>;\n /**\n * The engine flavor that actually booted (production wires\n * `resolvedEngineFlavor` from engine.ts; `undefined` until first boot).\n * Foreign-format import is guarded off on `native` — see\n * NATIVE_UNSUPPORTED_FORMATS. Omitting the hook disables the guard.\n */\n engineFlavor?: () => EngineFlavor | undefined;\n}\n\nexport function createLoadTool<E = unknown>(\n opts: CreateLoadToolOptions<E>\n): CodesignMcpToolRegistration {\n const {\n fs,\n store,\n session,\n engineLock,\n allowPath = false,\n onLeafWritten,\n renderThumbnail,\n engineFlavor\n } = opts;\n return {\n name: 'load',\n description: DESCRIPTION,\n // The SNIFFED design format (scene/psd/idml/pptx/pdf/…) is the telemetry\n // signal; the argument is a URL/path and never leaves the machine. It only\n // exists in the tool's own result JSON (`{ revision, title, format }` in\n // content[0]) — error results carry prose there, so the parse just fails.\n telemetryFields: (_args, result) => {\n try {\n const content = (\n result as { content?: Array<{ text?: unknown }> } | undefined\n )?.content;\n const text = content?.[0]?.text;\n if (typeof text !== 'string') return undefined;\n const format = (JSON.parse(text) as { format?: unknown }).format;\n return typeof format === 'string' ? { format } : undefined;\n } catch {\n return undefined;\n }\n },\n inputSchema: buildLoadInputSchema(allowPath),\n call: async (rawArgs) => {\n const args = (rawArgs ?? {}) as Partial<LoadArgs>;\n const source = args.source;\n if (\n source === undefined ||\n typeof source !== 'object' ||\n 'url' in source === 'path' in source\n ) {\n return errorResult(\n 'load: `source` is required — exactly one of `{ url }` or `{ path }`.'\n );\n }\n if ('path' in source && !allowPath) {\n return errorResult(\n 'load: `source.path` is not supported on this (hosted) backend. Pass a `{ url }` source instead.'\n );\n }\n // Ingest bytes OUTSIDE the engine lock — network/disk I/O must not\n // block concurrent engine work.\n let bytes: Uint8Array;\n if ('url' in source) {\n let parsed: URL;\n try {\n parsed = new URL(source.url);\n } catch {\n return errorResult(`load: invalid URL \"${source.url}\".`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return errorResult('load: `source.url` must be http(s).');\n }\n let resp: Response;\n try {\n resp = await fetch(source.url);\n } catch (err) {\n return errorResult(\n `load: fetching \"${source.url}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n if (!resp.ok) {\n return errorResult(\n `load: fetching \"${source.url}\" failed with HTTP ${resp.status}.`\n );\n }\n try {\n bytes = new Uint8Array(await resp.arrayBuffer());\n } catch (err) {\n return errorResult(\n `load: reading the response body of \"${source.url}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n } else {\n try {\n bytes = new Uint8Array(await nodeFs.readFile(source.path));\n } catch (err) {\n return errorResult(\n `load: reading \"${source.path}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n }\n const title = args.title ?? deriveTitle(source);\n const format = await detectDesignFormat(bytes);\n // Recognized-but-unsupported formats never reach the engine: reject with a\n // clear message rather than a cryptic archive-loader failure.\n if (isUnsupportedFormat(format)) {\n return errorResult(\n `load: ${UNSUPPORTED_FORMATS[format]} ${SUPPORTED_FORMATS_HINT}`\n );\n }\n // The engine is loaded and mutated across several awaits — serialize\n // against any other engine-touching tool call.\n return engineLock.runExclusive(async () => {\n const slot = await session.acquire(null);\n // Checked AFTER acquire: the flavor is undefined until the engine has\n // booted once, and acquire is what boots it. The slot is untouched, so\n // rejecting here leaves it clean (no markDirty needed).\n if (\n NATIVE_UNSUPPORTED_FORMATS.has(format) &&\n engineFlavor?.() === 'native'\n ) {\n return errorResult(\n `load: ${format} import currently requires the WASM engine (set IMGLY_CESDK_ENGINE=wasm).`\n );\n }\n const eng = slot.engine as MinimalLoadEngine;\n try {\n const {\n scene,\n assets,\n warnings = []\n } = await FORMAT_HANDLERS[format](eng, bytes, fs);\n const written = await store.write({ scene, parent: null, title });\n session.commit(slot, written.id);\n // Thumbnail block mirrors edit.ts — duplication is deliberate (KISS).\n if (renderThumbnail) {\n try {\n const thumb = await renderThumbnail({\n revision: written.id,\n engine: slot.engine\n });\n const shard = written.id.slice(0, 2);\n const rest = written.id.slice(2);\n await fs.writeFile(\n `exports/${shard}/${rest}/preview.webp`,\n thumb\n );\n } catch {\n // best-effort; thumbnail failure must not poison the load\n }\n }\n if (onLeafWritten) {\n // A new root is its own lineage root.\n await onLeafWritten({\n revision: written.id,\n rootRevision: written.id\n });\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n revision: written.id,\n // store.write seeded a fresh root's title with exactly this\n // (store.ts) — no need to re-read it from disk.\n title: title ?? 'Untitled',\n format,\n ...(assets !== undefined ? { assets } : {}),\n ...(warnings.length > 0 ? { warnings } : {})\n })\n }\n ]\n };\n } catch (err) {\n session.markDirty(slot);\n return errorResult(\n `load: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`\n );\n }\n });\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/tools/load.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,8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AQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iCAC7C,CAAC;6BACH;yBACF;qBACF,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;oBACxB,OAAO,WAAW,CAChB,SAAS,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC3E,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// packages/codesign-mcp/src/tools/load.ts\n//\n// `load` — ingest a design file as a NEW design root revision (the inverse of\n// `save`): a native CE.SDK `.scene` file or `.zip` scene archive, or a foreign\n// design format (Photoshop `.psd`, InDesign `.idml`, PowerPoint `.pptx`, PDF)\n// translated into the engine by a lazily-imported adapter (CODE-11). Archives\n// (and translated foreign designs) are \"exploded\": their asset bytes live in\n// the engine as ephemeral `buffer:` resources (which scene-level\n// `saveToString` rejects — the CODE-3 bug); we extract each one into the\n// content-addressed asset store (`assets/<sha>.<ext>`), relocate it to a\n// durable `workspace://` URI, and only then serialize. Bare `.scene` files\n// carry no asset bytes: they persist as-is, plus a classification report of\n// every referenced asset URI.\n//\n// Both source variants normalize to bytes up front (fetch for `url`, disk\n// read for `path` — Local only), then dispatch on the sniffed content format\n// (design-sniff.ts). Archive bytes are staged to a temp file and loaded via a\n// `file://` URL: scene-level CE.SDK v1.77 has no `loadFromArchive(path/bytes)`,\n// only `loadFromArchiveURL`, and `file` is a first-class engine scheme.\n\nimport { promises as nodeFs } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { Mutex } from '../engine/mutex.js';\nimport { SCENE_ALLOWED_RESOURCE_SCHEMES } from '../engine/scene-resource-schemes.js';\nimport { SCENE_COMPRESSION } from '../engine/scene-compression.js';\nimport type { EngineSession } from '../engine/session.js';\nimport type { RevisionStore } from '../revisions/store.js';\nimport type { CodesignMcpToolRegistration } from '../server.js';\nimport { persistAsset } from '../workspace/content-hash.js';\nimport type { WorkspaceFS } from '../workspace/types.js';\nimport { type DesignFormat, detectDesignFormat } from './design-sniff.js';\nimport { detectMedia } from './media-sniff.js';\nimport type { EngineFlavor } from './engine.js';\n\n/** The slice of CreativeEngine this tool touches — keeps it testable. */\ninterface MinimalLoadEngine {\n scene: {\n loadFromArchiveURL(\n url: string,\n overrideEditorConfig?: boolean,\n waitForResources?: boolean\n ): Promise<number>;\n loadFromString(\n content: string,\n overrideEditorConfig?: boolean,\n waitForResources?: boolean\n ): Promise<number>;\n /** CODE-98 — subset signature: the optional dpi/layout parameters are\n * unused (engine defaults size the page to the image). */\n createFromImage(url: string): Promise<number>;\n /** `compression` is a loose structural stand-in, not authoritative:\n * scene-compression.ts types SCENE_COMPRESSION against the engine's real\n * `SaveToStringOptions['compression']`, so a shape drift in the engine's\n * actual option type fails there, not silently here. */\n saveToString(options?: {\n allowedResourceSchemes?: string[];\n onDisallowedResourceScheme?: (\n url: string,\n dataHash: string\n ) => Promise<string>;\n compression?: { format?: number; level?: number };\n }): Promise<string>;\n };\n editor: {\n findAllTransientResources(): Array<{\n URL?: string;\n uri?: string;\n size: number;\n }>;\n findAllMediaURIs(): string[];\n getBufferLength(uri: string): number;\n getBufferData(uri: string, offset: number, length: number): Uint8Array;\n relocateResource(currentUrl: string, relocatedUrl: string): void;\n getMimeType(uri: string): Promise<string>;\n };\n}\n\ntype LoadSource = { url: string } | { path: string };\n\ninterface LoadArgs {\n source: LoadSource;\n title?: string;\n}\n\nconst DESCRIPTION = [\n 'Load a design as a NEW design root revision — a native CE.SDK `.scene` file or `.zip` scene archive; a foreign design file: Photoshop (`.psd`/`.psb`), InDesign (`.idml`), PowerPoint (`.pptx`), or PDF; or a plain image (PNG/JPEG/WebP/GIF) or SVG, which becomes a one-page design sized to the image (`format`: `\"image\"`/`\"svg\"`). The inverse of `save`. (`import` brings media INTO an existing design; `load` creates a new design FROM a file.)',\n '',\n 'Source: `{ url }` (http/https) or `{ path }` (absolute local file path; Local only). Archives are ingested: bundled asset bytes are extracted into the workspace as content-addressed `assets/<sha>.<ext>` files, so the loaded design is durable and behaves exactly like a natively-built one.',\n '',\n 'Returns JSON `{ revision, title, format }` — continue with `edit({ parent: revision, … })`. Foreign-format imports may add `warnings` (importer notes about what did not survive — substituted fonts, unsupported features): treat them as your touch-up list — `preview` the pages, then repair with `edit`; find replacement fonts via `asset_search`. Bare `.scene` loads additionally return `assets`: a classification of every referenced asset URI by scheme (`workspace` / `external` / `bundle` / `transient` / `other`). External URLs are NOT fetched; `transient` entries WILL be lost on the next save — replace or relocate them before committing further work.',\n '',\n 'Engine caveat: InDesign and PDF import need the WASM engine (`IMGLY_CESDK_ENGINE=wasm`) — on the native engine `load` errors cleanly for those two formats; Photoshop and PowerPoint import work on both.'\n].join('\\n');\n\n// Literal dynamic imports — esbuild inlines these in single-file mode (CODE-69\n// SEA bundle) while Node loads them on first use, so an unused (or, for pdf,\n// un-stageable) importer costs nothing at boot.\nconst IMPORTER_MODULES = {\n psd: () => import('./load-importers/psd.js'),\n idml: () => import('./load-importers/idml.js'),\n pptx: () => import('./load-importers/pptx.js'),\n pdf: () => import('./load-importers/pdf.js')\n} as const;\n\nconst SUPPORTED_FORMATS_HINT =\n 'Supported: a CE.SDK `.scene` file, a `.zip` scene archive, a Photoshop `.psd`/`.psb`, InDesign `.idml`, PowerPoint `.pptx`, or PDF (`.pdf`) file, or a plain image (`.png`/`.jpg`/`.jpeg`/`.webp`/`.gif`) or SVG (`.svg`).';\n\n// Formats the sniffer recognizes but load cannot turn into a design: design\n// formats with no importer (sketch/xd) and non-image media (CODE-98). `load`\n// rejects these up front with a clear message instead of letting the byte\n// payload fall through to the engine's archive/scene loader (a cryptic error).\nconst UNSUPPORTED_FORMATS: Record<\n 'sketch' | 'xd' | 'font' | 'audio' | 'video',\n string\n> = {\n sketch: 'Sketch (`.sketch`) files are not supported.',\n xd: 'Adobe XD (`.xd`) files are not supported.',\n font: 'This is a font file — use `import` to add it to an existing design as a brand font.',\n audio: \"This is an audio file — it can't be loaded as a design.\",\n video: \"This is a video file — video designs aren't supported yet.\"\n};\n\n// Type guard, so rejecting an unsupported format also narrows `format` down to\n// the importable set for the dispatch below (keeps IMPORTER_MODULES[format] typed).\nfunction isUnsupportedFormat(\n format: DesignFormat\n): format is keyof typeof UNSUPPORTED_FORMATS {\n return format in UNSUPPORTED_FORMATS;\n}\n\n// Foreign-format import is broken on `@cesdk/node-native` 1.78.0 (engine\n// matrix runs, 2026-07-20, on 1.79.0-nightly.20260715 — an earlier 1.78.0-only\n// native bug that broke ALL formats (saveToString ignoring\n// `allowedResourceSchemes`, ENGINE-637) is fixed on the nightlies, so psd and\n// pptx import fine on native, including the buffer:→workspace:// explode.\n// Still broken on native:\n// - idml: the importer queries the setting 'features/fontLineGapEnabled',\n// which the native engine does not have — fails inside renderPageElements.\n// - pdf: the importer's subset-font buffer survives as a straggler that\n// needs the explode's drain retry, and the drain can never trigger on\n// native because its engine errors carry no `err.code` (see\n// isDisallowedSchemesError) — fails with a disallowed-`buffer:`-scheme\n// error on the FIRST import.\n// Remove a format here once its native run of\n// test/tools/load-foreign.integration.test.ts is green (un-skip it there).\nconst NATIVE_UNSUPPORTED_FORMATS: ReadonlySet<DesignFormat> = new Set([\n 'idml',\n 'pdf'\n]);\n\n// The schema is built per-backend, like `save`'s outPath: the `{ path }`\n// source arm is advertised ONLY where local disk paths exist (Local).\n//\n// `source` is a FLAT object with optional `url`/`path` — deliberately NOT a\n// `oneOf` union. A `oneOf` here is the single construct most likely to break\n// tool calling: OpenAI bans it in strict mode, and weaker models (e.g.\n// openrouter:xiaomi/mimo-v2.5-pro, and Claude per samchon/openapi#88) serialize\n// the whole union value as an escaped JSON string, which then fails validation.\n// The \"exactly one of url/path\" invariant is enforced in `call` below, with a\n// clear error message instead of an opaque oneOf mismatch. This mirrors\n// `import`'s `source` shape. See test/tools/schema-best-practices.test.ts.\nfunction buildLoadInputSchema(allowPath: boolean) {\n const sourceProperties: Record<string, unknown> = {\n url: {\n type: 'string' as const,\n description: 'http(s) URL of the design file to load.'\n }\n };\n if (allowPath) {\n sourceProperties.path = {\n type: 'string' as const,\n description: 'Absolute local file path of the design file. Local-only.'\n };\n }\n return {\n type: 'object' as const,\n properties: {\n source: {\n type: 'object' as const,\n description: allowPath\n ? 'The design to load. Provide exactly one of `url` (http/https) or `path` (absolute local file path; Local only).'\n : 'The design to load. Provide `url` (http/https).',\n properties: sourceProperties,\n additionalProperties: false\n },\n title: {\n type: 'string' as const,\n description:\n \"Display name for the new design. Defaults to the source file's basename.\"\n }\n },\n required: ['source'],\n additionalProperties: false\n };\n}\n\n// Extensions stripped from a derived title, as one named list. The regex is\n// otherwise compiler-invisible — a format added to the importer set but missed\n// here would silently keep its extension in the title (e.g. 'deck.key').\nconst TITLE_EXTENSIONS = [\n 'zip',\n 'scene',\n 'psd',\n 'psb',\n 'idml',\n 'pptx',\n 'pdf',\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg'\n];\nconst TITLE_EXTENSION_RE = new RegExp(\n `\\\\.(${TITLE_EXTENSIONS.join('|')})$`,\n 'i'\n);\n\n/** Basename of the source, minus a known design-file extension. */\nfunction deriveTitle(source: LoadSource): string | undefined {\n let base: string;\n if ('url' in source) {\n const raw = new URL(source.url).pathname.split('/').pop() ?? '';\n try {\n base = decodeURIComponent(raw);\n } catch {\n base = raw; // malformed percent sequence — use the basename as-is\n }\n } else {\n // Local paths are literal filenames — never percent-decode them.\n base = source.path.split('/').pop() ?? '';\n }\n const name = base.replace(TITLE_EXTENSION_RE, '');\n return name === '' ? undefined : name;\n}\n\n// Broad enough for what CE.SDK archives actually bundle (images, fonts,\n// audio/video). Unknown types get a neutral `.bin` — the workspace store and\n// the /r/ route are extension-agnostic.\nconst MIME_EXT: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/wav': 'wav',\n 'audio/x-wav': 'wav',\n 'audio/mp4': 'm4a',\n 'font/ttf': 'ttf',\n 'font/otf': 'otf',\n 'font/woff': 'woff',\n 'font/woff2': 'woff2',\n 'application/x-font-ttf': 'ttf',\n 'application/font-sfnt': 'ttf'\n};\n\nfunction extForMime(mime: string): string {\n return MIME_EXT[mime] ?? 'bin';\n}\n\n/**\n * The buffer URI of a transient resource. @cesdk/node (WASM) exposes it as\n * `.URL`; @cesdk/node-native exposes it as `.uri`.\n */\nfunction transientResourceUri(resource: {\n URL?: string;\n uri?: string;\n}): string {\n const uri = resource.URL ?? resource.uri;\n if (uri === undefined) {\n throw new Error('load: transient resource has neither URL nor uri');\n }\n return uri;\n}\n\n/**\n * Persist one engine resource's bytes into the content-addressed asset store\n * and return its workspace-relative path. Identical bytes land at the\n * identical path regardless of caller (automatic dedup).\n */\nasync function persistResourceBytes(\n eng: MinimalLoadEngine,\n fs: WorkspaceFS,\n uri: string\n): Promise<string> {\n // getBufferLength + getBufferData is the engine-portable way to read a\n // transient (buffer:) resource's bytes: it exists on both @cesdk/node (WASM)\n // and @cesdk/node-native, whereas getResourceData is WASM-only. slice()\n // copies because the engine may reuse the returned buffer.\n const length = eng.editor.getBufferLength(uri);\n const bytes = eng.editor.getBufferData(uri, 0, length).slice();\n const ext = extForMime(await eng.editor.getMimeType(uri));\n return persistAsset(fs, bytes, ext);\n}\n\n/** The engine's error code when a serialized scene still carries a scheme\n * outside `allowedResourceSchemes` (e.g. a lingering `buffer:`). */\nconst DISALLOWED_SCHEMES_CODE = 'SCENE.DISALLOWED_SCHEMES';\n\n// `@cesdk/node-native` (as of 1.79.0-nightly.20260708) does not set `err.code`\n// on engine errors, so this predicate never matches on native and the\n// duplicate-transient drain retry below is effectively WASM-only until the\n// upstream fix lands. The first-save path (which normally succeeds after\n// explode) is unaffected.\nfunction isDisallowedSchemesError(err: unknown): boolean {\n return (\n err instanceof Error &&\n (err as Error & { code?: string }).code === DISALLOWED_SCHEMES_CODE\n );\n}\n\n/**\n * Extract every transient (`buffer:`) resource into the content-addressed\n * asset store and relocate it to its durable `workspace://` URI, then\n * serialize with the shared scene-scheme allowlist (which permits `workspace`\n * but not `buffer` — see scene-resource-schemes.ts), so a missed transient\n * still fails loudly instead of silently persisting an unloadable scene.\n */\nasync function explodeArchiveIntoWorkspace(\n eng: MinimalLoadEngine,\n fs: WorkspaceFS\n): Promise<string> {\n // Persist + relocate every transient, remembering each URL's workspace path.\n const persistedByUrl = new Map<string, string>();\n for (const resource of eng.editor.findAllTransientResources()) {\n const url = transientResourceUri(resource);\n // findAllTransientResources reports everything the engine materialized in\n // memory — on a warm engine that includes durable resources under their\n // real URIs (e.g. a bundle:// fallback font from a previously loaded\n // scene; see classifyAssets, CODE-3). Only a genuine buffer: resource is\n // in-memory-only and needs persisting; durable schemes serialize as-is\n // under the allowlist, and getBufferLength rejects their URIs anyway.\n if (!url.startsWith('buffer:')) continue;\n const relPath = await persistResourceBytes(eng, fs, url);\n persistedByUrl.set(url, relPath);\n eng.editor.relocateResource(url, `workspace://${relPath}`);\n }\n try {\n // Common case: every transient relocated cleanly, so no scheme is disallowed.\n return await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n compression: SCENE_COMPRESSION\n });\n } catch (err) {\n if (!isDisallowedSchemesError(err)) throw err;\n // A straggler survived the relocation pass. Two known ways:\n // - A duplicate-content transient: relocateResource no-ops when two\n // transients share a content-addressed target (seen with duplicated\n // fonts in premium-template archives), so the engine still serializes\n // that straggler's buffer: URL — it IS in persistedByUrl.\n // - An engine-level revival findAllTransientResources never reported:\n // the typeface registry survives scene replacement and re-injects a\n // PREVIOUS import's subset-font buffer whenever the same typeface name\n // recurs (every repeat PDF import on a warm engine, CODE-11). The\n // buffer's bytes stay readable even though it is enumerated nowhere —\n // it is NOT in persistedByUrl.\n //\n // Two engine constraints shape this (CE.SDK v1.77): (1) the callback MUST\n // NOT re-enter the engine — getBufferData/getMimeType from inside it\n // deadlocks saveToString (it holds the engine while awaiting the\n // callback), and a throw from inside it deadlocks the same way, so the\n // callback only looks up / records and never throws; (2) we attach the\n // callback ONLY here, on the failure path — passing\n // onDisallowedResourceScheme when nothing is disallowed hangs\n // saveToString.\n //\n // Drain pass 1 rewrites every known straggler in the OUTPUT to its\n // persisted workspace:// form and records unknown ones. If any were\n // unknown, their bytes are persisted OUTSIDE the save (no re-entry) and\n // pass 2 rewrites them too. A straggler that still cannot be resolved\n // fails loudly AFTER the save returns, rather than silently persisting\n // an unloadable scene.\n const unknown = new Set<string>();\n const drain = async (url: string): Promise<string> => {\n const relPath = persistedByUrl.get(url);\n if (relPath === undefined) {\n unknown.add(url);\n return 'workspace://__unresolved__';\n }\n return `workspace://${relPath}`;\n };\n let scene = await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n onDisallowedResourceScheme: drain,\n compression: SCENE_COMPRESSION\n });\n if (unknown.size > 0) {\n for (const url of unknown) {\n persistedByUrl.set(url, await persistResourceBytes(eng, fs, url));\n }\n unknown.clear();\n scene = await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n onDisallowedResourceScheme: drain,\n compression: SCENE_COMPRESSION\n });\n if (unknown.size > 0) {\n throw new Error(\n `load: cannot drain transient(s) ${[...unknown].join(', ')} — not persisted during explode.`\n );\n }\n }\n // The drain fixed the serialized OUTPUT, but the engine still holds the\n // un-relocatable straggler in memory — its live state now diverges from the\n // persisted scene. `load` commits this slot warm for the next edit, so\n // reload the drained scene to realign: reloading collapses the duplicate\n // typeface onto its single workspace:// URI, leaving no buffer: straggler.\n // Without this, the next edit reuses the warm slot and its plain\n // saveToString (no drain) fails on the lingering buffer: URL.\n await eng.scene.loadFromString(scene, false, true);\n return scene;\n }\n}\n\ntype AssetClass = 'workspace' | 'external' | 'bundle' | 'transient' | 'other';\n\ninterface AssetReportEntry {\n uri: string;\n class: AssetClass;\n}\n\n/**\n * Classify one asset URI by its scheme. Only a `buffer:` URI is genuinely\n * `transient` (in-memory, silently lost on the next save); every scheme in\n * SCENE_ALLOWED_RESOURCE_SCHEMES (workspace/http/https/bundle/file/…) is durable.\n */\nfunction classifyUri(uri: string): AssetClass {\n if (uri.startsWith('workspace://')) return 'workspace';\n if (uri.startsWith('http://') || uri.startsWith('https://'))\n return 'external';\n if (uri.startsWith('bundle://')) return 'bundle';\n if (uri.startsWith('buffer:')) return 'transient';\n return 'other';\n}\n\n/**\n * Classify every asset reference of a bare `.scene` (which carries no asset\n * bytes) by scheme. A referenced asset does NOT reliably surface in\n * `findAllMediaURIs()` alone: durable re-fetchable refs the engine keeps as\n * URLs (e.g. http(s)) come back there, while anything it had to load into\n * memory — `workspace://` (resolved via our URI resolver), `bundle://`\n * fallbacks, and genuine `buffer:` orphans — comes back from\n * `findAllTransientResources()` carrying its real URI. So we read BOTH lists\n * and classify by scheme, deduped by URI.\n *\n * Verified against the real engine (CODE-3): after a waitForResources load a\n * resolved `workspace://` asset appears ONLY as a transient resource (never in\n * findAllMediaURIs), and an UNRESOLVABLE `workspace://` ref is silently dropped\n * and substituted (e.g. a bundled fallback font) — so there is no reliable\n * \"dangling\" signal to report, and no such class exists. External URLs are\n * reported, never fetched.\n */\nfunction classifyAssets(eng: MinimalLoadEngine): AssetReportEntry[] {\n const uris = new Set<string>([\n ...eng.editor.findAllMediaURIs(),\n ...eng.editor.findAllTransientResources().map(transientResourceUri)\n ]);\n return [...uris].map((uri) => ({ uri, class: classifyUri(uri) }));\n}\n\n/** What every format handler produces. `assets` (bare `.scene` only) and\n * `warnings` (foreign imports only) are format-specific extras. */\ninterface LoadResult {\n scene: string;\n assets?: AssetReportEntry[];\n warnings?: string[];\n}\n\n/**\n * Load one already-sniffed format's bytes into `eng` and return the serialized\n * scene (plus format-specific extras). `fs` is used by handlers that explode\n * transient (`buffer:`) resources into the workspace store.\n */\ntype LoadHandler = (\n eng: MinimalLoadEngine,\n bytes: Uint8Array,\n fs: WorkspaceFS\n) => Promise<LoadResult>;\n\n/**\n * Native `.zip` scene archive. Staged to a temp file and loaded via `file://` —\n * scene-level CE.SDK has no `loadFromArchive(bytes/path)`, only\n * `loadFromArchiveURL`. Its bundled asset bytes land as `buffer:` transients,\n * so it explodes them into the workspace before serializing.\n */\nconst loadArchive: LoadHandler = async (eng, bytes, fs) => {\n const stagedDir = await nodeFs.mkdtemp(join(tmpdir(), 'codesign-load-'));\n const staged = join(stagedDir, 'archive.zip');\n try {\n await nodeFs.writeFile(staged, bytes);\n // waitForResources: the archive's bundled bytes must be fully materialized\n // as buffer: resources before we enumerate them.\n await eng.scene.loadFromArchiveURL(pathToFileURL(staged).href, false, true);\n } finally {\n await nodeFs\n .rm(stagedDir, { recursive: true, force: true })\n .catch(() => {});\n }\n return { scene: await explodeArchiveIntoWorkspace(eng, fs) };\n};\n\n/**\n * Bare CE.SDK `.scene` string. Carries no asset bytes — it only references\n * assets by URI — so it persists verbatim (never re-serialized) alongside a\n * scheme classification of every referenced URI. A `buffer:` orphan here is\n * *reported* (see classifyAssets), never rescued.\n */\nconst loadScene: LoadHandler = async (eng, bytes) => {\n const content = new TextDecoder().decode(bytes).trim();\n try {\n await eng.scene.loadFromString(content, false, true);\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new Error(\n `the file is not a loadable design (${detail}). ${SUPPORTED_FORMATS_HINT}`\n );\n }\n return { scene: content, assets: classifyAssets(eng) };\n};\n\n/**\n * Plain image / SVG (CODE-98) — `scene.createFromImage` with engine-default\n * sizing (the page adopts the image's dimensions). Persist-first: the bytes\n * land content-addressed in the workspace BEFORE the engine sees a URI, so\n * the scene only ever references the durable `workspace://` form. No\n * `buffer:` transients exist on this path, hence plain saveToString (no\n * explode); a hypothetical warm-engine straggler would fail the allowlist\n * loudly and mark the slot dirty via the shared catch in `call`.\n */\nconst loadImage: LoadHandler = async (eng, bytes, fs) => {\n // Re-sniff for the canonical extension: detectDesignFormat returns only the\n // coarse format, and detectMedia is a pure few-byte check — re-running it\n // here is cheaper than widening every sniff caller's return type.\n const media = detectMedia(bytes);\n if (media === undefined || media.kind !== 'image') {\n // Unreachable: dispatch guarantees image/svg-classified bytes.\n throw new Error('load: bytes no longer sniff as an image');\n }\n const relPath = await persistAsset(fs, bytes, media.ext);\n await eng.scene.createFromImage(`workspace://${relPath}`);\n return {\n scene: await eng.scene.saveToString({\n allowedResourceSchemes: SCENE_ALLOWED_RESOURCE_SCHEMES,\n compression: SCENE_COMPRESSION\n })\n };\n};\n\n/**\n * Foreign design format (psd/idml/pptx/pdf). The four differ only by which\n * lazily-imported adapter translates their bytes into the engine; each emits\n * `buffer:` transients, so the result explodes into the workspace like an\n * archive. `parseIntoEngine` types its engine param as `unknown` — passing the\n * `MinimalLoadEngine` (the same object as `slot.engine`) is fine.\n */\nfunction foreignHandler(format: keyof typeof IMPORTER_MODULES): LoadHandler {\n return async (eng, bytes, fs) => {\n const { parseIntoEngine } = await IMPORTER_MODULES[format]();\n const { warnings } = await parseIntoEngine(eng, bytes);\n return { scene: await explodeArchiveIntoWorkspace(eng, fs), warnings };\n };\n}\n\n/** One handler per importable format — `scene` and `archive` are ordinary\n * entries alongside the foreign importers. `sketch`/`xd` are rejected before\n * dispatch (UNSUPPORTED_FORMATS), so they need no entry. */\nconst FORMAT_HANDLERS: Record<\n Exclude<DesignFormat, keyof typeof UNSUPPORTED_FORMATS>,\n LoadHandler\n> = {\n archive: loadArchive,\n scene: loadScene,\n image: loadImage,\n svg: loadImage,\n psd: foreignHandler('psd'),\n idml: foreignHandler('idml'),\n pptx: foreignHandler('pptx'),\n pdf: foreignHandler('pdf')\n};\n\nfunction errorResult(text: string): {\n isError: true;\n content: Array<{ type: 'text'; text: string }>;\n} {\n return { isError: true, content: [{ type: 'text' as const, text }] };\n}\n\nexport interface CreateLoadToolOptions<E = unknown> {\n fs: WorkspaceFS;\n store: RevisionStore;\n session: EngineSession<E>;\n /** Guards the shared engine — load-then-explode must not interleave with another engine-touching call. */\n engineLock: Mutex;\n /** Whether to honour a `{ path }` source (Local: yes; Hosted/sandbox: no). */\n allowPath?: boolean;\n /** Called after the new root revision is written (viewer SSE hook). */\n onLeafWritten?: (event: {\n revision: string;\n rootRevision: string;\n }) => void | Promise<void>;\n /** Render a thumbnail for the new revision. Best-effort: failures are swallowed. */\n renderThumbnail?: (event: {\n revision: string;\n engine: E;\n }) => Promise<Uint8Array>;\n /**\n * The engine flavor that actually booted (production wires\n * `resolvedEngineFlavor` from engine.ts; `undefined` until first boot).\n * Foreign-format import is guarded off on `native` — see\n * NATIVE_UNSUPPORTED_FORMATS. Omitting the hook disables the guard.\n */\n engineFlavor?: () => EngineFlavor | undefined;\n}\n\nexport function createLoadTool<E = unknown>(\n opts: CreateLoadToolOptions<E>\n): CodesignMcpToolRegistration {\n const {\n fs,\n store,\n session,\n engineLock,\n allowPath = false,\n onLeafWritten,\n renderThumbnail,\n engineFlavor\n } = opts;\n return {\n name: 'load',\n description: DESCRIPTION,\n // The SNIFFED design format (scene/psd/idml/pptx/pdf/…) is the telemetry\n // signal; the argument is a URL/path and never leaves the machine. It only\n // exists in the tool's own result JSON (`{ revision, title, format }` in\n // content[0]) — error results carry prose there, so the parse just fails.\n telemetryFields: (_args, result) => {\n try {\n const content = (\n result as { content?: Array<{ text?: unknown }> } | undefined\n )?.content;\n const text = content?.[0]?.text;\n if (typeof text !== 'string') return undefined;\n const format = (JSON.parse(text) as { format?: unknown }).format;\n return typeof format === 'string' ? { format } : undefined;\n } catch {\n return undefined;\n }\n },\n inputSchema: buildLoadInputSchema(allowPath),\n call: async (rawArgs) => {\n const args = (rawArgs ?? {}) as Partial<LoadArgs>;\n const source = args.source;\n if (\n source === undefined ||\n typeof source !== 'object' ||\n 'url' in source === 'path' in source\n ) {\n return errorResult(\n 'load: `source` is required — exactly one of `{ url }` or `{ path }`.'\n );\n }\n if ('path' in source && !allowPath) {\n return errorResult(\n 'load: `source.path` is not supported on this (hosted) backend. Pass a `{ url }` source instead.'\n );\n }\n // Ingest bytes OUTSIDE the engine lock — network/disk I/O must not\n // block concurrent engine work.\n let bytes: Uint8Array;\n if ('url' in source) {\n let parsed: URL;\n try {\n parsed = new URL(source.url);\n } catch {\n return errorResult(`load: invalid URL \"${source.url}\".`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return errorResult('load: `source.url` must be http(s).');\n }\n let resp: Response;\n try {\n resp = await fetch(source.url);\n } catch (err) {\n return errorResult(\n `load: fetching \"${source.url}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n if (!resp.ok) {\n return errorResult(\n `load: fetching \"${source.url}\" failed with HTTP ${resp.status}.`\n );\n }\n try {\n bytes = new Uint8Array(await resp.arrayBuffer());\n } catch (err) {\n return errorResult(\n `load: reading the response body of \"${source.url}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n } else {\n try {\n bytes = new Uint8Array(await nodeFs.readFile(source.path));\n } catch (err) {\n return errorResult(\n `load: reading \"${source.path}\" failed — ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n }\n }\n const title = args.title ?? deriveTitle(source);\n const format = await detectDesignFormat(bytes);\n // Recognized-but-unsupported formats never reach the engine: reject with a\n // clear message rather than a cryptic archive-loader failure.\n if (isUnsupportedFormat(format)) {\n return errorResult(\n `load: ${UNSUPPORTED_FORMATS[format]} ${SUPPORTED_FORMATS_HINT}`\n );\n }\n // The engine is loaded and mutated across several awaits — serialize\n // against any other engine-touching tool call.\n return engineLock.runExclusive(async () => {\n const slot = await session.acquire(null);\n // Checked AFTER acquire: the flavor is undefined until the engine has\n // booted once, and acquire is what boots it. The slot is untouched, so\n // rejecting here leaves it clean (no markDirty needed).\n if (\n NATIVE_UNSUPPORTED_FORMATS.has(format) &&\n engineFlavor?.() === 'native'\n ) {\n return errorResult(\n `load: ${format} import currently requires the WASM engine (set IMGLY_CESDK_ENGINE=wasm).`\n );\n }\n const eng = slot.engine as MinimalLoadEngine;\n try {\n const {\n scene,\n assets,\n warnings = []\n } = await FORMAT_HANDLERS[format](eng, bytes, fs);\n const written = await store.write({ scene, parent: null, title });\n session.commit(slot, written.id);\n // Thumbnail block mirrors edit.ts — duplication is deliberate (KISS).\n if (renderThumbnail) {\n try {\n const thumb = await renderThumbnail({\n revision: written.id,\n engine: slot.engine\n });\n const shard = written.id.slice(0, 2);\n const rest = written.id.slice(2);\n await fs.writeFile(\n `exports/${shard}/${rest}/preview.webp`,\n thumb\n );\n } catch {\n // best-effort; thumbnail failure must not poison the load\n }\n }\n if (onLeafWritten) {\n // A new root is its own lineage root.\n await onLeafWritten({\n revision: written.id,\n rootRevision: written.id\n });\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n revision: written.id,\n // store.write seeded a fresh root's title with exactly this\n // (store.ts) — no need to re-read it from disk.\n title: title ?? 'Untitled',\n format,\n ...(assets !== undefined ? { assets } : {}),\n ...(warnings.length > 0 ? { warnings } : {})\n })\n }\n ]\n };\n } catch (err) {\n session.markDirty(slot);\n return errorResult(\n `load: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`\n );\n }\n });\n }\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spa-assets.generated.d.ts","sourceRoot":"","sources":["../../src/viewer/spa-assets.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"spa-assets.generated.d.ts","sourceRoot":"","sources":["../../src/viewer/spa-assets.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAqgC7C,CAAC"}
|
|
@@ -313,7 +313,13 @@ if (!match) {
|
|
|
313
313
|
});
|
|
314
314
|
return;
|
|
315
315
|
}
|
|
316
|
-
|
|
316
|
+
// format: 1 = CompressionFormat.Zstd, level: 1 = CompressionLevel.Default —
|
|
317
|
+
// mirrors the server-side SCENE_COMPRESSION constant in
|
|
318
|
+
// src/engine/scene-compression.ts (this bundle can't import it directly;
|
|
319
|
+
// that module is the source of truth for the values).
|
|
320
|
+
const scene = await engine.scene.saveToString({
|
|
321
|
+
compression: { format: 1, level: 1 }
|
|
322
|
+
});
|
|
317
323
|
const res = await fetch(\`\${BASE}/api/design/\${root}/revisions\`, {
|
|
318
324
|
method: 'POST',
|
|
319
325
|
headers: { 'content-type': 'application/json' },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spa-assets.generated.js","sourceRoot":"","sources":["../../src/viewer/spa-assets.generated.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,UAAU,GAA2B;IACjD,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAm5Bb;IACA,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0Cd;IACA,kBAAkB,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8DpB;CACA,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-spa-assets.mjs. Do not edit by hand.\nexport const SPA_ASSETS: Record<string, string> = {\n\t\"editor.js\": `// The CoDesign editor — the single browser surface for a design (CODE-74).\n// /d/<root> LIVE — opens at the design head, follows new revisions\n// /d/<root>/<rev> PINNED — opens frozen at <rev>\n//\n// The canvas is FULLY EDITABLE from the start; the read-only viewer and the\n// detached \"Edit a copy\" tab are gone. Edits are LOCAL TO THE TAB: nothing\n// writes back to the workspace or notifies the agent — the export actions in\n// the navigation bar (archive / image / PDF) are the only way work leaves\n// this tab. While the tab is untouched, /d/<root> live-follows the head over\n// SSE; the FIRST local edit pauses following, pins the URL, and shows an\n// infinite \"not saved back\" warning (see the dirty tracking below).\n// See docs/specs/2026-07-10-merged-editor-design.md.\n//\n// CE.SDK ships NO default UI since v1.69: \\`create()\\` renders only the bare\n// canvas and every UI area starts EMPTY. The canonical design-editor UI is the\n// \\`DesignEditorConfig\\` plugin from \\`@cesdk/core-configs-web/design-editor\\`,\n// but that package is NOT published to npm or the CDN, so it can't be imported\n// in this bundler-less browser module that loads CE.SDK straight from the CDN.\n// \\`configureDesignEditorUI()\\` below therefore mirrors what \\`DesignEditorConfig\\`\n// does — the exact features, actions and component orders from IMG.LY's Design\n// Editor starter kit — via the public Order API, trimmed for this surface: the\n// asset-library dock IS present, with Text / Shapes / Stickers fed by CE.SDK's\n// default asset sources (no demo/stock media, no uploads); video/audio\n// features stay off (so a static design never shows a timeline).\n// See docs/specs/2026-07-07-codesign-detached-editor-design.md.\n\n// Mount prefix set by index.html (\"\" on stdio, \"/viewer\" on HTTP). See router.ts.\nconst BASE = window.__VIEWER_BASE__ ?? '';\n\nconst { order, relTime, fetchRevisions } = await import(\n \\`\\${BASE}/static/revision-data.js\\`\n);\n\nconst relPath = () =>\n location.pathname.startsWith(BASE)\n ? location.pathname.slice(BASE.length)\n : location.pathname;\n\nconst PATH_RE = /^\\\\/d\\\\/([0-9a-f]{12})(?:\\\\/([0-9a-f]{12}))?$/;\nconst statusEl = document.getElementById('status');\n\nconst HISTORY_PANEL = 'codesign.revisionHistory';\n\nconst match = relPath().match(PATH_RE);\n\nif (!match) {\n statusEl.textContent = 'invalid URL';\n} else {\n const root = match[1];\n\n // Server-supplied license + resource base + engine URL.\n const cfgRes = await fetch(\\`\\${BASE}/api/config\\`);\n if (!cfgRes.ok) throw new Error(\\`/api/config failed: \\${cfgRes.status}\\`);\n const {\n license,\n resourceBase,\n cesdkEngineUrl,\n cesdkAssetsUrl,\n defaultAssetsBaseUrl,\n gfontsContentUrl\n } = await cfgRes.json();\n\n const cesdkMod = await import(cesdkEngineUrl);\n const CreativeEditorSDK = cesdkMod.default ?? cesdkMod.CreativeEditorSDK;\n\n // UI icons/CSS (\\`ui.baseURL\\`) load from the cesdk-js CDN path we imported the\n // SDK from. Engine WASM/data (\\`baseURL\\`) load from cesdk-engine's own CDN\n // path (\\`cesdkAssetsUrl\\`) instead — the two packages' asset builds can drift\n // on the CDN, and cesdk-engine's own path is self-consistent with the bundle\n // that references it (see cesdk-cdn.ts).\n const uiAssetBase = cesdkEngineUrl.replace(/\\\\/index\\\\.js$/, '/assets');\n const cesdk = await CreativeEditorSDK.create(\n document.getElementById('cesdk'),\n {\n license,\n baseURL: cesdkAssetsUrl,\n ui: { baseURL: uiAssetBase + '/ui/' },\n theme: 'dark'\n }\n );\n const engine = cesdk.engine;\n\n configureDesignEditorUI(cesdk);\n\n // Register CE.SDK's DEFAULT asset sources — shapes, stickers, typefaces,\n // color palettes, LUT filters/effects, page & crop presets — never the\n // demo ones (no stock images/videos/audio). The manifest base URL comes\n // from /api/config so the browser and the headless engine resolve the\n // same manifests (IMGLY_DEFAULT_ASSETS_BASE_URL-aware). \\`ly.img.text\\` is\n // excluded exactly like the node side (its manifest is missing from the\n // CDN manifest root and one 404 rejects the whole call). Page presets\n // ride along here — the former page-presets plugin registered the same\n // source id and the two cannot coexist (colliding registrations reject\n // the whole call), so the plugin is gone; the \\`ly.img.pagePresets\\` LIBRARY\n // ENTRY the Resize Page panel reads is wired in configureDesignEditorUI.\n // Best-effort and isolated in its own try/catch: a down/misconfigured\n // IMGLY_DEFAULT_ASSETS_BASE_URL leaves the editor usable with an empty\n // shapes/stickers/typefaces/LUT-filters/presets library, and must NOT take\n // down the engine-CDN sources registered below (different host, see that\n // block's comment).\n try {\n await cesdk.addDefaultAssetSources({\n baseURL: defaultAssetsBaseUrl,\n excludeAssetSourceIds: ['ly.img.text']\n });\n } catch (err) {\n console.error(\n 'codesign: asset-source registration failed — asset library will be empty',\n err\n );\n }\n\n // The engine-assets manifests below cover what the default manifest root\n // does NOT carry (each 404s under <defaultAssetsBaseUrl>/<id>/content.json\n // but is published under <engine>/assets/<id>/content.json, where the CDN\n // plugins bundle used to load them from):\n // - the stock \\`ly.img.text\\` library entry queries the four text sources —\n // with none registered the Text dock panel shows \"No Elements\";\n // - the appearance Filter panel hard-queries the combined \\`ly.img.filter\\`\n // source (not filter.lut/filter.duotone) and shows an infinite spinner\n // while that id is unregistered;\n // - the stock Shapes entry titles its group headers with\n // \\`libraries.ly.img.vector.shape.<group>.label\\`, and the UI bundle only\n // ships translations for THIS source's groups (filled/outline/gradient/\n // image/abstract-*) — the default root's vectorpath source has verbose\n // category group ids that render as raw i18n keys.\n // These six are registered in parallel via Promise.allSettled, each\n // isolated from the others' failures — one 404 must not take out the rest\n // of the library. This block runs UNCONDITIONALLY, regardless of whether\n // addDefaultAssetSources above succeeded: the two target different hosts —\n // a down/misconfigured IMGLY_DEFAULT_ASSETS_BASE_URL must not blank the\n // Text/Filter panels whose manifests come from the (independent) engine\n // CDN. No try/catch needed here: Promise.allSettled never rejects.\n const engineAssetSourceIds = [\n 'ly.img.text',\n 'ly.img.text.styles',\n 'ly.img.text.components',\n 'ly.img.text.curves',\n 'ly.img.filter',\n 'ly.img.vector.shape'\n ];\n const results = await Promise.allSettled(\n engineAssetSourceIds.map((id) =>\n engine.asset.addLocalAssetSourceFromJSONURI(\n \\`\\${cesdkAssetsUrl}/\\${id}/content.json\\`\n )\n )\n );\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n console.error(\n 'codesign: failed to register asset source',\n engineAssetSourceIds[index],\n result.reason\n );\n }\n });\n\n // Google Fonts (ly.img.gfonts) — the same self-hosted catalog the headless\n // engine registers, URL via /api/config so both sides stay in sync.\n // Best-effort in its own try/catch: a CDN failure must not take down the\n // editor — the font picker just falls back to the stock typefaces.\n try {\n await engine.asset.addLocalAssetSourceFromJSONURI(gfontsContentUrl);\n } catch (err) {\n console.error('codesign: Google Fonts source registration failed', err);\n }\n\n // Resolve workspace:// asset URIs to the /r/ HTTP route.\n const absResourceBase = location.origin + resourceBase;\n engine.editor.setURIResolver((uri, defaultResolver) =>\n uri.startsWith('workspace://')\n ? absResourceBase + uri.slice('workspace://'.length)\n : defaultResolver(uri)\n );\n\n // --- runtime state ----------------------------------------------------\n let head = null; // the design's latest leaf\n let currentRev = null; // the revision currently on canvas\n let following = false; // true → the canvas tracks head as SSE arrives\n let dirty = false; // true → a local edit happened since the last load\n let loading = false; // true while show() swaps the scene programmatically\n let warnNotification = null; // id of the \"not saved back\" notification\n let newCount = 0; // revisions arrived since following stopped\n let orderedRevisions = []; // order(fetchRevisions(...)) — drives the panel\n let saving = false; // save-back POST in flight\n\n // --- CE.SDK re-render bridge ------------------------------------------\n // Builder components re-render when a state() value they read changes. Our\n // editor state lives in the plain variables above, which CE.SDK's reactor\n // can't see, so each reactive component reads a monotonic \\`uiVersion\\` from\n // state() purely to subscribe, and invalidateUI() bumps every mounted\n // component to force a coherent re-read. The title, too, is bridged — CE.SDK's\n // builder components don't re-render on engine name changes alone (see\n // codesign.title below). Calls are wrapped because a component that has\n // since unmounted (e.g. a closed panel) throws on setValue.\n let uiVersion = 0;\n const bump = new Map(); // componentKey -> setValue, refreshed on each render\n function invalidateUI() {\n uiVersion += 1;\n for (const setVersion of bump.values()) {\n try {\n setVersion(uiVersion);\n } catch {\n /* component unmounted — ignore */\n }\n }\n }\n\n // Subscribe a component to invalidateUI(). Reading \\`version.value\\` (not just\n // grabbing setValue) is what registers the reactive dependency — CE.SDK only\n // re-renders a component when a state value it *read* during render changes,\n // so invalidateUI()'s setValue bumps are no-ops unless the value was read.\n function subscribeToUI(state, key) {\n const version = state('v', 0);\n bump.set(key, version.setValue);\n return version.value;\n }\n\n async function loadRevision(rev) {\n const res = await fetch(\\`\\${BASE}/snapshot/\\${rev}\\`);\n if (!res.ok) throw new Error(\\`snapshot \\${rev} \\${res.status}\\`);\n const snap = await res.json();\n await engine.scene.loadFromString(snap.scene);\n // Feed the nav-bar title component via engine reactivity.\n const scene = engine.scene.get();\n if (scene != null) engine.block.setName(scene, snap.title ?? 'Untitled');\n // Fit the page in the viewport and keep it fitted on resize.\n const page = engine.block.findByType('page')[0];\n if (page != null)\n engine.scene.enableZoomAutoFit(page, 'Both', 40, 40, 40, 40);\n }\n\n // The single navigation primitive. Loads \\`rev\\`, sets LIVE/PINNED, writes the\n // URL. historyMode: \"push\" adds a history entry, \"replace\" rewrites in place,\n // \"none\" leaves history alone (popstate already changed the URL).\n // Every arrival here is a fresh scene: it clears \\`dirty\\` and dismisses the\n // warning. Callers navigating away from local edits must confirmDiscard()\n // FIRST — show() itself never asks.\n async function show(rev, { following: nextFollowing, historyMode }) {\n try {\n // Clear any prior error banner so a later successful load self-heals it.\n statusEl.textContent = '';\n loading = true;\n try {\n await loadRevision(rev);\n } finally {\n loading = false;\n }\n if (dirty) {\n dirty = false;\n dismissEditWarning();\n }\n currentRev = rev;\n following = nextFollowing;\n if (following) newCount = 0;\n const url = following ? \\`\\${BASE}/d/\\${root}\\` : \\`\\${BASE}/d/\\${root}/\\${rev}\\`;\n if (historyMode === 'push') window.history.pushState({ rev }, '', url);\n else if (historyMode === 'replace')\n window.history.replaceState({ rev }, '', url);\n } catch {\n statusEl.textContent = 'unknown revision';\n }\n invalidateUI();\n }\n\n async function refreshRevisions() {\n try {\n orderedRevisions = order(await fetchRevisions(BASE, root));\n } catch {\n orderedRevisions = [];\n }\n invalidateUI();\n }\n\n // --- dirty tracking -----------------------------------------------------\n // The first REAL local edit detaches the tab from live-follow: edits are\n // local-only (no write path back to the workspace), so the canvas must stop\n // being swapped out underneath them. 'Updated' events during a programmatic\n // load (loading === true) and the post-load baseline (canUndo() === false)\n // are not edits. Undoing back to the baseline does NOT clear \\`dirty\\` — once\n // touched, the tab stays detached until explicit navigation via show().\n function dismissEditWarning() {\n if (warnNotification == null) return;\n try {\n cesdk.ui.dismissNotification?.(warnNotification);\n } catch {\n /* notification already gone — ignore */\n }\n warnNotification = null;\n }\n\n // Save the tab's scene back to the workspace as a child revision of\n // currentRev (CODE-111). On success the canvas already IS the new head:\n // advance pointers and resume following WITHOUT reloading — a reload would\n // wipe the user's undo stack.\n async function saveBack() {\n if (saving || currentRev == null) return;\n const divergedHead = head != null && head !== currentRev ? head : null;\n saving = true;\n invalidateUI();\n try {\n // Pasted media lives only in this tab's engine (buffer:// resources);\n // saveToString would persist dangling references. Refuse loudly.\n const transient = engine.editor.findAllTransientResources?.() ?? [];\n if (transient.length > 0) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n 'This design contains pasted media that only exists in this tab — remove it or use Export; saving it back is not supported yet.'\n });\n return;\n }\n const scene = await engine.scene.saveToString();\n const res = await fetch(\\`\\${BASE}/api/design/\\${root}/revisions\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ parent: currentRev, scene })\n });\n if (!res.ok) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n res.status === 422\n ? 'Saving failed: the scene could not be read back. Your edits stay in this tab.'\n : res.status === 503\n ? 'Saving failed: the design engine is busy — try again in a moment. Your edits stay in this tab.'\n : \\`Saving failed (\\${res.status}). Your edits stay in this tab.\\`\n });\n return;\n }\n const body = await res.json();\n if (body.noop && head != null && head !== body.revision) {\n // Diverged no-op save while the design moved on (the assistant\n // committed meanwhile): nothing was written — keep the tab detached\n // so \"Revert to Synced\" still points at the newer head, and keep \\`head\\` intact.\n dirty = false;\n dismissEditWarning();\n cesdk.ui.showNotification({\n type: 'success',\n message:\n 'Nothing new to save — the design has newer revisions; use Revert to Synced to see them.'\n });\n return;\n }\n // Either a real save (201) or a non-diverged no-op (200, nothing\n // written but the tab already matches the saved revision) — both\n // resume following/unpin the same way; only the message tells the\n // truth about whether anything was actually written.\n currentRev = body.revision;\n head = body.revision;\n newCount = 0;\n dirty = false;\n dismissEditWarning();\n following = true;\n window.history.replaceState({ rev: null }, '', \\`\\${BASE}/d/\\${root}\\`);\n refreshRevisions();\n cesdk.ui.showNotification({\n type: 'success',\n message: body.noop\n ? 'Nothing new to save — everything already matches the saved revision.'\n : divergedHead\n ? 'Saved as a parallel version — the assistant also changed this design while you were editing.'\n : 'Saved — the assistant can now see your changes.'\n });\n } catch (err) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n 'Saving failed: could not reach the local server. Your edits stay in this tab.'\n });\n } finally {\n saving = false;\n invalidateUI();\n }\n }\n\n engine.editor.onHistoryUpdatedWithKind((kind) => {\n if (kind !== 'Updated' || loading || dirty) return;\n if (!engine.editor.canUndo()) return;\n dirty = true;\n following = false;\n // The URL mirrors following-state everywhere else (LIVE = /d/<root>,\n // PINNED = /d/<root>/<rev>); a detached-by-edit tab is pinned.\n if (currentRev != null)\n window.history.replaceState(\n { rev: currentRev },\n '',\n \\`\\${BASE}/d/\\${root}/\\${currentRev}\\`\n );\n warnNotification = cesdk.ui.showNotification({\n type: 'warning',\n duration: 'infinite',\n message:\n \"Unsaved edits — click 'Save for Agent' to share them with the assistant.\"\n });\n invalidateUI();\n });\n\n // Local edits are throwaway: every navigation that would replace the scene\n // asks before discarding them.\n function confirmDiscard() {\n return (\n !dirty ||\n window.confirm(\n 'Discard your local edits? They are not saved back to the workspace.'\n )\n );\n }\n\n // Closing the tab with unexported local edits prompts (browsers show their\n // own generic message; preventDefault is what arms it).\n window.addEventListener('beforeunload', (ev) => {\n if (!dirty) return;\n ev.preventDefault();\n ev.returnValue = '';\n });\n\n // --- nav bar components ------------------------------------------------\n installCodesignChrome();\n\n function installCodesignChrome() {\n // Panel title (registered here so the toggle's target exists and the i18n\n // title is set once; the toggle itself is hidden for now).\n cesdk.i18n.setTranslations({\n en: { [\\`panel.\\${HISTORY_PANEL}\\`]: 'Revisions' }\n });\n\n // Live-follow status: \"Synced\" while following; \"Revert to Synced\"\n // (+ unseen count) when pinned or detached by a local edit. Reads module\n // state → bridged via the version bump.\n cesdk.ui.registerComponent('codesign.liveStatus', ({ builder, state }) => {\n subscribeToUI(state, 'liveStatus');\n if (following) {\n builder.Button('codesign.liveStatus.live', {\n label: 'Synced',\n icon: '@imgly/FileCheck',\n variant: 'plain',\n isDisabled: true\n });\n } else {\n builder.Button('codesign.liveStatus.goLive', {\n label:\n newCount > 0\n ? \\`Revert to Synced (\\${newCount})\\`\n : 'Revert to Synced',\n icon: '@imgly/FileImport',\n variant: 'plain',\n onClick: () => {\n if (head && confirmDiscard())\n show(head, { following: true, historyMode: 'push' });\n }\n });\n }\n });\n\n // Save-back button: always visible, actionable only while the tab holds\n // unsaved edits (grayed out when there is nothing to save).\n cesdk.ui.registerComponent('codesign.saveBack', ({ builder, state }) => {\n subscribeToUI(state, 'saveBack');\n builder.Button('codesign.saveBack.button', {\n label: saving ? 'Saving…' : 'Save for Agent',\n icon: '@imgly/Save',\n color: 'accent',\n isDisabled: saving || !dirty,\n onClick: () => void saveBack()\n });\n });\n\n // Document title. The built-in \\`ly.img.title.navigationBar\\` does NOT read\n // engine.block.getName() reactively — it only renders a static string\n // passed via \\`ui.elements.navigation.title\\` at create() time or a\n // per-instance \\`payload.title\\` in the order array (neither of which we\n // set), so it never renders anything here. Read the scene name ourselves\n // instead, bridged through the same state()/invalidateUI() mechanism as\n // codesign.liveStatus so it refreshes on every show(). Refreshes on\n // invalidateUI() bumps; a rename via document settings while the tab is\n // already dirty stays stale until the next bump — accepted cosmetic\n // staleness.\n cesdk.ui.registerComponent('codesign.title', ({ builder, state }) => {\n subscribeToUI(state, 'title');\n const scene = engine.scene.get();\n const title = scene != null ? engine.block.getName(scene) : '';\n if (title) builder.Heading('codesign.title.heading', { content: title });\n });\n\n // History toggle. isActive rides CE.SDK's own reactive panel-open state.\n cesdk.ui.registerComponent('codesign.historyToggle', ({ builder }) => {\n const open = cesdk.ui.isPanelOpen(HISTORY_PANEL);\n builder.Button('codesign.historyToggle.button', {\n label: 'History',\n isActive: open,\n onClick: () =>\n open\n ? cesdk.ui.closePanel(HISTORY_PANEL)\n : cesdk.ui.openPanel(HISTORY_PANEL, {\n position: 'right',\n floating: true\n })\n });\n });\n\n // Revision history — native builder panel. Reuses revision-data.js's order()\n // output; reads module state → bridged via the version bump. Rows are\n // buttons: indent = depth, label = short id · note · time (+ head/root/fork).\n cesdk.ui.registerPanel(HISTORY_PANEL, ({ builder, state }) => {\n subscribeToUI(state, 'historyPanel');\n builder.Section('codesign.history.section', {\n title: following ? 'Revisions · SYNCED' : 'Revisions · PINNED',\n children: () => {\n if (orderedRevisions.length === 0) {\n builder.Text('codesign.history.empty', {\n content: 'No revisions yet'\n });\n return;\n }\n for (const { node, depth, isHead, isRoot } of orderedRevisions) {\n const indent = depth > 0 ? ' '.repeat(depth) + '↳ ' : '';\n const marker = isHead\n ? ' · head'\n : isRoot\n ? ' · root'\n : depth > 0\n ? ' · fork'\n : '';\n const note = node.note ? \\` · \\${node.note}\\` : '';\n builder.Button(\\`codesign.history.\\${node.id}\\`, {\n label: \\`\\${indent}\\${node.id.slice(0, 7)}\\${note}\\${marker} · \\${relTime(node.createdAt)}\\`,\n variant: 'plain',\n isActive: node.id === currentRev,\n onClick: () => {\n if (!confirmDiscard()) return;\n show(node.id, {\n following: node.id === head,\n historyMode: 'push'\n });\n }\n });\n }\n }\n });\n });\n\n // Final navigation bar: the design-editor chrome (document settings,\n // undo/redo, title, zoom, preview) plus the live-follow status. This\n // REPLACES the order configureDesignEditorUI set, so the export dropdown\n // must be (re-)inserted after it.\n cesdk.ui.setComponentOrder({ in: 'ly.img.navigation.bar' }, [\n 'ly.img.documentSettings.navigationBar',\n 'ly.img.undoRedo.navigationBar',\n 'ly.img.spacer',\n 'codesign.title',\n 'ly.img.spacer',\n 'codesign.liveStatus',\n 'codesign.saveBack',\n 'ly.img.zoom.navigationBar',\n 'ly.img.preview.navigationBar'\n // 'codesign.historyToggle' — hidden for now; the panel + refreshRevisions\n // machinery stays wired, so re-add this line to bring History back.\n ]);\n\n // Export dropdown. The scene references workspace:// assets, so exporting\n // the bare scene (or \"Save\") would produce broken links — the self-contained\n // archive (.zip, assets embedded) is the default/prominent action, with\n // image and PDF in the overflow. Each child carries an explicit handler\n // that ends in a browser download — the only way work leaves this tab.\n cesdk.ui.insertOrderComponent(\n { in: 'ly.img.navigation.bar', position: 'end' },\n {\n id: 'ly.img.actions.navigationBar',\n children: [\n {\n id: 'ly.img.exportArchive.navigationBar',\n onClick: async () => {\n const archive = await engine.scene.saveToArchive();\n await cesdk.utils.downloadFile(archive, 'application/zip');\n }\n },\n {\n id: 'ly.img.exportImage.navigationBar',\n onClick: async () => {\n const { blobs, options } = await cesdk.utils.export({\n mimeType: 'image/png'\n });\n await cesdk.utils.downloadFile(blobs[0], options.mimeType);\n }\n },\n {\n id: 'ly.img.exportPDF.navigationBar',\n onClick: async () => {\n const { blobs, options } = await cesdk.utils.export({\n mimeType: 'application/pdf'\n });\n await cesdk.utils.downloadFile(blobs[0], options.mimeType);\n }\n }\n ]\n }\n );\n }\n\n // --- bootstrap --------------------------------------------------------\n let latestLeaf;\n try {\n const res = await fetch(\\`\\${BASE}/api/design/\\${root}\\`);\n if (!res.ok) throw new Error(String(res.status));\n latestLeaf = (await res.json()).latestLeaf;\n } catch {\n statusEl.textContent = 'unknown design';\n }\n\n if (latestLeaf !== undefined) {\n head = latestLeaf;\n const pinned = match[2]; // undefined → LIVE\n await show(pinned ?? head, {\n following: pinned === undefined,\n historyMode: 'replace'\n });\n await refreshRevisions();\n\n // SSE — held open for the tab's life, in every state. It moves the canvas\n // only while following (a dirty tab is never following).\n const es = new EventSource(\\`\\${BASE}/sse/\\${root}\\`);\n es.onmessage = (ev) => {\n let payload;\n try {\n payload = JSON.parse(ev.data);\n } catch (err) {\n console.error('sse parse failed', err);\n return;\n }\n if (!payload || typeof payload.revision !== 'string') return;\n head = payload.revision;\n refreshRevisions();\n if (payload.revision === currentRev) {\n // Our own save-back landing (or any echo of the state already on\n // canvas) — reloading it would wipe the undo stack.\n invalidateUI();\n return;\n }\n if (following) {\n show(head, { following: true, historyMode: 'replace' });\n } else {\n newCount += 1;\n invalidateUI();\n }\n };\n }\n\n // Browser back/forward: re-resolve the URL shape and sync, without writing\n // history (the entry already changed). With unexported local edits, ask\n // first — on cancel, restore the URL of the revision still on canvas.\n window.addEventListener('popstate', () => {\n const m = relPath().match(PATH_RE);\n if (!m || m[1] !== root) return;\n if (!confirmDiscard()) {\n const url = following\n ? \\`\\${BASE}/d/\\${root}\\`\n : \\`\\${BASE}/d/\\${root}/\\${currentRev}\\`;\n window.history.pushState({ rev: currentRev }, '', url);\n return;\n }\n const pinned = m[2];\n show(pinned ?? head, {\n following: pinned === undefined,\n historyMode: 'none'\n });\n });\n}\n\n// Install the design-editor UI. This mirrors IMG.LY's \\`DesignEditorConfig\\`\n// plugin (features → actions → component orders), which we can't import here\n// (see the file header), reproduced verbatim from the Design Editor starter kit\n// and trimmed for this surface:\n// - the dock / asset library IS enabled (features \\`ly.img.dock\\`,\n// \\`ly.img.library.panel\\`) with a Text / Shapes / Stickers dock order set\n// below, fed by the default asset sources registered in the boot code;\n// - no video/audio features enabled (so a static design has no timeline);\n// - the Trim and Vector inspector edit modes are omitted because their\n// features (video trimming, vector-path editing) aren't enabled here, so\n// those modes are unreachable;\n// - the Document inspector's \"Resize Page\" panel is fed by the\n// \\`ly.img.pagePresets\\` entry wired below to the page-presets source that\n// rides along with the default asset sources (see the boot code);\n// - the navigation-bar order + export dropdown live in\n// installCodesignChrome() (they include codesign components registered\n// after the resetEditor() below).\nfunction configureDesignEditorUI(cesdk) {\n // Clear the empty default configuration, then apply ours. \\`resetEditor()\\` can\n // drop the theme passed to \\`create()\\`, so re-apply it.\n cesdk.resetEditor();\n cesdk.ui.setTheme('dark');\n\n // --- Features (starter-kit design set, plus the dock/library) -------------\n cesdk.feature.enable([\n 'ly.img.navigation',\n 'ly.img.dock',\n 'ly.img.library.panel',\n 'ly.img.text',\n 'ly.img.crop',\n 'ly.img.transform',\n 'ly.img.filter',\n 'ly.img.adjustment',\n 'ly.img.effect',\n 'ly.img.blur',\n 'ly.img.shadow',\n 'ly.img.cutout',\n 'ly.img.canvas',\n 'ly.img.inspector',\n 'ly.img.inspector.bar',\n 'ly.img.inspector.toggle',\n 'ly.img.delete',\n 'ly.img.duplicate',\n 'ly.img.group',\n 'ly.img.replace',\n 'ly.img.page',\n 'ly.img.scene.layout',\n 'ly.img.fill.color',\n 'ly.img.fill.image',\n 'ly.img.stroke',\n 'ly.img.opacity',\n 'ly.img.blendMode',\n 'ly.img.shape.options',\n 'ly.img.combine',\n 'ly.img.position',\n 'ly.img.trim',\n 'ly.img.notifications',\n 'ly.img.keyboard.shortcuts'\n ]);\n\n // --- Panels: inspector docked on the left, pushing the canvas -------------\n cesdk.ui.setPanelPosition('//ly.img.panel/inspector', 'left');\n cesdk.ui.setPanelFloating('//ly.img.panel/inspector', false);\n\n // --- Dock: asset library with Text / Shapes / Stickers --------------------\n // The stock \\`ly.img.vector.shape\\` and \\`ly.img.sticker\\` entries ship with\n // EMPTY sourceIds — wire them explicitly (no reliance on hidden\n // auto-population). Shapes points at the engine-CDN \\`ly.img.vector.shape\\`\n // source registered in the boot code — NOT the default root's vectorpath\n // source, whose group ids have no shipped translations and render as raw\n // i18n keys in the panel's section headers. Stickers uses the source\n // addDefaultAssetSources registers; the \\`ly.img.text\\` entry keeps its stock\n // sources. No image/video/audio/upload entries: the library carries only\n // the neutral defaults, no demo content.\n cesdk.ui.updateAssetLibraryEntry('ly.img.vector.shape', {\n sourceIds: ['ly.img.vector.shape']\n });\n cesdk.ui.updateAssetLibraryEntry('ly.img.sticker', {\n sourceIds: ['ly.img.sticker']\n });\n // The Document inspector's \"Resize Page\" panel lists the formats of the\n // sources named by the \\`ly.img.pagePresets\\` entry (note: entry id, NOT the\n // \\`ly.img.page.presets\\` source id) — it also ships with EMPTY sourceIds,\n // which left the panel body blank. The source itself is registered by\n // addDefaultAssetSources in the boot code.\n cesdk.ui.updateAssetLibraryEntry('ly.img.pagePresets', {\n sourceIds: ['ly.img.page.presets']\n });\n // The text inspector's font picker reads the \\`ly.img.typefaces\\` (PLURAL)\n // library entry — not to be confused with the \\`ly.img.typeface\\` (singular)\n // stock asset SOURCE id it already lists in its sourceIds. Unlike the\n // neighboring \\`ly.img.vector.shape\\` / \\`ly.img.sticker\\` / \\`ly.img.pagePresets\\`\n // patches above (justified because those entries ship EMPTY sourceIds),\n // \\`ly.img.typefaces\\` already lists the stock source — so we APPEND the\n // Google Fonts source (registered in the boot code) to whatever the entry\n // already has, rather than overwriting it, so the picker lists gfonts\n // families alongside the stock set instead of replacing it. Assert the\n // entry exists — if CE.SDK renames it we want a loud warning, not a\n // silently stock-only font list.\n const typefaceEntry = cesdk.ui.getAssetLibraryEntry('ly.img.typefaces');\n if (typefaceEntry) {\n cesdk.ui.updateAssetLibraryEntry('ly.img.typefaces', {\n sourceIds: [\n ...new Set([...(typefaceEntry.sourceIds ?? []), 'ly.img.gfonts'])\n ]\n });\n // Give the gfonts group a human label instead of the raw source id\n // header in the panel.\n cesdk.i18n.setTranslations({\n en: { 'libraries.ly.img.gfonts.label': 'Google Fonts' }\n });\n } else {\n console.warn(\n 'codesign: ly.img.typefaces library entry missing — Google Fonts hidden in the font picker'\n );\n }\n cesdk.ui.setComponentOrder({ in: 'ly.img.dock' }, [\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'text',\n label: 'libraries.ly.img.text.label',\n icon: '@imgly/Text',\n entries: ['ly.img.text']\n },\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'shapes',\n label: 'libraries.ly.img.vector.shape.label',\n icon: '@imgly/Shapes',\n entries: ['ly.img.vector.shape']\n },\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'stickers',\n label: 'libraries.ly.img.sticker.label',\n icon: '@imgly/Sticker',\n entries: ['ly.img.sticker']\n }\n ]);\n\n // --- Inspector bar — contextual controls for the selected block -----------\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.inspector.bar', when: { editMode: 'Transform' } },\n [\n 'ly.img.spacer',\n 'ly.img.pageResize.inspectorBar',\n 'ly.img.separator',\n 'ly.img.video.caption.inspectorBar',\n 'ly.img.shape.options.inspectorBar',\n 'ly.img.cutout.type.inspectorBar',\n 'ly.img.cutout.offset.inspectorBar',\n 'ly.img.cutout.smoothing.inspectorBar',\n 'ly.img.group.create.inspectorBar',\n 'ly.img.group.ungroup.inspectorBar',\n 'ly.img.audio.replace.inspectorBar',\n 'ly.img.separator',\n 'ly.img.text.typeFace.inspectorBar',\n 'ly.img.text.bold.inspectorBar',\n 'ly.img.text.italic.inspectorBar',\n 'ly.img.text.fontSize.inspectorBar',\n 'ly.img.text.alignHorizontal.inspectorBar',\n 'ly.img.text.advanced.inspectorBar',\n 'ly.img.combine.inspectorBar',\n 'ly.img.separator',\n 'ly.img.fill.inspectorBar',\n 'ly.img.trim.inspectorBar',\n 'ly.img.volume.inspectorBar',\n 'ly.img.crop.inspectorBar',\n 'ly.img.separator',\n 'ly.img.stroke.inspectorBar',\n 'ly.img.separator',\n 'ly.img.text.background.inspectorBar',\n 'ly.img.separator',\n 'ly.img.animations.inspectorBar',\n 'ly.img.separator',\n {\n id: 'ly.img.appearance.inspectorBar',\n children: [\n 'ly.img.adjustment.inspectorBar',\n 'ly.img.filter.inspectorBar',\n 'ly.img.effect.inspectorBar',\n 'ly.img.blur.inspectorBar'\n ]\n },\n 'ly.img.separator',\n 'ly.img.shadow.inspectorBar',\n 'ly.img.separator',\n 'ly.img.opacityOptions.inspectorBar',\n 'ly.img.separator',\n 'ly.img.position.inspectorBar',\n 'ly.img.spacer',\n 'ly.img.separator',\n 'ly.img.inspectorToggle.inspectorBar'\n ]\n );\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.inspector.bar', when: { editMode: 'Crop' } },\n ['ly.img.cropControls.inspectorBar']\n );\n\n // --- Canvas bar (bottom) and the selection context menu -------------------\n cesdk.ui.setComponentOrder({ in: 'ly.img.canvas.bar', at: 'bottom' }, [\n 'ly.img.settings.canvasBar',\n 'ly.img.spacer',\n 'ly.img.page.add.canvasBar',\n 'ly.img.spacer'\n ]);\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.canvas.menu', when: { editMode: 'Transform' } },\n [\n 'ly.img.group.enter.canvasMenu',\n 'ly.img.group.select.canvasMenu',\n 'ly.img.page.moveUp.canvasMenu',\n 'ly.img.page.moveDown.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.edit.canvasMenu',\n 'ly.img.text.styles.canvasMenu',\n 'ly.img.replace.canvasMenu',\n 'ly.img.separator',\n 'ly.img.bringForward.canvasMenu',\n 'ly.img.sendBackward.canvasMenu',\n 'ly.img.separator',\n 'ly.img.duplicate.canvasMenu',\n 'ly.img.delete.canvasMenu',\n 'ly.img.separator',\n 'ly.img.options.canvasMenu'\n ]\n );\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.canvas.menu', when: { editMode: 'Text' } },\n [\n 'ly.img.text.color.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.bold.canvasMenu',\n 'ly.img.text.italic.canvasMenu',\n 'ly.img.text.underline.canvasMenu',\n 'ly.img.text.strikethrough.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.list.unordered.canvasMenu',\n 'ly.img.text.list.ordered.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.variables.canvasMenu'\n ]\n );\n}\n`,\n\t\"index.html\": `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>CoDesign</title>\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <!-- Mount prefix injected by the viewer router (router.ts). \"\" on the stdio\n listener, \"/viewer\" on the HTTP transport. Read by editor.js. -->\n <script>\n window.__VIEWER_BASE__ = '{{VIEWER_BASE}}';\n </script>\n <style>\n html,\n body {\n margin: 0;\n height: 100%;\n background: #1d1d1f;\n color: #eee;\n font-family: -apple-system, system-ui, sans-serif;\n }\n #cesdk {\n position: fixed;\n inset: 0;\n }\n #status {\n position: fixed;\n top: 14px;\n left: 14px;\n z-index: 10;\n font:\n 500 12px -apple-system,\n system-ui,\n sans-serif;\n }\n </style>\n </head>\n <body>\n <div id=\"cesdk\"></div>\n <div id=\"status\"></div>\n <script type=\"module\" src=\"{{VIEWER_BASE}}/static/editor.js\"></script>\n </body>\n</html>\n`,\n\t\"revision-data.js\": `// revision-data.js — framework-free data layer for the editor's revision\n// history. No DOM and no top-level \\`window\\` access, so order()/relTime() are\n// unit-testable under node. Consumed by editor.js's CE.SDK history panel.\n\n// Relative time label (\"5m ago\"). Uses Date.now() at call time (browser + node).\nexport function relTime(ms) {\n const s = Math.max(0, Math.round((Date.now() - ms) / 1000));\n if (s < 60) return \\`\\${s}s ago\\`;\n const m = Math.round(s / 60);\n if (m < 60) return \\`\\${m}m ago\\`;\n const h = Math.round(m / 60);\n if (h < 24) return \\`\\${h}h ago\\`;\n return \\`\\${Math.round(h / 24)}d ago\\`;\n}\n\n// Depth-first walk. At each node the spine child (or, off-spine, the latest\n// child) continues at the same depth; other children are branches at depth + 1,\n// emitted before the continuation so the spine reads top-to-bottom. Returns\n// [{ node, depth, isHead, isRoot }]. Pure — no DOM, no globals.\nexport function order(nodes) {\n if (nodes.length === 0) return [];\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const children = new Map();\n for (const n of nodes) {\n if (n.parent != null) {\n const sibs = children.get(n.parent) ?? [];\n sibs.push(n);\n children.set(n.parent, sibs);\n }\n }\n for (const sibs of children.values())\n sibs.sort((a, b) => a.createdAt - b.createdAt);\n const rootNode = nodes.find((n) => n.parent === null);\n const head = nodes.reduce((a, b) => (b.createdAt > a.createdAt ? b : a));\n const spine = new Set();\n for (let n = head; n; n = n.parent != null ? byId.get(n.parent) : null)\n spine.add(n.id);\n const out = [];\n function walk(node, depth) {\n out.push({\n node,\n depth,\n isHead: node.id === head.id,\n isRoot: node.parent === null\n });\n const kids = children.get(node.id) ?? [];\n if (kids.length === 0) return;\n const primary = kids.find((k) => spine.has(k.id)) ?? kids[kids.length - 1];\n for (const k of kids) if (k !== primary) walk(k, depth + 1);\n walk(primary, depth);\n }\n if (rootNode) walk(rootNode, 0);\n return out;\n}\n\n// Fetch a design's full revision tree. \\`base\\` is the mount prefix (\"\" on stdio,\n// \"/viewer\" on HTTP). Throws on a non-2xx response so the caller can degrade.\nexport async function fetchRevisions(base, root) {\n const res = await fetch(\\`\\${base}/api/design/\\${root}/revisions\\`);\n if (!res.ok) throw new Error(\\`revisions \\${root} \\${res.status}\\`);\n return res.json();\n}\n`,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"spa-assets.generated.js","sourceRoot":"","sources":["../../src/viewer/spa-assets.generated.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,UAAU,GAA2B;IACjD,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAy5Bb;IACA,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0Cd;IACA,kBAAkB,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8DpB;CACA,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-spa-assets.mjs. Do not edit by hand.\nexport const SPA_ASSETS: Record<string, string> = {\n\t\"editor.js\": `// The CoDesign editor — the single browser surface for a design (CODE-74).\n// /d/<root> LIVE — opens at the design head, follows new revisions\n// /d/<root>/<rev> PINNED — opens frozen at <rev>\n//\n// The canvas is FULLY EDITABLE from the start; the read-only viewer and the\n// detached \"Edit a copy\" tab are gone. Edits are LOCAL TO THE TAB: nothing\n// writes back to the workspace or notifies the agent — the export actions in\n// the navigation bar (archive / image / PDF) are the only way work leaves\n// this tab. While the tab is untouched, /d/<root> live-follows the head over\n// SSE; the FIRST local edit pauses following, pins the URL, and shows an\n// infinite \"not saved back\" warning (see the dirty tracking below).\n// See docs/specs/2026-07-10-merged-editor-design.md.\n//\n// CE.SDK ships NO default UI since v1.69: \\`create()\\` renders only the bare\n// canvas and every UI area starts EMPTY. The canonical design-editor UI is the\n// \\`DesignEditorConfig\\` plugin from \\`@cesdk/core-configs-web/design-editor\\`,\n// but that package is NOT published to npm or the CDN, so it can't be imported\n// in this bundler-less browser module that loads CE.SDK straight from the CDN.\n// \\`configureDesignEditorUI()\\` below therefore mirrors what \\`DesignEditorConfig\\`\n// does — the exact features, actions and component orders from IMG.LY's Design\n// Editor starter kit — via the public Order API, trimmed for this surface: the\n// asset-library dock IS present, with Text / Shapes / Stickers fed by CE.SDK's\n// default asset sources (no demo/stock media, no uploads); video/audio\n// features stay off (so a static design never shows a timeline).\n// See docs/specs/2026-07-07-codesign-detached-editor-design.md.\n\n// Mount prefix set by index.html (\"\" on stdio, \"/viewer\" on HTTP). See router.ts.\nconst BASE = window.__VIEWER_BASE__ ?? '';\n\nconst { order, relTime, fetchRevisions } = await import(\n \\`\\${BASE}/static/revision-data.js\\`\n);\n\nconst relPath = () =>\n location.pathname.startsWith(BASE)\n ? location.pathname.slice(BASE.length)\n : location.pathname;\n\nconst PATH_RE = /^\\\\/d\\\\/([0-9a-f]{12})(?:\\\\/([0-9a-f]{12}))?$/;\nconst statusEl = document.getElementById('status');\n\nconst HISTORY_PANEL = 'codesign.revisionHistory';\n\nconst match = relPath().match(PATH_RE);\n\nif (!match) {\n statusEl.textContent = 'invalid URL';\n} else {\n const root = match[1];\n\n // Server-supplied license + resource base + engine URL.\n const cfgRes = await fetch(\\`\\${BASE}/api/config\\`);\n if (!cfgRes.ok) throw new Error(\\`/api/config failed: \\${cfgRes.status}\\`);\n const {\n license,\n resourceBase,\n cesdkEngineUrl,\n cesdkAssetsUrl,\n defaultAssetsBaseUrl,\n gfontsContentUrl\n } = await cfgRes.json();\n\n const cesdkMod = await import(cesdkEngineUrl);\n const CreativeEditorSDK = cesdkMod.default ?? cesdkMod.CreativeEditorSDK;\n\n // UI icons/CSS (\\`ui.baseURL\\`) load from the cesdk-js CDN path we imported the\n // SDK from. Engine WASM/data (\\`baseURL\\`) load from cesdk-engine's own CDN\n // path (\\`cesdkAssetsUrl\\`) instead — the two packages' asset builds can drift\n // on the CDN, and cesdk-engine's own path is self-consistent with the bundle\n // that references it (see cesdk-cdn.ts).\n const uiAssetBase = cesdkEngineUrl.replace(/\\\\/index\\\\.js$/, '/assets');\n const cesdk = await CreativeEditorSDK.create(\n document.getElementById('cesdk'),\n {\n license,\n baseURL: cesdkAssetsUrl,\n ui: { baseURL: uiAssetBase + '/ui/' },\n theme: 'dark'\n }\n );\n const engine = cesdk.engine;\n\n configureDesignEditorUI(cesdk);\n\n // Register CE.SDK's DEFAULT asset sources — shapes, stickers, typefaces,\n // color palettes, LUT filters/effects, page & crop presets — never the\n // demo ones (no stock images/videos/audio). The manifest base URL comes\n // from /api/config so the browser and the headless engine resolve the\n // same manifests (IMGLY_DEFAULT_ASSETS_BASE_URL-aware). \\`ly.img.text\\` is\n // excluded exactly like the node side (its manifest is missing from the\n // CDN manifest root and one 404 rejects the whole call). Page presets\n // ride along here — the former page-presets plugin registered the same\n // source id and the two cannot coexist (colliding registrations reject\n // the whole call), so the plugin is gone; the \\`ly.img.pagePresets\\` LIBRARY\n // ENTRY the Resize Page panel reads is wired in configureDesignEditorUI.\n // Best-effort and isolated in its own try/catch: a down/misconfigured\n // IMGLY_DEFAULT_ASSETS_BASE_URL leaves the editor usable with an empty\n // shapes/stickers/typefaces/LUT-filters/presets library, and must NOT take\n // down the engine-CDN sources registered below (different host, see that\n // block's comment).\n try {\n await cesdk.addDefaultAssetSources({\n baseURL: defaultAssetsBaseUrl,\n excludeAssetSourceIds: ['ly.img.text']\n });\n } catch (err) {\n console.error(\n 'codesign: asset-source registration failed — asset library will be empty',\n err\n );\n }\n\n // The engine-assets manifests below cover what the default manifest root\n // does NOT carry (each 404s under <defaultAssetsBaseUrl>/<id>/content.json\n // but is published under <engine>/assets/<id>/content.json, where the CDN\n // plugins bundle used to load them from):\n // - the stock \\`ly.img.text\\` library entry queries the four text sources —\n // with none registered the Text dock panel shows \"No Elements\";\n // - the appearance Filter panel hard-queries the combined \\`ly.img.filter\\`\n // source (not filter.lut/filter.duotone) and shows an infinite spinner\n // while that id is unregistered;\n // - the stock Shapes entry titles its group headers with\n // \\`libraries.ly.img.vector.shape.<group>.label\\`, and the UI bundle only\n // ships translations for THIS source's groups (filled/outline/gradient/\n // image/abstract-*) — the default root's vectorpath source has verbose\n // category group ids that render as raw i18n keys.\n // These six are registered in parallel via Promise.allSettled, each\n // isolated from the others' failures — one 404 must not take out the rest\n // of the library. This block runs UNCONDITIONALLY, regardless of whether\n // addDefaultAssetSources above succeeded: the two target different hosts —\n // a down/misconfigured IMGLY_DEFAULT_ASSETS_BASE_URL must not blank the\n // Text/Filter panels whose manifests come from the (independent) engine\n // CDN. No try/catch needed here: Promise.allSettled never rejects.\n const engineAssetSourceIds = [\n 'ly.img.text',\n 'ly.img.text.styles',\n 'ly.img.text.components',\n 'ly.img.text.curves',\n 'ly.img.filter',\n 'ly.img.vector.shape'\n ];\n const results = await Promise.allSettled(\n engineAssetSourceIds.map((id) =>\n engine.asset.addLocalAssetSourceFromJSONURI(\n \\`\\${cesdkAssetsUrl}/\\${id}/content.json\\`\n )\n )\n );\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n console.error(\n 'codesign: failed to register asset source',\n engineAssetSourceIds[index],\n result.reason\n );\n }\n });\n\n // Google Fonts (ly.img.gfonts) — the same self-hosted catalog the headless\n // engine registers, URL via /api/config so both sides stay in sync.\n // Best-effort in its own try/catch: a CDN failure must not take down the\n // editor — the font picker just falls back to the stock typefaces.\n try {\n await engine.asset.addLocalAssetSourceFromJSONURI(gfontsContentUrl);\n } catch (err) {\n console.error('codesign: Google Fonts source registration failed', err);\n }\n\n // Resolve workspace:// asset URIs to the /r/ HTTP route.\n const absResourceBase = location.origin + resourceBase;\n engine.editor.setURIResolver((uri, defaultResolver) =>\n uri.startsWith('workspace://')\n ? absResourceBase + uri.slice('workspace://'.length)\n : defaultResolver(uri)\n );\n\n // --- runtime state ----------------------------------------------------\n let head = null; // the design's latest leaf\n let currentRev = null; // the revision currently on canvas\n let following = false; // true → the canvas tracks head as SSE arrives\n let dirty = false; // true → a local edit happened since the last load\n let loading = false; // true while show() swaps the scene programmatically\n let warnNotification = null; // id of the \"not saved back\" notification\n let newCount = 0; // revisions arrived since following stopped\n let orderedRevisions = []; // order(fetchRevisions(...)) — drives the panel\n let saving = false; // save-back POST in flight\n\n // --- CE.SDK re-render bridge ------------------------------------------\n // Builder components re-render when a state() value they read changes. Our\n // editor state lives in the plain variables above, which CE.SDK's reactor\n // can't see, so each reactive component reads a monotonic \\`uiVersion\\` from\n // state() purely to subscribe, and invalidateUI() bumps every mounted\n // component to force a coherent re-read. The title, too, is bridged — CE.SDK's\n // builder components don't re-render on engine name changes alone (see\n // codesign.title below). Calls are wrapped because a component that has\n // since unmounted (e.g. a closed panel) throws on setValue.\n let uiVersion = 0;\n const bump = new Map(); // componentKey -> setValue, refreshed on each render\n function invalidateUI() {\n uiVersion += 1;\n for (const setVersion of bump.values()) {\n try {\n setVersion(uiVersion);\n } catch {\n /* component unmounted — ignore */\n }\n }\n }\n\n // Subscribe a component to invalidateUI(). Reading \\`version.value\\` (not just\n // grabbing setValue) is what registers the reactive dependency — CE.SDK only\n // re-renders a component when a state value it *read* during render changes,\n // so invalidateUI()'s setValue bumps are no-ops unless the value was read.\n function subscribeToUI(state, key) {\n const version = state('v', 0);\n bump.set(key, version.setValue);\n return version.value;\n }\n\n async function loadRevision(rev) {\n const res = await fetch(\\`\\${BASE}/snapshot/\\${rev}\\`);\n if (!res.ok) throw new Error(\\`snapshot \\${rev} \\${res.status}\\`);\n const snap = await res.json();\n await engine.scene.loadFromString(snap.scene);\n // Feed the nav-bar title component via engine reactivity.\n const scene = engine.scene.get();\n if (scene != null) engine.block.setName(scene, snap.title ?? 'Untitled');\n // Fit the page in the viewport and keep it fitted on resize.\n const page = engine.block.findByType('page')[0];\n if (page != null)\n engine.scene.enableZoomAutoFit(page, 'Both', 40, 40, 40, 40);\n }\n\n // The single navigation primitive. Loads \\`rev\\`, sets LIVE/PINNED, writes the\n // URL. historyMode: \"push\" adds a history entry, \"replace\" rewrites in place,\n // \"none\" leaves history alone (popstate already changed the URL).\n // Every arrival here is a fresh scene: it clears \\`dirty\\` and dismisses the\n // warning. Callers navigating away from local edits must confirmDiscard()\n // FIRST — show() itself never asks.\n async function show(rev, { following: nextFollowing, historyMode }) {\n try {\n // Clear any prior error banner so a later successful load self-heals it.\n statusEl.textContent = '';\n loading = true;\n try {\n await loadRevision(rev);\n } finally {\n loading = false;\n }\n if (dirty) {\n dirty = false;\n dismissEditWarning();\n }\n currentRev = rev;\n following = nextFollowing;\n if (following) newCount = 0;\n const url = following ? \\`\\${BASE}/d/\\${root}\\` : \\`\\${BASE}/d/\\${root}/\\${rev}\\`;\n if (historyMode === 'push') window.history.pushState({ rev }, '', url);\n else if (historyMode === 'replace')\n window.history.replaceState({ rev }, '', url);\n } catch {\n statusEl.textContent = 'unknown revision';\n }\n invalidateUI();\n }\n\n async function refreshRevisions() {\n try {\n orderedRevisions = order(await fetchRevisions(BASE, root));\n } catch {\n orderedRevisions = [];\n }\n invalidateUI();\n }\n\n // --- dirty tracking -----------------------------------------------------\n // The first REAL local edit detaches the tab from live-follow: edits are\n // local-only (no write path back to the workspace), so the canvas must stop\n // being swapped out underneath them. 'Updated' events during a programmatic\n // load (loading === true) and the post-load baseline (canUndo() === false)\n // are not edits. Undoing back to the baseline does NOT clear \\`dirty\\` — once\n // touched, the tab stays detached until explicit navigation via show().\n function dismissEditWarning() {\n if (warnNotification == null) return;\n try {\n cesdk.ui.dismissNotification?.(warnNotification);\n } catch {\n /* notification already gone — ignore */\n }\n warnNotification = null;\n }\n\n // Save the tab's scene back to the workspace as a child revision of\n // currentRev (CODE-111). On success the canvas already IS the new head:\n // advance pointers and resume following WITHOUT reloading — a reload would\n // wipe the user's undo stack.\n async function saveBack() {\n if (saving || currentRev == null) return;\n const divergedHead = head != null && head !== currentRev ? head : null;\n saving = true;\n invalidateUI();\n try {\n // Pasted media lives only in this tab's engine (buffer:// resources);\n // saveToString would persist dangling references. Refuse loudly.\n const transient = engine.editor.findAllTransientResources?.() ?? [];\n if (transient.length > 0) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n 'This design contains pasted media that only exists in this tab — remove it or use Export; saving it back is not supported yet.'\n });\n return;\n }\n // format: 1 = CompressionFormat.Zstd, level: 1 = CompressionLevel.Default —\n // mirrors the server-side SCENE_COMPRESSION constant in\n // src/engine/scene-compression.ts (this bundle can't import it directly;\n // that module is the source of truth for the values).\n const scene = await engine.scene.saveToString({\n compression: { format: 1, level: 1 }\n });\n const res = await fetch(\\`\\${BASE}/api/design/\\${root}/revisions\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ parent: currentRev, scene })\n });\n if (!res.ok) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n res.status === 422\n ? 'Saving failed: the scene could not be read back. Your edits stay in this tab.'\n : res.status === 503\n ? 'Saving failed: the design engine is busy — try again in a moment. Your edits stay in this tab.'\n : \\`Saving failed (\\${res.status}). Your edits stay in this tab.\\`\n });\n return;\n }\n const body = await res.json();\n if (body.noop && head != null && head !== body.revision) {\n // Diverged no-op save while the design moved on (the assistant\n // committed meanwhile): nothing was written — keep the tab detached\n // so \"Revert to Synced\" still points at the newer head, and keep \\`head\\` intact.\n dirty = false;\n dismissEditWarning();\n cesdk.ui.showNotification({\n type: 'success',\n message:\n 'Nothing new to save — the design has newer revisions; use Revert to Synced to see them.'\n });\n return;\n }\n // Either a real save (201) or a non-diverged no-op (200, nothing\n // written but the tab already matches the saved revision) — both\n // resume following/unpin the same way; only the message tells the\n // truth about whether anything was actually written.\n currentRev = body.revision;\n head = body.revision;\n newCount = 0;\n dirty = false;\n dismissEditWarning();\n following = true;\n window.history.replaceState({ rev: null }, '', \\`\\${BASE}/d/\\${root}\\`);\n refreshRevisions();\n cesdk.ui.showNotification({\n type: 'success',\n message: body.noop\n ? 'Nothing new to save — everything already matches the saved revision.'\n : divergedHead\n ? 'Saved as a parallel version — the assistant also changed this design while you were editing.'\n : 'Saved — the assistant can now see your changes.'\n });\n } catch (err) {\n cesdk.ui.showNotification({\n type: 'error',\n message:\n 'Saving failed: could not reach the local server. Your edits stay in this tab.'\n });\n } finally {\n saving = false;\n invalidateUI();\n }\n }\n\n engine.editor.onHistoryUpdatedWithKind((kind) => {\n if (kind !== 'Updated' || loading || dirty) return;\n if (!engine.editor.canUndo()) return;\n dirty = true;\n following = false;\n // The URL mirrors following-state everywhere else (LIVE = /d/<root>,\n // PINNED = /d/<root>/<rev>); a detached-by-edit tab is pinned.\n if (currentRev != null)\n window.history.replaceState(\n { rev: currentRev },\n '',\n \\`\\${BASE}/d/\\${root}/\\${currentRev}\\`\n );\n warnNotification = cesdk.ui.showNotification({\n type: 'warning',\n duration: 'infinite',\n message:\n \"Unsaved edits — click 'Save for Agent' to share them with the assistant.\"\n });\n invalidateUI();\n });\n\n // Local edits are throwaway: every navigation that would replace the scene\n // asks before discarding them.\n function confirmDiscard() {\n return (\n !dirty ||\n window.confirm(\n 'Discard your local edits? They are not saved back to the workspace.'\n )\n );\n }\n\n // Closing the tab with unexported local edits prompts (browsers show their\n // own generic message; preventDefault is what arms it).\n window.addEventListener('beforeunload', (ev) => {\n if (!dirty) return;\n ev.preventDefault();\n ev.returnValue = '';\n });\n\n // --- nav bar components ------------------------------------------------\n installCodesignChrome();\n\n function installCodesignChrome() {\n // Panel title (registered here so the toggle's target exists and the i18n\n // title is set once; the toggle itself is hidden for now).\n cesdk.i18n.setTranslations({\n en: { [\\`panel.\\${HISTORY_PANEL}\\`]: 'Revisions' }\n });\n\n // Live-follow status: \"Synced\" while following; \"Revert to Synced\"\n // (+ unseen count) when pinned or detached by a local edit. Reads module\n // state → bridged via the version bump.\n cesdk.ui.registerComponent('codesign.liveStatus', ({ builder, state }) => {\n subscribeToUI(state, 'liveStatus');\n if (following) {\n builder.Button('codesign.liveStatus.live', {\n label: 'Synced',\n icon: '@imgly/FileCheck',\n variant: 'plain',\n isDisabled: true\n });\n } else {\n builder.Button('codesign.liveStatus.goLive', {\n label:\n newCount > 0\n ? \\`Revert to Synced (\\${newCount})\\`\n : 'Revert to Synced',\n icon: '@imgly/FileImport',\n variant: 'plain',\n onClick: () => {\n if (head && confirmDiscard())\n show(head, { following: true, historyMode: 'push' });\n }\n });\n }\n });\n\n // Save-back button: always visible, actionable only while the tab holds\n // unsaved edits (grayed out when there is nothing to save).\n cesdk.ui.registerComponent('codesign.saveBack', ({ builder, state }) => {\n subscribeToUI(state, 'saveBack');\n builder.Button('codesign.saveBack.button', {\n label: saving ? 'Saving…' : 'Save for Agent',\n icon: '@imgly/Save',\n color: 'accent',\n isDisabled: saving || !dirty,\n onClick: () => void saveBack()\n });\n });\n\n // Document title. The built-in \\`ly.img.title.navigationBar\\` does NOT read\n // engine.block.getName() reactively — it only renders a static string\n // passed via \\`ui.elements.navigation.title\\` at create() time or a\n // per-instance \\`payload.title\\` in the order array (neither of which we\n // set), so it never renders anything here. Read the scene name ourselves\n // instead, bridged through the same state()/invalidateUI() mechanism as\n // codesign.liveStatus so it refreshes on every show(). Refreshes on\n // invalidateUI() bumps; a rename via document settings while the tab is\n // already dirty stays stale until the next bump — accepted cosmetic\n // staleness.\n cesdk.ui.registerComponent('codesign.title', ({ builder, state }) => {\n subscribeToUI(state, 'title');\n const scene = engine.scene.get();\n const title = scene != null ? engine.block.getName(scene) : '';\n if (title) builder.Heading('codesign.title.heading', { content: title });\n });\n\n // History toggle. isActive rides CE.SDK's own reactive panel-open state.\n cesdk.ui.registerComponent('codesign.historyToggle', ({ builder }) => {\n const open = cesdk.ui.isPanelOpen(HISTORY_PANEL);\n builder.Button('codesign.historyToggle.button', {\n label: 'History',\n isActive: open,\n onClick: () =>\n open\n ? cesdk.ui.closePanel(HISTORY_PANEL)\n : cesdk.ui.openPanel(HISTORY_PANEL, {\n position: 'right',\n floating: true\n })\n });\n });\n\n // Revision history — native builder panel. Reuses revision-data.js's order()\n // output; reads module state → bridged via the version bump. Rows are\n // buttons: indent = depth, label = short id · note · time (+ head/root/fork).\n cesdk.ui.registerPanel(HISTORY_PANEL, ({ builder, state }) => {\n subscribeToUI(state, 'historyPanel');\n builder.Section('codesign.history.section', {\n title: following ? 'Revisions · SYNCED' : 'Revisions · PINNED',\n children: () => {\n if (orderedRevisions.length === 0) {\n builder.Text('codesign.history.empty', {\n content: 'No revisions yet'\n });\n return;\n }\n for (const { node, depth, isHead, isRoot } of orderedRevisions) {\n const indent = depth > 0 ? ' '.repeat(depth) + '↳ ' : '';\n const marker = isHead\n ? ' · head'\n : isRoot\n ? ' · root'\n : depth > 0\n ? ' · fork'\n : '';\n const note = node.note ? \\` · \\${node.note}\\` : '';\n builder.Button(\\`codesign.history.\\${node.id}\\`, {\n label: \\`\\${indent}\\${node.id.slice(0, 7)}\\${note}\\${marker} · \\${relTime(node.createdAt)}\\`,\n variant: 'plain',\n isActive: node.id === currentRev,\n onClick: () => {\n if (!confirmDiscard()) return;\n show(node.id, {\n following: node.id === head,\n historyMode: 'push'\n });\n }\n });\n }\n }\n });\n });\n\n // Final navigation bar: the design-editor chrome (document settings,\n // undo/redo, title, zoom, preview) plus the live-follow status. This\n // REPLACES the order configureDesignEditorUI set, so the export dropdown\n // must be (re-)inserted after it.\n cesdk.ui.setComponentOrder({ in: 'ly.img.navigation.bar' }, [\n 'ly.img.documentSettings.navigationBar',\n 'ly.img.undoRedo.navigationBar',\n 'ly.img.spacer',\n 'codesign.title',\n 'ly.img.spacer',\n 'codesign.liveStatus',\n 'codesign.saveBack',\n 'ly.img.zoom.navigationBar',\n 'ly.img.preview.navigationBar'\n // 'codesign.historyToggle' — hidden for now; the panel + refreshRevisions\n // machinery stays wired, so re-add this line to bring History back.\n ]);\n\n // Export dropdown. The scene references workspace:// assets, so exporting\n // the bare scene (or \"Save\") would produce broken links — the self-contained\n // archive (.zip, assets embedded) is the default/prominent action, with\n // image and PDF in the overflow. Each child carries an explicit handler\n // that ends in a browser download — the only way work leaves this tab.\n cesdk.ui.insertOrderComponent(\n { in: 'ly.img.navigation.bar', position: 'end' },\n {\n id: 'ly.img.actions.navigationBar',\n children: [\n {\n id: 'ly.img.exportArchive.navigationBar',\n onClick: async () => {\n const archive = await engine.scene.saveToArchive();\n await cesdk.utils.downloadFile(archive, 'application/zip');\n }\n },\n {\n id: 'ly.img.exportImage.navigationBar',\n onClick: async () => {\n const { blobs, options } = await cesdk.utils.export({\n mimeType: 'image/png'\n });\n await cesdk.utils.downloadFile(blobs[0], options.mimeType);\n }\n },\n {\n id: 'ly.img.exportPDF.navigationBar',\n onClick: async () => {\n const { blobs, options } = await cesdk.utils.export({\n mimeType: 'application/pdf'\n });\n await cesdk.utils.downloadFile(blobs[0], options.mimeType);\n }\n }\n ]\n }\n );\n }\n\n // --- bootstrap --------------------------------------------------------\n let latestLeaf;\n try {\n const res = await fetch(\\`\\${BASE}/api/design/\\${root}\\`);\n if (!res.ok) throw new Error(String(res.status));\n latestLeaf = (await res.json()).latestLeaf;\n } catch {\n statusEl.textContent = 'unknown design';\n }\n\n if (latestLeaf !== undefined) {\n head = latestLeaf;\n const pinned = match[2]; // undefined → LIVE\n await show(pinned ?? head, {\n following: pinned === undefined,\n historyMode: 'replace'\n });\n await refreshRevisions();\n\n // SSE — held open for the tab's life, in every state. It moves the canvas\n // only while following (a dirty tab is never following).\n const es = new EventSource(\\`\\${BASE}/sse/\\${root}\\`);\n es.onmessage = (ev) => {\n let payload;\n try {\n payload = JSON.parse(ev.data);\n } catch (err) {\n console.error('sse parse failed', err);\n return;\n }\n if (!payload || typeof payload.revision !== 'string') return;\n head = payload.revision;\n refreshRevisions();\n if (payload.revision === currentRev) {\n // Our own save-back landing (or any echo of the state already on\n // canvas) — reloading it would wipe the undo stack.\n invalidateUI();\n return;\n }\n if (following) {\n show(head, { following: true, historyMode: 'replace' });\n } else {\n newCount += 1;\n invalidateUI();\n }\n };\n }\n\n // Browser back/forward: re-resolve the URL shape and sync, without writing\n // history (the entry already changed). With unexported local edits, ask\n // first — on cancel, restore the URL of the revision still on canvas.\n window.addEventListener('popstate', () => {\n const m = relPath().match(PATH_RE);\n if (!m || m[1] !== root) return;\n if (!confirmDiscard()) {\n const url = following\n ? \\`\\${BASE}/d/\\${root}\\`\n : \\`\\${BASE}/d/\\${root}/\\${currentRev}\\`;\n window.history.pushState({ rev: currentRev }, '', url);\n return;\n }\n const pinned = m[2];\n show(pinned ?? head, {\n following: pinned === undefined,\n historyMode: 'none'\n });\n });\n}\n\n// Install the design-editor UI. This mirrors IMG.LY's \\`DesignEditorConfig\\`\n// plugin (features → actions → component orders), which we can't import here\n// (see the file header), reproduced verbatim from the Design Editor starter kit\n// and trimmed for this surface:\n// - the dock / asset library IS enabled (features \\`ly.img.dock\\`,\n// \\`ly.img.library.panel\\`) with a Text / Shapes / Stickers dock order set\n// below, fed by the default asset sources registered in the boot code;\n// - no video/audio features enabled (so a static design has no timeline);\n// - the Trim and Vector inspector edit modes are omitted because their\n// features (video trimming, vector-path editing) aren't enabled here, so\n// those modes are unreachable;\n// - the Document inspector's \"Resize Page\" panel is fed by the\n// \\`ly.img.pagePresets\\` entry wired below to the page-presets source that\n// rides along with the default asset sources (see the boot code);\n// - the navigation-bar order + export dropdown live in\n// installCodesignChrome() (they include codesign components registered\n// after the resetEditor() below).\nfunction configureDesignEditorUI(cesdk) {\n // Clear the empty default configuration, then apply ours. \\`resetEditor()\\` can\n // drop the theme passed to \\`create()\\`, so re-apply it.\n cesdk.resetEditor();\n cesdk.ui.setTheme('dark');\n\n // --- Features (starter-kit design set, plus the dock/library) -------------\n cesdk.feature.enable([\n 'ly.img.navigation',\n 'ly.img.dock',\n 'ly.img.library.panel',\n 'ly.img.text',\n 'ly.img.crop',\n 'ly.img.transform',\n 'ly.img.filter',\n 'ly.img.adjustment',\n 'ly.img.effect',\n 'ly.img.blur',\n 'ly.img.shadow',\n 'ly.img.cutout',\n 'ly.img.canvas',\n 'ly.img.inspector',\n 'ly.img.inspector.bar',\n 'ly.img.inspector.toggle',\n 'ly.img.delete',\n 'ly.img.duplicate',\n 'ly.img.group',\n 'ly.img.replace',\n 'ly.img.page',\n 'ly.img.scene.layout',\n 'ly.img.fill.color',\n 'ly.img.fill.image',\n 'ly.img.stroke',\n 'ly.img.opacity',\n 'ly.img.blendMode',\n 'ly.img.shape.options',\n 'ly.img.combine',\n 'ly.img.position',\n 'ly.img.trim',\n 'ly.img.notifications',\n 'ly.img.keyboard.shortcuts'\n ]);\n\n // --- Panels: inspector docked on the left, pushing the canvas -------------\n cesdk.ui.setPanelPosition('//ly.img.panel/inspector', 'left');\n cesdk.ui.setPanelFloating('//ly.img.panel/inspector', false);\n\n // --- Dock: asset library with Text / Shapes / Stickers --------------------\n // The stock \\`ly.img.vector.shape\\` and \\`ly.img.sticker\\` entries ship with\n // EMPTY sourceIds — wire them explicitly (no reliance on hidden\n // auto-population). Shapes points at the engine-CDN \\`ly.img.vector.shape\\`\n // source registered in the boot code — NOT the default root's vectorpath\n // source, whose group ids have no shipped translations and render as raw\n // i18n keys in the panel's section headers. Stickers uses the source\n // addDefaultAssetSources registers; the \\`ly.img.text\\` entry keeps its stock\n // sources. No image/video/audio/upload entries: the library carries only\n // the neutral defaults, no demo content.\n cesdk.ui.updateAssetLibraryEntry('ly.img.vector.shape', {\n sourceIds: ['ly.img.vector.shape']\n });\n cesdk.ui.updateAssetLibraryEntry('ly.img.sticker', {\n sourceIds: ['ly.img.sticker']\n });\n // The Document inspector's \"Resize Page\" panel lists the formats of the\n // sources named by the \\`ly.img.pagePresets\\` entry (note: entry id, NOT the\n // \\`ly.img.page.presets\\` source id) — it also ships with EMPTY sourceIds,\n // which left the panel body blank. The source itself is registered by\n // addDefaultAssetSources in the boot code.\n cesdk.ui.updateAssetLibraryEntry('ly.img.pagePresets', {\n sourceIds: ['ly.img.page.presets']\n });\n // The text inspector's font picker reads the \\`ly.img.typefaces\\` (PLURAL)\n // library entry — not to be confused with the \\`ly.img.typeface\\` (singular)\n // stock asset SOURCE id it already lists in its sourceIds. Unlike the\n // neighboring \\`ly.img.vector.shape\\` / \\`ly.img.sticker\\` / \\`ly.img.pagePresets\\`\n // patches above (justified because those entries ship EMPTY sourceIds),\n // \\`ly.img.typefaces\\` already lists the stock source — so we APPEND the\n // Google Fonts source (registered in the boot code) to whatever the entry\n // already has, rather than overwriting it, so the picker lists gfonts\n // families alongside the stock set instead of replacing it. Assert the\n // entry exists — if CE.SDK renames it we want a loud warning, not a\n // silently stock-only font list.\n const typefaceEntry = cesdk.ui.getAssetLibraryEntry('ly.img.typefaces');\n if (typefaceEntry) {\n cesdk.ui.updateAssetLibraryEntry('ly.img.typefaces', {\n sourceIds: [\n ...new Set([...(typefaceEntry.sourceIds ?? []), 'ly.img.gfonts'])\n ]\n });\n // Give the gfonts group a human label instead of the raw source id\n // header in the panel.\n cesdk.i18n.setTranslations({\n en: { 'libraries.ly.img.gfonts.label': 'Google Fonts' }\n });\n } else {\n console.warn(\n 'codesign: ly.img.typefaces library entry missing — Google Fonts hidden in the font picker'\n );\n }\n cesdk.ui.setComponentOrder({ in: 'ly.img.dock' }, [\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'text',\n label: 'libraries.ly.img.text.label',\n icon: '@imgly/Text',\n entries: ['ly.img.text']\n },\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'shapes',\n label: 'libraries.ly.img.vector.shape.label',\n icon: '@imgly/Shapes',\n entries: ['ly.img.vector.shape']\n },\n {\n id: 'ly.img.assetLibrary.dock',\n key: 'stickers',\n label: 'libraries.ly.img.sticker.label',\n icon: '@imgly/Sticker',\n entries: ['ly.img.sticker']\n }\n ]);\n\n // --- Inspector bar — contextual controls for the selected block -----------\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.inspector.bar', when: { editMode: 'Transform' } },\n [\n 'ly.img.spacer',\n 'ly.img.pageResize.inspectorBar',\n 'ly.img.separator',\n 'ly.img.video.caption.inspectorBar',\n 'ly.img.shape.options.inspectorBar',\n 'ly.img.cutout.type.inspectorBar',\n 'ly.img.cutout.offset.inspectorBar',\n 'ly.img.cutout.smoothing.inspectorBar',\n 'ly.img.group.create.inspectorBar',\n 'ly.img.group.ungroup.inspectorBar',\n 'ly.img.audio.replace.inspectorBar',\n 'ly.img.separator',\n 'ly.img.text.typeFace.inspectorBar',\n 'ly.img.text.bold.inspectorBar',\n 'ly.img.text.italic.inspectorBar',\n 'ly.img.text.fontSize.inspectorBar',\n 'ly.img.text.alignHorizontal.inspectorBar',\n 'ly.img.text.advanced.inspectorBar',\n 'ly.img.combine.inspectorBar',\n 'ly.img.separator',\n 'ly.img.fill.inspectorBar',\n 'ly.img.trim.inspectorBar',\n 'ly.img.volume.inspectorBar',\n 'ly.img.crop.inspectorBar',\n 'ly.img.separator',\n 'ly.img.stroke.inspectorBar',\n 'ly.img.separator',\n 'ly.img.text.background.inspectorBar',\n 'ly.img.separator',\n 'ly.img.animations.inspectorBar',\n 'ly.img.separator',\n {\n id: 'ly.img.appearance.inspectorBar',\n children: [\n 'ly.img.adjustment.inspectorBar',\n 'ly.img.filter.inspectorBar',\n 'ly.img.effect.inspectorBar',\n 'ly.img.blur.inspectorBar'\n ]\n },\n 'ly.img.separator',\n 'ly.img.shadow.inspectorBar',\n 'ly.img.separator',\n 'ly.img.opacityOptions.inspectorBar',\n 'ly.img.separator',\n 'ly.img.position.inspectorBar',\n 'ly.img.spacer',\n 'ly.img.separator',\n 'ly.img.inspectorToggle.inspectorBar'\n ]\n );\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.inspector.bar', when: { editMode: 'Crop' } },\n ['ly.img.cropControls.inspectorBar']\n );\n\n // --- Canvas bar (bottom) and the selection context menu -------------------\n cesdk.ui.setComponentOrder({ in: 'ly.img.canvas.bar', at: 'bottom' }, [\n 'ly.img.settings.canvasBar',\n 'ly.img.spacer',\n 'ly.img.page.add.canvasBar',\n 'ly.img.spacer'\n ]);\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.canvas.menu', when: { editMode: 'Transform' } },\n [\n 'ly.img.group.enter.canvasMenu',\n 'ly.img.group.select.canvasMenu',\n 'ly.img.page.moveUp.canvasMenu',\n 'ly.img.page.moveDown.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.edit.canvasMenu',\n 'ly.img.text.styles.canvasMenu',\n 'ly.img.replace.canvasMenu',\n 'ly.img.separator',\n 'ly.img.bringForward.canvasMenu',\n 'ly.img.sendBackward.canvasMenu',\n 'ly.img.separator',\n 'ly.img.duplicate.canvasMenu',\n 'ly.img.delete.canvasMenu',\n 'ly.img.separator',\n 'ly.img.options.canvasMenu'\n ]\n );\n cesdk.ui.setComponentOrder(\n { in: 'ly.img.canvas.menu', when: { editMode: 'Text' } },\n [\n 'ly.img.text.color.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.bold.canvasMenu',\n 'ly.img.text.italic.canvasMenu',\n 'ly.img.text.underline.canvasMenu',\n 'ly.img.text.strikethrough.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.list.unordered.canvasMenu',\n 'ly.img.text.list.ordered.canvasMenu',\n 'ly.img.separator',\n 'ly.img.text.variables.canvasMenu'\n ]\n );\n}\n`,\n\t\"index.html\": `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>CoDesign</title>\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <!-- Mount prefix injected by the viewer router (router.ts). \"\" on the stdio\n listener, \"/viewer\" on the HTTP transport. Read by editor.js. -->\n <script>\n window.__VIEWER_BASE__ = '{{VIEWER_BASE}}';\n </script>\n <style>\n html,\n body {\n margin: 0;\n height: 100%;\n background: #1d1d1f;\n color: #eee;\n font-family: -apple-system, system-ui, sans-serif;\n }\n #cesdk {\n position: fixed;\n inset: 0;\n }\n #status {\n position: fixed;\n top: 14px;\n left: 14px;\n z-index: 10;\n font:\n 500 12px -apple-system,\n system-ui,\n sans-serif;\n }\n </style>\n </head>\n <body>\n <div id=\"cesdk\"></div>\n <div id=\"status\"></div>\n <script type=\"module\" src=\"{{VIEWER_BASE}}/static/editor.js\"></script>\n </body>\n</html>\n`,\n\t\"revision-data.js\": `// revision-data.js — framework-free data layer for the editor's revision\n// history. No DOM and no top-level \\`window\\` access, so order()/relTime() are\n// unit-testable under node. Consumed by editor.js's CE.SDK history panel.\n\n// Relative time label (\"5m ago\"). Uses Date.now() at call time (browser + node).\nexport function relTime(ms) {\n const s = Math.max(0, Math.round((Date.now() - ms) / 1000));\n if (s < 60) return \\`\\${s}s ago\\`;\n const m = Math.round(s / 60);\n if (m < 60) return \\`\\${m}m ago\\`;\n const h = Math.round(m / 60);\n if (h < 24) return \\`\\${h}h ago\\`;\n return \\`\\${Math.round(h / 24)}d ago\\`;\n}\n\n// Depth-first walk. At each node the spine child (or, off-spine, the latest\n// child) continues at the same depth; other children are branches at depth + 1,\n// emitted before the continuation so the spine reads top-to-bottom. Returns\n// [{ node, depth, isHead, isRoot }]. Pure — no DOM, no globals.\nexport function order(nodes) {\n if (nodes.length === 0) return [];\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const children = new Map();\n for (const n of nodes) {\n if (n.parent != null) {\n const sibs = children.get(n.parent) ?? [];\n sibs.push(n);\n children.set(n.parent, sibs);\n }\n }\n for (const sibs of children.values())\n sibs.sort((a, b) => a.createdAt - b.createdAt);\n const rootNode = nodes.find((n) => n.parent === null);\n const head = nodes.reduce((a, b) => (b.createdAt > a.createdAt ? b : a));\n const spine = new Set();\n for (let n = head; n; n = n.parent != null ? byId.get(n.parent) : null)\n spine.add(n.id);\n const out = [];\n function walk(node, depth) {\n out.push({\n node,\n depth,\n isHead: node.id === head.id,\n isRoot: node.parent === null\n });\n const kids = children.get(node.id) ?? [];\n if (kids.length === 0) return;\n const primary = kids.find((k) => spine.has(k.id)) ?? kids[kids.length - 1];\n for (const k of kids) if (k !== primary) walk(k, depth + 1);\n walk(primary, depth);\n }\n if (rootNode) walk(rootNode, 0);\n return out;\n}\n\n// Fetch a design's full revision tree. \\`base\\` is the mount prefix (\"\" on stdio,\n// \"/viewer\" on HTTP). Throws on a non-2xx response so the caller can degrade.\nexport async function fetchRevisions(base, root) {\n const res = await fetch(\\`\\${base}/api/design/\\${root}/revisions\\`);\n if (!res.ok) throw new Error(\\`revisions \\${root} \\${res.status}\\`);\n return res.json();\n}\n`,\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imgly/codesign-mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11-next.20260727132311.gbce42f2",
|
|
4
4
|
"description": "IMG.LY CoDesign MCP server: SYSTEM prompt, prompts, skills, design tools as MCP resources/prompts/tools.",
|
|
5
5
|
"mcpName": "io.github.imgly/codesign",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
},
|
|
16
16
|
"type": "module",
|
|
17
17
|
"engines": {
|
|
18
|
-
"node": ">=
|
|
18
|
+
"node": ">=22.15"
|
|
19
19
|
},
|
|
20
20
|
"bin": {
|
|
21
21
|
"codesign-mcp": "dist/cli.js"
|