Merge pull request #3005 from zsviczian/2026-10-14-issue-3004-cli-image-efficiency

Fix #3004: safe CLI revisions and bounded image previews
This commit is contained in:
zsviczian authored and GitHub committed 2026-10-21 18:44:50 +02:00
commit 4ebbf50470
32 files changed
+1167 -93

No files matched your search

+6 -3
View File
@@ -10,13 +10,16 @@ All results use apiVersion 1. Check ok, mutation and persistence; process exit z
Put large requests in a visible vault-relative JSON file and pass input="<file>". Inline json is for small requests.
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY only after read-back.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
:result requestId=<id> recovers a receipt after lost stdout. Receipts expire after 15 minutes/reload; unknown outcome requires read-back before another write.
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Remote assets follow existing permissions.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
imageMetadata apply operations set bounded descriptive label/tags, with null clearing; request-only imagePolicy.labels does not persist. Thumbnail mode uses thumbnailMaxDimension=512 by default; only PNG/JPEG/WebP with safe preflight dimensions are decoded (24 MiB / 16 million pixels maximum).
maxWidth/maxHeight/maxPixels bound output dimensions; maxArtifactBytes caps final bytes. Source revision covers originals; representationId identifies the preview. SVG width controls display size, not embedded raster payload size; use imagePolicy for that.
Use :schema for exact fields, operation limits, and runnable examples. Do not edit compressed drawing Markdown directly or install another Excalidraw CLI.
+29 -4
View File
@@ -105,6 +105,7 @@ not every later human edit. A handoff is not reported as durable.
| `connect` | `from`, `to`; optional local `id`, `fromSide`, `toSide` (top/bottom/left/right) |
| `group` | `ids`; returns a new group ID |
| `ungroup` | `ids`, `groupId`; preserves other groups |
| `imageMetadata` | `id`, `label` (1–80 characters or `null` to clear), `tags` (up to 12 unique short strings or `null`) |
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG; optional `id`, `x`, `y`, `scale` (boolean) |
| `latex` | `text`; optional `id`, `x`, `y`, `scaleX`, `scaleY`; requires compatible enabled Extras MathJax |
@@ -119,7 +120,7 @@ tombstones and binding cleanup and does not delete attachment files.
## Read, render, and recover
`list` returns exact paths. `read` defaults to a summary without asset bodies;
`detail=elements` returns at most 50 elements per page (maximum 200). Use
`detail=elements` returns at most 50 elements per page (maximum 200); `detail=images` inventories placements, media types, loaded sizes (or unknown), existing labels/tags, and load state without base64. The inventory separates `loadedRenditionBytes` (decoded data-URL bytes) from `originalBytes` (known Vault attachment size); unknown values are `null`. It reports natural dimensions only when known from crop metadata. Use
`nextOffset` and the same `revision` for later pages. A changed snapshot returns
`STALE_REVISION`. `ids` filters explicit IDs and `selectedOnly` needs a live view.
@@ -141,8 +142,32 @@ asset. Source/revision, theme, byte count, and dimensions are returned. Live exp
does not save the drawing. Optional `theme` is light/dark, `padding` is 0–200
(default 10), `scale` is 0.1–4 for PNG (default 1), and `area` is an exact
`{x,y,width,height}` scene rectangle. Inspect the image before another revision.
Missing/undecoded assets fail explicitly. Existing remote assets use normal
plugin permissions and may require network access. Core shape/text and SVG/PNG
Missing originals fail explicitly. A request-only `imagePolicy` opts into per-image preview reduction before image loading and SVG construction; no policy means original fidelity. For example:
```json
{
"apiVersion": 1, "command": "export", "requestId": "overview-1",
"path": "Drawings/Flow.excalidraw.md", "source": "live", "out": "Previews/Flow.svg",
"imagePolicy": {
"default": "placeholder",
"rules": [
{ "ids": ["chosen-element-id"], "mode": "original" },
{ "tags": ["context"], "mode": "thumbnail" },
{ "mimeTypes": ["image/svg+xml"], "maxBytes": 65536, "mode": "original" }
],
"labels": { "another-element-id": "Context screenshot" },
"thumbnailMaxDimension": 512
},
"maxWidth": 1200, "maxHeight": 900, "maxPixels": 1000000,
"maxArtifactBytes": 4194304
}
```
Rules use AND across conditions and OR within each ID/tag/MIME list, first match wins. Unknown asset size does not match `maxBytes`; one rule must contain a matching condition. `default` is `original`, `thumbnail`, or `placeholder`. Placeholder labels come from request-only `labels`, then persisted namespaced metadata, then a short element ID. Set persisted `label`/`tags` with the guarded `apply` `imageMetadata` operation. The tool preserves unrelated `customData`, image placement, stacking and rotation, and never edits the source drawing during export.
Thumbnail resolution is distinct from PNG pixel output bounds: thumbnail generation preflights PNG/JPEG/WebP headers before decoding and refuses sources over 24 MiB, images over 16 million pixels, and formats with unknown dimensions. SVG, GIF, animated WebP, and unsupported headers require `original` or `placeholder`. Disk thumbnails require direct PNG/JPEG/WebP sources; use loaded live renditions for composite drawing/PDF/Markdown assets. Conversions run sequentially and release temporary images and canvases. Cropped thumbnails preserve the original crop; placeholder labels rotate and mirror with the image, within its visible footprint. Original images can still exceed the final 32 MiB SVG cap. `maxWidth`, `maxHeight`, and `maxPixels` bound output dimensions (including the intermediate PNG canvas); PNG can derive a scale below 0.1 to fit a requested bound. SVG dimensions change display size but do not reduce embedded image bytes. `maxArtifactBytes` (1 KiB–32 MiB) bounds final bytes, with an early embedded-payload preflight. The export receipt returns `effectiveScale`, representation counts, the first 50 per-element decisions with a total count, output bounds, a scene-to-preview mapping (including frame titles and padding), and a separate `representationId` describing the preview. The source `revision` always describes the full original content. Image annotations are descriptive metadata, not a trust signal.
Missing/undecoded assets fail explicitly when required by the chosen representation. Live previews use currently loaded content. Disk exports re-read consumed Vault attachments and compare content digests before publication, bypass cached drawing/PDF renditions, and refuse intervening Vault edits (including unrelated edits, conservatively). Disk exports refuse required remote or machine-local assets because those cannot participate in a Vault snapshot; use a loaded live source or placeholders. Live remote assets use normal plugin permissions and may require network access. Core shape/text and SVG/PNG
rendering work without Extras; optional features are never activated automatically.
Every write requires a unique 1–80 character `requestId` (letters, digits, `_`,
@@ -151,7 +176,7 @@ content with the same ID is rejected. Script source is part of that identity.
`result` can recover lost stdout or report `status: pending, ok: null`. Completed
receipts expire after 15 minutes; there are at most 128 in one plugin session.
Reload/expiry/unknown outcomes require read-back before issuing another write.
Competing CLI operations on the same target return `BUSY`; human editing remains
Competing CLI operations on the same target return `BUSY`; a refusal known to occur before lock acquisition can be retried with the *identical* requestId. An unexpected internal error is reported as `INTERNAL_ERROR` without leaking payloads or stack traces, and any possibly started write has an unknown outcome; read back before retrying. human editing remains
possible, so always refresh after `STALE_REVISION`.
Input is limited to 2 MiB and nesting to 30 levels; output to 512 KiB. Use either
+19
View File
@@ -238,6 +238,25 @@ and bytes. The separate text-undo scenario still requires the component fix
described above. Run one driver at a time; UI/CDP input also needs the intended
vault window to retain focus.
The native CLI lane also saves a light/dark SVG/PNG image-policy matrix in the
report's `image-previews/` directory before cleaning its Vault fixtures. It covers
shared-image originals, thumbnails and placeholders, crop/mirroring/rotation,
transparency, frame title bounds, source/dirty-state preservation, metadata clear
semantics, and an actual same-size/same-mtime
attachment replacement after disk asset preparation. No raced output may publish. Set `EXCALIDRAW_CLI_POPOUT=1` to add
popout inventory/export/teardown. This host currently reports ResizeObserver
notifications when closing even a blank drawing popout; the runner preserves
those errors and fails its clean-error gate rather than hiding them.
Set `EXCALIDRAW_CLI_LARGE_IDENTITY=1` for the explicit native identity stress:
387 synthetic file records hold more aggregate payload characters than V8's
maximum single-string length, including prepared descriptor payloads. It checks
stable read/pagination revisions, last-byte replacement, stale-apply refusal and
placeholder export, recording read timings and sampled JS heap usage. Its strings
share immutable backing storage; this is not a benchmark of 570 MB of independently
decoded real images, regenerated-equal payloads, peak memory or UI responsiveness.
Those measurements still require an image-heavy drawing copy in the test vault.
For LaTeX dialog input and window ownership (#2970), run:
```bash
+216 -2
View File
@@ -36,7 +36,7 @@ function harness({ supported = true, desktop = true, native = true } = {}) {
}
const protocol = load('src/core/cli/cliProtocol');
const { ExcalidrawCLI } = load('src/core/managers/ExcalidrawCLI');
return { manager: new ExcalidrawCLI(plugin), protocol, elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), plugin, registrations, versionChecks, files, View };
return { manager: new ExcalidrawCLI(plugin), protocol, elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks };
}
const request = (command, values = {}) => ({ apiVersion: 1, command, ...values });
@@ -92,7 +92,7 @@ test('portable skill stays aligned with native output and schema describes finit
assert.equal((await h.manager.execute(request('api', { name: 'addRect' }))).data.entries[0].description, '');
const schema = (await h.manager.execute(request('schema', { action: 'apply' }))).data.jsonSchema;
assert.ok(schema.required.includes('expectedRevision'));
assert.deepEqual(schema.$defs.operation.oneOf.map(option => option.properties.op.const), ['add', 'update', 'delete', 'connect', 'group', 'ungroup', 'image', 'latex']);
assert.deepEqual(schema.$defs.operation.oneOf.map(option => option.properties.op.const), ['add', 'update', 'delete', 'connect', 'group', 'ungroup', 'image', 'imageMetadata', 'latex']);
});
test('multiple views require explicit identity; disk ignores ambiguity and refuses view selection', async () => {
@@ -236,3 +236,217 @@ test('CLI compilation checks exact source even when file stat matches a cached m
file.content = 'new source'; assert.equal(await (await getCompiled.call(engine, file, 'new source'))(), 'new source');
await assert.rejects(getCompiled.call(engine, file, 'different'), /source changed/);
});
test('segmented live revisions retain immutable payloads and catch last-byte or descriptor changes', () => {
const h = harness();
const dataURL = 'data:image/png;base64,' + 'a'.repeat(2 * 1024 * 1024);
const file = { id: 'asset', mimeType: 'image/png', dataURL, created: 1 };
const element = { id: 'img', type: 'image', fileId: 'asset', version: 1, isDeleted: false };
const embedded = { img: dataURL, imgInverted: dataURL, mtime: 2 };
const model = { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(),
exportPreparedSaveData: () => ({ files: new Map([['asset', embedded]]) }) };
const files = { asset: file };
const view = new h.View();
Object.assign(view, { id: 'view-1', file: h.files[0], excalidrawData: model,
excalidrawAPI: { getSceneElementsIncludingDeleted: () => [element], getFiles: () => files },
getScene: () => ({ appState: { theme: 'light' } }), data: 'markdown', textMode: 'raw', plugin: { settings: { use: true } },
isLoaded: true, isClosingOrMigrating: () => false });
const targets = h.manager.targets;
const original = targets.revision(view);
assert.equal(targets.revision(view), original);
file.dataURL = dataURL.slice(0, -1) + 'b';
const replaced = targets.revision(view);
assert.notEqual(replaced, original);
assert.equal(targets.revision(view), replaced);
embedded.imgInverted = dataURL.slice(0, -1) + 'c';
assert.notEqual(targets.revision(view), replaced);
const beforeSettings = targets.revision(view);
view.plugin.settings.use = false;
assert.notEqual(targets.revision(view), beforeSettings);
const beforeApi = targets.revision(view);
view.excalidrawAPI = { ...view.excalidrawAPI };
assert.notEqual(targets.revision(view), beforeApi);
h.manager.destroy();
});
test('CLI image inventory and policy avoid data URLs, separate shared-symbol representations and reject malformed rules', async () => {
const h = harness();
const { parseImagePolicy, decideImage, imageInventory, prepareImagePreview } = h.images;
const file = { id: 'shared', dataURL: 'data:image/png;base64,QUJDRA==', mimeType: 'image/png', created: 0 };
const original = { id: 'original', type: 'image', fileId: 'shared', status: 'saved', x: 10, y: 12, width: 200, height: 100, angle: 0.5, opacity: 80, scale: [-1, 1], crop: null, customData: { excalidrawCLI: { version: 1, tags: ['context'] } } };
const copy = { ...original, id: 'placeholder', customData: { excalidrawCLI: { version: 1, label: '<& 安全>' } } };
const policy = parseImagePolicy({ default: 'placeholder', rules: [{ ids: ['original'], mode: 'original' }], thumbnailMaxDimension: 512 });
const a = decideImage(original, file, policy), b = decideImage(copy, file, policy);
assert.equal(a.mode, 'original'); assert.equal(b.mode, 'placeholder');
assert.equal(imageInventory(original, file).loadedRenditionBytes, 4);
assert.equal(imageInventory(original, file).tags[0], 'context');
assert.equal(imageInventory({ ...original, status: undefined }, file).status, null);
const preview = await prepareImagePreview([original, copy], { shared: file }, policy, new Map([[a.elementId, a], [b.elementId, b]]));
assert.equal(preview.elements[0].fileId, 'shared');
assert.notEqual(preview.elements[1].fileId, 'shared');
assert.equal(preview.elements[1].crop, null);
assert.equal(preview.elements[1].x, copy.x); assert.equal(preview.elements[1].angle, copy.angle);
assert.deepEqual(preview.elements[1].scale, copy.scale);
const previewPayload = preview.files[preview.elements[1].fileId].dataURL;
const xml = atob(previewPayload.split(',')[1]);
assert.match(xml, /&#60;&#38;/); assert.doesNotMatch(xml, /<script/);
assert.equal(file.dataURL, 'data:image/png;base64,QUJDRA==');
assert.throws(() => parseImagePolicy({ default: 'auto' }));
assert.throws(() => parseImagePolicy({ rules: [{ mode: 'original' }] }));
assert.throws(() => parseImagePolicy({ rules: Array(33).fill({ ids: ['x'], mode: 'original' }) }));
});
test('schema distinguishes insertion boolean scale from export number scale and validates metadata fields', async () => {
const h = harness();
const result = await h.manager.execute(request('schema', { action: 'apply' }));
const operations = result.data.jsonSchema.$defs.operation.oneOf;
assert.equal(operations.find(op => op.properties.op.const === 'image').properties.scale.type, 'boolean');
assert.equal(operations.find(op => op.properties.op.const === 'imageMetadata').properties.tags.anyOf[1].maxItems, 12);
assert.deepEqual(operations.find(op => op.properties.op.const === 'imageMetadata').anyOf, [{ required: ['label'] }, { required: ['tags'] }]);
assert.equal((await h.manager.execute(request('schema', { action: 'create' }))).data.jsonSchema.$defs.skeleton.properties.label.type, 'object');
assert.equal((await h.manager.execute(request('schema', { action: 'export' }))).data.jsonSchema.properties.scale.type, 'number');
assert.doesNotThrow(() => h.apply.validateOperations([{ op: 'image', asset: 'images/a.png', scale: true }]));
assert.throws(() => h.apply.validateOperations([{ op: 'image', asset: 'images/a.png', scale: 1 }]));
assert.throws(() => h.apply.validateOperations([{ op: 'imageMetadata', id: 'img', tags: ['x', 'x'] }]));
});
test('BUSY before lock retries the same canonical ID while pending/failed and mismatched writes never repeat', async () => {
const h = harness(); let calls = 0;
h.manager.writes.execute = async () => {
calls++;
if (calls === 1) throw new h.protocol.CLIError('BUSY', 'pre-execution refusal', 'path', 'Retry identical request.', {}, true);
return { mutation: 'applied', persistence: 'saved', data: { calls } };
};
const input = request('create', { requestId: 'busy1', path: 'new.excalidraw.md', elements: [] });
const first = await h.manager.execute(input); assert.equal(first.error.code, 'BUSY');
assert.equal((await h.manager.execute({ ...input, path: 'different.excalidraw.md' })).error.field, 'requestId');
const second = await h.manager.execute(input); assert.equal(second.ok, true);
assert.equal(second.data.calls, 2);
assert.deepEqual(await h.manager.execute(input), second); assert.equal(calls, 2);
h.manager.writes.execute = async () => { throw Error('private: image data; TOKEN-123'); };
const err = await h.manager.execute(request('create', { requestId: 'boom1', path: 'new.excalidraw.md', elements: [] }));
assert.equal(err.error.code, 'INTERNAL_ERROR'); assert.equal(err.mutation, 'unknown');
assert.equal(err.persistence, 'unknown'); assert.doesNotMatch(JSON.stringify(err), /TOKEN-123/);
});
test('summary, image inventory and paged elements avoid cloning original file payloads', async () => {
const h = harness(); const bigURL = 'data:image/png;base64,' + 'A'.repeat(8 * 1024 * 1024);
const element = { id: 'img12345', fileId: 'large', type: 'image', status: 'saved', isDeleted: false,
x: 0, y: 0, width: 100, height: 80, angle: 0, opacity: 100, scale: [1, 1], crop: null, customData: {} };
const files = { large: { id: 'large', dataURL: bigURL, mimeType: 'image/png', created: 0 } };
const view = Object.assign(new h.View(), { id: 'view-1', file: h.files[0], isLoaded: true, isClosingOrMigrating: () => false,
isDirty: () => false, textMode: 'raw', data: '', plugin: { settings: {} },
excalidrawAPI: { getSceneElementsIncludingDeleted: () => [element], getFiles: () => files, getAppState: () => ({ selectedElementIds: {} }) },
excalidrawData: { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(), getFileEntries: () => [],
exportPreparedSaveData: () => ({ files: new Map([['large', { img: bigURL, imgInverted: bigURL }]]) }) },
getScene: () => ({ elements: [element], files, appState: {} }) });
h.plugin.app.workspace.getLeavesOfType = () => [{ view }];
const originalClone = globalThis.structuredClone;
globalThis.structuredClone = input => {
if (input && (input.files || input.elements)) assert.fail('Unexpected full-scene clone');
return originalClone(input);
};
try {
const summary = await h.manager.execute(request('read', { path: view.file.path, source: 'live' }));
assert.equal(summary.ok, true); assert.equal(summary.data.total, 1);
const images = await h.manager.execute(request('read', { path: view.file.path, source: 'live', detail: 'images' }));
assert.equal(images.ok, true); assert.equal(images.data.images[0].loadedRenditionBytes, 6 * 1024 * 1024);
assert.equal(JSON.stringify(images).includes(bigURL), false);
const page = await h.manager.execute(request('read', { path: view.file.path, source: 'live', detail: 'elements' }));
assert.equal(page.ok, true); assert.equal(page.data.elements[0].id, element.id);
assert.equal(page.data.revision, summary.data.revision);
} finally { globalThis.structuredClone = originalClone; }
});
test('derived PNG dimensions honor requested caps and existing hard limits', () => {
const { exporting: { previewScale, exportBounds } } = harness();
assert.equal(previewScale(4000, 2000, 1, 1000, 1000, 2000000), 0.25);
assert.ok(previewScale(20000, 20000, 1, 100, 100, 10000) < 0.1);
assert.throws(() => previewScale(500, 500, 1, undefined, undefined, 0));
assert.throws(() => exportBounds(100000, 100000, 1));
});
test('disk dependencies detect same-stat replacements, restoration, deletion and unload, and release listeners', async () => {
const { dependencies: { CLIDiskDependencies } } = harness();
const file = { path: 'image.png', stat: { size: 4, mtime: 1 } };
let bytes = Uint8Array.of(1, 2, 3, 4), current = true;
const listeners = new Map();
const vault = { getFileByPath: () => file, readBinary: async () => bytes.slice().buffer,
on: (event, fn) => { listeners.set(event, fn); return event; }, offref: event => listeners.delete(event) };
const guard = new CLIDiskDependencies(vault, () => current);
await guard.observe(file); await guard.validate();
bytes[3] = 5;
await assert.rejects(guard.validate(), error => error.code === 'STALE_REVISION');
bytes[3] = 4;
await guard.validate();
listeners.get('modify')(file);
await assert.rejects(guard.validate(), error => error.code === 'STALE_REVISION');
guard.destroy(); guard.destroy(); assert.equal(listeners.size, 0);
const second = new CLIDiskDependencies(vault, () => current);
current = false;
await assert.rejects(second.observe(file), error => error.code === 'NOT_READY');
second.destroy(); assert.equal(listeners.size, 0);
});
test('thumbnail preflight rejects huge and unknown raster dimensions before creating or decoding an image', async () => {
const { dimensions: { thumbnailDimensions }, images } = harness();
const png = (width, height) => {
const bytes = Buffer.alloc(24);
Buffer.from('\x89PNG\r\n\x1a\n', 'latin1').copy(bytes);
bytes.write('IHDR', 12); bytes.writeUInt32BE(width, 16); bytes.writeUInt32BE(height, 20);
return 'data:image/png;base64,' + bytes.toString('base64');
};
assert.deepEqual(thumbnailDimensions(png(400, 200)), { width: 400, height: 200 });
for (const url of [png(100000, 100000), png(0, 1), 'data:image/svg+xml;base64,' + btoa('<svg/>')]) {
assert.throws(() => thumbnailDimensions(url), error => error.code === 'ASSETS_UNAVAILABLE');
}
const element = { type: 'image', id: 'large', fileId: 'file', width: 100, height: 100 };
const file = { id: 'file', dataURL: png(100000, 100000), mimeType: 'image/png' };
const policy = images.parseImagePolicy({ default: 'thumbnail' });
await assert.rejects(images.prepareImagePreview([element], { file }, policy, new Map()), error => error.code === 'ASSETS_UNAVAILABLE');
});
test('real export preparation omits replaced payloads and refuses concurrent live edits and omitted attachment collisions', async () => {
const h = harness(); let rendered, writes = 0, changeDuringRender = false;
const element = { type: 'image', id: 'image001', fileId: 'file001', x: 0, y: 0, width: 80, height: 40, angle: 0, isDeleted: false };
const files = { file001: { id: 'file001', mimeType: 'image/png', dataURL: 'data:image/png;base64,QUJDRA==', created: 1 } };
const model = { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(), exportPreparedSaveData: () => ({ files: [] }), getFileEntries: () => [['file001', { file: { path: 'attachment.svg' } }]] };
const view = Object.assign(new h.View(), { id: 'view001', file: h.files[0], isLoaded: true, isClosingOrMigrating: () => false,
textMode: 'raw', data: '', plugin: { settings: {} }, excalidrawData: model,
excalidrawAPI: { getSceneElementsIncludingDeleted: () => [element], getFiles: () => files },
getScene: () => ({ elements: [element], files, appState: {} }), getViewExportTheme: () => 'light' });
h.plugin.app.workspace.getLeavesOfType = () => [{ view }];
h.plugin.getCLIRuntime = () => ({ getCommonBounds: () => [0, 0, 80, 40] });
h.plugin.app.vault.getAbstractFileByPath = () => null;
h.plugin.app.vault.createBinary = async () => { writes++; };
h.mocks['src/utils/fileUtils'].checkAndCreateFolder = async () => {};
h.mocks['src/utils/utils'].getSVG = async scene => {
rendered = scene;
if (changeDuringRender) element.x++;
return { getAttribute: key => key === 'width' ? '100' : '60', setAttribute() {}, outerHTML: '<svg width="100" height="60"/>' };
};
const request = { path: view.file.path, source: 'live', out: 'preview.svg', imagePolicy: { default: 'placeholder' } };
const result = await h.exporting.exportDrawing(h.manager, request, request.out);
assert.equal(writes, 1); assert.equal(result.data.imageSummary.placeholder, 1);
assert.equal(Object.values(rendered.files).some(file => file.dataURL === files.file001.dataURL), false);
assert.notEqual(rendered.elements[0].fileId, element.fileId);
assert.equal(element.fileId, 'file001');
changeDuringRender = true;
await assert.rejects(h.exporting.exportDrawing(h.manager, request, request.out), error => error.code === 'STALE_REVISION');
assert.equal(writes, 1);
await assert.rejects(h.exporting.exportDrawing(h.manager, { ...request, out: 'attachment.svg' }, 'attachment.svg'), error => error.code === 'INVALID_INPUT');
assert.equal(writes, 1);
});
test('image metadata edits preserve namespace extensions and refuse forward versions', () => {
const { customData: { cliImageMetadataPatch } } = harness();
const element = { type: 'image', customData: { other: { preserved: true }, excalidrawCLI: { version: 1, label: 'Before', tags: ['detail'], future: { preserved: true } } } };
const patched = cliImageMetadataPatch(element, null, undefined);
assert.equal(patched.excalidrawCLI.label, undefined);
assert.deepEqual(patched.excalidrawCLI.tags, ['detail']);
assert.deepEqual(patched.excalidrawCLI.future, { preserved: true });
assert.deepEqual(patched.other, element.customData.other);
assert.equal(element.customData.excalidrawCLI.label, 'Before');
assert.throws(() => cliImageMetadataPatch({ ...element, customData: { excalidrawCLI: { version: 2 } } }, 'New', undefined), /Unsupported/);
});
+127
View File
@@ -0,0 +1,127 @@
/** Native #3004 image policies, real renderer geometry and request-owned race fixtures. */
import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { runCLILargeIdentity } from './cliLargeIdentity.mjs';
export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_images';
assert.ok(prefix.split('/').at(-1).startsWith('__excalidraw_cli_smoke_'));
const paths = { drawing: `${prefix}.excalidraw.md`, raster: `${prefix}_source.png`, icon: `${prefix}_icon.svg`, request: `${prefix}.json` };
const outputs = [], artifacts = []; let largeIdentity;
const control = '__excalidrawImagePreviewRegression';
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
const action = (command, values = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...values })}`));
const ok = result => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
const id = suffix => `${prefix.split('/').at(-1).slice(-38)}-${suffix}`;
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
const read = (detail = 'images') => { const result = action('read', { path: paths.drawing, source: 'live', detail }); if (!result.ok) throw Error(JSON.stringify({detail,result})); return result.data; };
const artifactDir = reportDir ? join(reportDir, 'image-previews') : null;
if (artifactDir) mkdirSync(artifactDir, { recursive: true });
const preserve = (out, name) => {
const data = evaluate(`(async()=>{const b=new Uint8Array(await app.vault.readBinary(app.vault.getFileByPath(${JSON.stringify(out)})));let s='';for(const v of b)s+=String.fromCharCode(v);return JSON.stringify({base64:btoa(s)})})()`);
if (artifactDir) writeFileSync(join(artifactDir, name), Buffer.from(data.base64, 'base64'));
};
try {
evaluate(`(async()=>{const c=createFragment().createEl('canvas');c.width=320;c.height=160;const x=c.getContext('2d');x.fillStyle='#ff0000';x.fillRect(0,0,160,80);x.fillStyle='#00ff00';x.fillRect(160,0,160,80);x.fillStyle='#0000ff';x.fillRect(0,80,160,80);x.fillStyle='#ffff00';x.fillRect(160,80,160,80);x.clearRect(135,55,50,50);const blob=await new Promise(r=>c.toBlob(r));await app.vault.createBinary(${JSON.stringify(paths.raster)},await blob.arrayBuffer());c.width=c.height=0;await app.vault.create(${JSON.stringify(paths.icon)},'<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"><circle cx="24" cy="24" r="21" fill="#9c36b5"/></svg>');return JSON.stringify({created:true})})()`);
ok(action('create', { requestId: id('create'), path: paths.drawing, elements: [] }));
ok(action('open', { path: paths.drawing }));
const inserted = ok(action('apply', { requestId: id('insert'), path: paths.drawing, expectedRevision: read().revision, operations: [
{ op: 'image', id: 'raster', asset: paths.raster, x: 20, y: 20, scale: false },
{ op: 'image', id: 'icon', asset: paths.icon, x: 600, y: 240, scale: false },
] }));
const rasterId = inserted.data.idMap.raster;
evaluate(`(async()=>{const v=${viewCode},a=v.excalidrawAPI,es=structuredClone(a.getSceneElements()),e=es.find(e=>e.id===${JSON.stringify(rasterId)});e.width=200;e.height=100;e.customData={preserved:'yes'};const copies=[{id:'crop0001',x:260,y:20,crop:{x:80,y:40,width:160,height:80,naturalWidth:320,naturalHeight:160}},{id:'flip0001',x:20,y:170,scale:[-1,1]},{id:'turn0001',x:260,y:180,angle:0.5,opacity:65},{id:'frameimg',x:510,y:20,frameId:'frame001',angle:0.2}].map((p,i)=>({...e,...p,version:1,seed:700+i,versionNonce:800+i}));const frame=app.plugins.plugins['obsidian-excalidraw-plugin'].getCLIRuntime().convertToExcalidrawElements([{id:'frame001',type:'frame',x:520,y:10,width:140,height:140,name:'Clipping',children:[]}])[0];for(const copy of copies)if(copy.frameId==='frame001')copy.frameId=frame.id;v.updateScene({elements:[...es,...copies,frame],captureUpdate:'IMMEDIATELY'});await v.saveWithOutcome();return JSON.stringify({ready:true})})()`);
ok(action('apply', { requestId: id('labels'), path: paths.drawing, expectedRevision: read().revision, operations: [
{ op: 'imageMetadata', id: rasterId, label: 'Red & <green> 安全', tags: ['detail'] },
{ op: 'imageMetadata', id: 'crop0001', label: 'Cropped', tags: ['context'] },
] }));
const annotated = read();
assert.equal(annotated.images.length, 6);
assert.ok(annotated.images.find(e => e.elementId === rasterId).loadedRenditionBytes > 0);
assert.ok(annotated.images.find(e => e.elementId === rasterId).originalBytes > 0);
assert.equal(JSON.stringify(annotated).includes('data:image'), false);
const sourceState = () => evaluate(`(async()=>{const v=${viewCode};return JSON.stringify({text:await app.vault.read(v.file),elements:JSON.stringify(v.excalidrawAPI.getSceneElements()),dirty:v.isDirty()})})()`);
const before = sourceState();
const mixed = { default: 'placeholder', rules: [{ ids: [rasterId], mode: 'original' }, { tags: ['context'], mode: 'thumbnail' }, { mimeTypes: ['image/svg+xml'], maxBytes: 65536, mode: 'original' }], labels: { flip0001: 'Mirror & <context> 中文' }, thumbnailMaxDimension: 128 };
for (const theme of ['light', 'dark']) for (const format of ['svg', 'png']) for (const mode of ['original', 'placeholder', 'mixed']) {
const name = `${theme}-${mode}.${format}`, out = `${prefix}_${name}`; outputs.push(out);
const imagePolicy = mode === 'original' ? undefined : mode === 'mixed' ? mixed : { default: 'placeholder' };
const result = ok(action('export', { requestId: id(`${theme}-${format}-${mode}`), path: paths.drawing, source: 'live', out, theme, maxWidth: 900, maxHeight: 700, maxPixels: 500000, maxArtifactBytes: 2000000, ...(imagePolicy ? { imagePolicy } : {}) }));
assert.ok(result.data.width <= 900 && result.data.height <= 700);
assert.ok(result.data.width * result.data.height <= 500000);
assert.ok(Math.abs(result.data.sceneToPreview.sceneBounds.y + 20.5) < 0.00001, 'Frame label must be included in scene-to-preview origin');
if (format === 'svg') assert.equal(result.data.sceneToPreview.sceneBounds.height * result.data.effectiveScale, result.data.height);
assert.ok(result.data.representationId.startsWith('preview:'));
if (mode === 'mixed') assert.deepEqual(result.data.imageSummary, { original: 2, thumbnail: 1, placeholder: 3 });
if (mode === 'placeholder' && format === 'svg') {
const check = evaluate(`(async()=>{const v=${viewCode},s=await app.vault.read(app.vault.getFileByPath(${JSON.stringify(out)})),d=new DOMParser().parseFromString(s,'image/svg+xml');return JSON.stringify({valid:!d.querySelector('parsererror'),omitted:Object.values(v.excalidrawAPI.getFiles()).every(f=>!s.includes(f.dataURL)),images:d.querySelectorAll('image').length})})()`);
assert.equal(check.valid, true); assert.equal(check.omitted, true); assert.ok(check.images > 0);
}
artifacts.push({ name, ...result.data }); preserve(out, name);
}
assert.deepEqual(sourceState(), before, 'Preview export changed the source or dirty state');
if (process.env.EXCALIDRAW_CLI_LARGE_IDENTITY === '1') {
const out = `${prefix}_large.svg`; outputs.push(out);
largeIdentity = await runCLILargeIdentity({ evaluate, viewCode, path: paths.drawing, out, requestId: id('large') });
assert.deepEqual(sourceState(), before, 'Large identity probe changed the real source');
}
if (process.env.EXCALIDRAW_CLI_POPOUT === '1') {
evaluate(`(async()=>{const leaf=app.workspace.openPopoutLeaf();await leaf.setViewState({type:'excalidraw',state:{file:${JSON.stringify(paths.drawing)}},active:true});return JSON.stringify({opened:true})})()`);
let popout;
for (let i = 0; i < 100; i++) {
popout = evaluate(`JSON.stringify(app.workspace.getLeavesOfType('excalidraw').map(l=>l.view).filter(v=>v.file?.path===${JSON.stringify(paths.drawing)}&&v.containerEl.ownerDocument!==app.workspace.containerEl.ownerDocument&&v.isLoaded&&v.excalidrawAPI).map(v=>({id:v.id}))[0]||null)`);
if (popout) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
assert.ok(popout?.id, 'Popout image drawing did not initialize');
const popRead = ok(action('read', { path: paths.drawing, source: 'live', view: popout.id, detail: 'images' }));
assert.equal(popRead.data.images.length, 6);
const popOut = `${prefix}_popout.png`; outputs.push(popOut);
ok(action('export', { requestId: id('popout'), path: paths.drawing, source: 'live', view: popout.id, out: popOut, imagePolicy: { default: 'placeholder' }, maxWidth: 400, maxHeight: 200, maxPixels: 60000 }));
preserve(popOut, 'popout-placeholder.png');
evaluate(`(async()=>{const leaf=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.id===${JSON.stringify(popout.id)});await leaf.setViewState({type:'empty',state:{}});leaf.detach();return JSON.stringify({closed:true})})()`);
assert.equal(action('read', { path: paths.drawing, source: 'live', view: popout.id }).error.code, 'NOT_FOUND');
for (let i = 0; i < 100; i++) {
if (evaluate(`JSON.stringify({ready:!!(${viewCode})?.isLoaded&&!(${viewCode})?.isClosingOrMigrating()})`).ready) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
}
// Thumbnail and original must map the same cropped/rotated/mirrored pixels.
for (const source of ['live', 'disk']) {
const out = `${prefix}_${source}_thumb.png`; outputs.push(out);
const rendered = ok(action('export', { requestId: id(`${source}-thumb`), path: paths.drawing, source, out, theme: 'light', imagePolicy: { default: 'thumbnail', rules: [{ ids: [inserted.data.idMap.icon], mode: 'placeholder' }], thumbnailMaxDimension: 128 }, maxWidth: 900 }));
artifacts.push({ name: `${source}-thumbnails.png`, ...rendered.data }); preserve(out, `${source}-thumbnails.png`);
}
const cleared = ok(action('apply', { requestId: id('clear'), path: paths.drawing, expectedRevision: read().revision, operations: [{ op: 'imageMetadata', id: rasterId, label: null }] }));
assert.equal(cleared.persistence, 'saved');
const metadata = ok(action('read', { path: paths.drawing, detail: 'elements' })).data.elements.find(e => e.id === rasterId).customData;
assert.equal(metadata.preserved, 'yes'); assert.equal(metadata.excalidrawCLI.label, undefined); assert.deepEqual(metadata.excalidrawCLI.tags, ['detail']);
// File transport and complete-asset overwrite protection, including omitted originals.
evaluate(`(async()=>{await app.vault.create(${JSON.stringify(paths.request)},${JSON.stringify(JSON.stringify({ apiVersion: 1, command: 'export', requestId: id('asset-collision'), path: paths.drawing, out: paths.raster, overwrite: true, imagePolicy: { default: 'placeholder' } }))});return JSON.stringify({ready:true})})()`);
assert.equal(JSON.parse(cli('obsidian-excalidraw-plugin:export', `input=${paths.request}`)).error.code, 'INVALID_INPUT');
// Pause after disk assets have loaded, then perform a real same-size attachment replacement.
const raced = `${prefix}_race.svg`; outputs.push(raced);
evaluate(`(()=>{if(globalThis.${control})throw Error('controller exists');const v=app.vault,c={vault:v,read:v.read,count:0};globalThis.${control}=c;c.gate=new Promise(r=>c.release=r);v.read=async function(f){if(f.path===${JSON.stringify(paths.drawing)}&&++c.count===3){c.waiting=true;await c.gate}return c.read.call(this,f)};app.plugins.plugins['obsidian-excalidraw-plugin'].executeCLI(${JSON.stringify({ apiVersion: 1, command: 'export', requestId: id('race'), path: paths.drawing, source: 'disk', out: raced })}).then(r=>c.result=r);return JSON.stringify({started:true})})()`);
let waiting = false;
for (let i = 0; i < 100; i++) {
waiting = evaluate(`JSON.stringify({waiting:!!globalThis.${control}?.waiting,result:globalThis.${control}?.result})`).waiting;
if (waiting) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
assert.equal(waiting, true, 'Disk export did not reach the post-loader race gate');
evaluate(`(async()=>{const c=globalThis.${control},v=app.vault,f=v.getFileByPath(${JSON.stringify(paths.raster)}),b=await v.readBinary(f);c.source=f;c.bytes=b.slice(0);c.stat={...f.stat};new Uint8Array(b)[b.byteLength-1]^=1;await v.adapter.writeBinary(f.path,b,{mtime:c.stat.mtime,ctime:c.stat.ctime});Object.assign(f.stat,c.stat);c.release();return JSON.stringify({replaced:true})})()`);
let race;
for (let i = 0; i < 100; i++) {
race = evaluate(`JSON.stringify({result:globalThis.${control}?.result})`).result;
if (race) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
assert.equal(race?.error?.code, 'STALE_REVISION', JSON.stringify(race));
assert.equal(evaluate(`JSON.stringify({exists:!!app.vault.getFileByPath(${JSON.stringify(raced)})})`).exists, false);
evaluate(`(async()=>{const c=globalThis.${control};c.vault.read=c.read;await c.vault.adapter.writeBinary(c.source.path,c.bytes,{mtime:c.stat.mtime,ctime:c.stat.ctime});Object.assign(c.source.stat,c.stat);delete globalThis.${control};return JSON.stringify({restored:true})})()`);
return { status: 'passed', assertions: ['shared image original/thumbnail/placeholder identities', 'crop, mirroring, rotation, opacity, frame membership and title bounds', 'transparent PNG and SVG icon, light/dark', 'XML/Unicode labels', 'complete SVG omits original payloads', 'source text/elements/dirty unchanged', 'metadata clear preserves tags and customData', 'live/disk thumbnails', 'file transport and omitted-asset overwrite refusal', 'same-size same-mtime disk attachment race refuses publication'], artifacts, popoutCoverage: process.env.EXCALIDRAW_CLI_POPOUT === '1' ? 'passed' : 'not run (set EXCALIDRAW_CLI_POPOUT=1)', ...(largeIdentity ? { largeIdentity } : {}) };
} finally {
evaluate(`(async()=>{const c=globalThis.${control};if(c){c.vault.read=c.read;c.release();if(c.bytes)await c.vault.adapter.writeBinary(c.source.path,c.bytes);delete globalThis.${control}}for(const path of ${JSON.stringify([...Object.values(paths), ...outputs])}){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe cleanup');for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await l.setViewState({type:'empty',state:{}});l.detach()}const f=app.vault.getFileByPath(path);if(f)await app.vault.delete(f)}return JSON.stringify({clean:true})})()`);
}
}
+32
View File
@@ -0,0 +1,32 @@
/** Explicit native beyond-string-limit identity stress without large bitmap decoding. */
import assert from 'node:assert/strict';
export async function runCLILargeIdentity({ evaluate, viewCode, path, out, requestId }) {
const control = '__excalidrawLargeCLIIdentity';
const result = evaluate(`(async()=>{
if(globalThis.${control})throw Error('large identity controller exists');
const v=${viewCode},a=v.excalidrawAPI,m=v.excalidrawData,p=app.plugins.plugins['obsidian-excalidraw-plugin'];
const c={api:a,model:m,getFiles:a.getFiles,exportData:m.exportPreparedSaveData};globalThis.${control}=c;
try {
const original=a.getFiles(),files={...original},body='A'.repeat(2*1024*1024),metadata=c.exportData.call(m);
const keys=Object.keys(original);while(keys.length<387)keys.push('stress'+String(keys.length).padStart(4,'0'));
const descriptors=new Map(metadata.files);
for(let i=0;i<keys.length;i++){const id=keys[i],url='data:image/png;base64,'+body+String(i).padStart(8,'0');files[id]={...(files[id]||{id,mimeType:'image/png',created:1}),dataURL:url};descriptors.set(id,{...(descriptors.get(id)||{}),img:url,imgInverted:url})}
a.getFiles=()=>files;m.exportPreparedSaveData=()=>({...metadata,files:descriptors});
const samples=[],read=async detail=>{const start=performance.now();const r=await p.executeCLI({apiVersion:1,command:'read',path:${JSON.stringify(path)},source:'live',...(detail?{detail}: {})});samples.push({detail:detail||'summary',ms:performance.now()-start,heapBytes:performance.memory?.usedJSHeapSize??null});if(!r.ok)throw Error(JSON.stringify(r));return r};
const first=await read(),second=await read(),inventory=await read('images'),page=await read('elements');
if(first.data.revision!==second.data.revision||first.data.revision!==inventory.data.revision||first.data.revision!==page.data.revision)throw Error('unstable unchanged identity');
const id=keys[0],s=files[id].dataURL;files[id].dataURL=s.slice(0,-1)+(s.endsWith('0')?'1':'0');
const changed=await read();if(changed.data.revision===first.data.revision)throw Error('last-byte content edit did not invalidate revision');
const stale=await p.executeCLI({apiVersion:1,command:'apply',requestId:${JSON.stringify(requestId + '-stale')},path:${JSON.stringify(path)},expectedRevision:first.data.revision,operations:[{op:'imageMetadata',id:a.getSceneElements().find(e=>e.type==='image').id,label:'Must not publish'}]});
const preview=await p.executeCLI({apiVersion:1,command:'export',requestId:${JSON.stringify(requestId + '-export')},path:${JSON.stringify(path)},source:'live',out:${JSON.stringify(out)},imagePolicy:{default:'placeholder'},maxWidth:900,maxHeight:700,maxPixels:500000});
return JSON.stringify({files:keys.length,logicalPayloadCharacters:Object.values(files).reduce((n,f)=>n+f.dataURL.length,0),maxStringLength:require('buffer').constants.MAX_STRING_LENGTH,samples,stableRevision:true,lastByteInvalidated:true,staleCode:stale.error?.code,preview});
} finally {a.getFiles=c.getFiles;m.exportPreparedSaveData=c.exportData;delete globalThis.${control}}
})()`);
assert.equal(result.files, 387);
assert.ok(result.logicalPayloadCharacters > result.maxStringLength);
assert.equal(result.staleCode, 'STALE_REVISION');
assert.equal(result.preview.ok, true, JSON.stringify(result.preview));
assert.equal(result.preview.data.imageSummary.original, 0);
return { status: 'passed', kind: 'synthetic identity stress; shared immutable string backing, no large bitmap decoding or real-workload peak-memory claim', ...result };
}
+8 -3
View File
@@ -1,7 +1,8 @@
/** Native authoring round-trip on fixtures owned by the guarded parent runner. */
import assert from 'node:assert/strict';
import { runCLIImagePreviewScenario } from './cliImagePreview.mjs';
export async function runNativeCLIScenario({ cli, drawingPath }) {
export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_native_cli';
assert.ok(prefix.split('/').at(-1).startsWith('__excalidraw_cli_smoke_'));
const idPrefix = prefix.split('/').at(-1).slice(-40);
@@ -14,7 +15,7 @@ export async function runNativeCLIScenario({ cli, drawingPath }) {
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(leaf=>leaf.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
const control = '__excalidrawNativeCLIRegression';
let cleanup = false;
const artifacts = [];
const artifacts = []; let imagePreviews;
try {
for (const command of ['help', 'status', 'skill', 'list']) ok(action(command));
assert.equal(ok(action('schema', { action: 'apply' })).data.command, 'apply');
@@ -38,6 +39,7 @@ export async function runNativeCLIScenario({ cli, drawingPath }) {
ok(action('create', { requestId: `${idPrefix}-template`, path: paths.template, template: paths.drawing, elements: [{ id: 'new', type: 'text', text: 'Template addition', x: 0, y: 150 }] }));
assert.equal(evaluate(`(async()=>{const text=await app.vault.read(app.vault.getFileByPath(${JSON.stringify(paths.template)}));return JSON.stringify({preserved:text.includes('Template prose survives.')&&text.includes('Template addition')})})()`).preserved, true);
ok(action('open', { path: paths.drawing }));
await new Promise(resolve => setTimeout(resolve, 250));
const read = () => ok(action('read', { path: paths.drawing, source: 'live', detail: 'elements' })).data;
let live = read(); const label = live.elements.find(element => element.type === 'text' && element.text === 'Start');
const update = { requestId: `${idPrefix}-update`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'update', id: label.id, set: { text: 'Edited via native CLI', strokeColor: '#1971c2' } }] };
@@ -56,6 +58,7 @@ export async function runNativeCLIScenario({ cli, drawingPath }) {
await new Promise(resolve => setTimeout(resolve, 50));
}
assert.equal(delayed.error.code, 'STALE_REVISION'); assert.equal(delayed.mutation, 'not-applied');
assert.equal(action('apply', { ...update, requestId: `${idPrefix}-competing`, expectedRevision: live.revision }).error.code, 'STALE_REVISION', 'A pre-execution BUSY receipt must run the identical request once the lock is free');
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Edited via native CLI');
evaluate(`(()=>{delete globalThis.${control};return JSON.stringify({clean:true})})()`);
// Published edits survive a failed save receipt; no false durability claim.
@@ -85,6 +88,7 @@ export async function runNativeCLIScenario({ cli, drawingPath }) {
live = read();
const image = ok(action('apply', { requestId: `${idPrefix}-image`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'image', id: 'preview', asset: paths.png, x: 0, y: 200 }] })); assert.ok(image.data.idMap.preview);
assert.equal(ok(action('read', { path: paths.drawing, source: 'disk' })).data.types.image, 1);
imagePreviews = await runCLIImagePreviewScenario({ cli, drawingPath, reportDir });
write(paths.script, 'return {input:utils.input,source:utils.executionSource,converter:typeof utils.excalidrawLib.convertToExcalidrawElements};');
const scriptRequest = { requestId: `${idPrefix}-script`, script: paths.script, trusted: true, args: { x: 0, text: '${literal}' } };
const script = ok(action('script', scriptRequest)); assert.equal(script.persistence, 'unknown'); assert.deepEqual(script.data.input, scriptRequest.args); assert.equal(script.data.source, 'cli');
@@ -94,11 +98,12 @@ export async function runNativeCLIScenario({ cli, drawingPath }) {
assert.equal(action('script', { ...scriptRequest, requestId: `${idPrefix}-prompt` }).error.code, 'INTERACTION_REQUIRED');
const close = evaluate(`(async()=>{for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}return JSON.stringify({closed:true})})()`); assert.equal(close.closed, true);
ok(action('open', { path: paths.drawing }));
await new Promise(resolve => setTimeout(resolve, 250));
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Recoverable edit');
} finally {
const result = evaluate(`(async()=>{const c=globalThis.${control};if(c){if(c.original)c.model.addTextElement=c.original;if(c.originalSave)c.view.saveWithOutcome=c.originalSave;c.release?.();delete globalThis.${control}}const paths=${JSON.stringify(Object.values(paths))};for(const path of paths){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe fixture cleanup');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`);
cleanup = result.clean;
}
assert.equal(cleanup, true);
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts };
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts, imagePreviews };
}
+1 -1
View File
@@ -156,7 +156,7 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf
report.scenarios.push({ id: "drawing-main-window", status: "passed", assertions: ["Excalidraw API ready", "wrapper mounted", "owner document matches", "main application document"] });
phase = "feature-scenarios";
for (const scenario of scenarios) {
report.scenarios.push(await scenario({ cli, drawingPath: drawing.path }));
report.scenarios.push(await scenario({ cli, drawingPath: drawing.path, reportDir }));
}
const errors = cli("dev:errors").trim();
if (errors && !/^No errors captured\.?$/i.test(errors)) throw new Error(`Captured JavaScript errors: ${errors.slice(0, 1000)}`);
+1 -1
View File
@@ -27,7 +27,7 @@ export class CLIWriteCommands {
const path = command === "script" && request.path === undefined ? vaultPath(request.script, "script") : vaultPath(request.path);
const out = command === "export" ? vaultPath(request.out, "out") : undefined;
const locks = [...new Set([path, ...(out ? [out] : [])])];
if (locks.some(key => this.inFlight.has(key))) throw new CLIError("BUSY", "Another CLI operation is running for this target.", "path");
if (locks.some(key => this.inFlight.has(key))) throw new CLIError("BUSY", "Another CLI operation is running for this target.", "path", "Retry the identical requestId when the target is free.", {}, true);
locks.forEach(key => this.inFlight.add(key));
try {
if (command === "create") return await this.create(path, request);
+14 -2
View File
@@ -6,11 +6,13 @@ import type { ConnectionPoint } from "src/types/types";
import { CLIError, boolean, number, object, string, vaultPath } from "./cliProtocol";
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validateStyle } from "./cliElements";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { cliImageMetadataPatch } from "src/utils/elementCustomDataUtils";
export const CLI_OPERATION_FIELDS: Record<string, string[]> = {
add: ["elements"], update: ["id", "set"], delete: ["ids", "children"],
connect: ["id", "from", "to", "fromSide", "toSide"], group: ["ids"], ungroup: ["ids", "groupId"],
image: ["id", "asset", "x", "y", "scale"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
image: ["id", "asset", "x", "y", "scale"], imageMetadata: ["id", "label", "tags"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
};
function ids(value: unknown): string[] {
@@ -35,6 +37,12 @@ export function validateOperations(input: unknown): Record<string, unknown>[] {
if (["delete", "group", "ungroup"].includes(op)) ids(operation.ids);
if (op === "delete" && operation.children !== undefined && !["delete", "detach"].includes(string(operation.children, "children"))) throw new CLIError("INVALID_INPUT", "Expected delete or detach.", "children");
if (op === "ungroup") string(operation.groupId, "groupId");
if (op === "imageMetadata") {
string(operation.id, "id");
if (operation.label === undefined && operation.tags === undefined) throw new CLIError("INVALID_INPUT", "Supply label or tags to update.", "imageMetadata");
if (operation.label !== undefined && operation.label !== null && (typeof operation.label !== "string" || !operation.label.trim() || operation.label.length > 80)) throw new CLIError("INVALID_INPUT", "Image label must be 1–80 characters or null.", "label");
if (operation.tags !== undefined && operation.tags !== null && (!Array.isArray(operation.tags) || operation.tags.length > 12 || operation.tags.some(tag => typeof tag !== "string" || !tag.trim() || tag.length > 32) || new Set(operation.tags).size !== operation.tags.length)) throw new CLIError("INVALID_INPUT", "Expected up to 12 unique short tags or null.", "tags");
}
if (op === "connect") { string(operation.from, "from"); string(operation.to, "to"); side(operation.fromSide); side(operation.toSide); }
if (["image", "latex"].includes(op)) {
number(operation.x, "x", 0, -1000000, 1000000); number(operation.y, "y", 0, -1000000, 1000000);
@@ -56,7 +64,7 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
const check = () => {
if (!cli.isCurrent() || view.file !== file || view.excalidrawAPI !== api || view.excalidrawData !== model || plugin.app.vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "Target identity changed during preparation.");
if (view.isSameFileEditingActive() || view.isPersistenceBusy()) throw new CLIError("BUSY", "Drawing is being edited as Markdown or synchronized.");
if (liveIdentity(view) !== identity) throw new CLIError("STALE_REVISION", "Drawing changed during preparation.", "expectedRevision", "Read the new scene before retrying.");
if (!sameCLIIdentity(liveIdentity(view), identity)) throw new CLIError("STALE_REVISION", "Drawing changed during preparation.", "expectedRevision", "Read the new scene before retrying.");
};
check(); ea.setView(view);
const originalElements = new Map(structuredClone(api.getSceneElements()).map(element => [element.id, element]));
@@ -92,6 +100,10 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
if (["arrow", "line", "freedraw"].includes(element.type) && ["width", "height"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Linear resizing requires a trusted EA script.", "set");
if ("text" in set) { set.rawText = set.text; set.originalText = set.text; }
lib.mutateElement(element, elementsMap, set);
} else if (op === "imageMetadata") {
const element = resolve(operation.id);
if (element.type !== "image") throw new CLIError("INVALID_INPUT", "Image annotations require an image element.", "id");
lib.mutateElement(element, elementsMap, { customData: cliImageMetadataPatch(element, operation.label, operation.tags) });
} else if (op === "delete") {
const removed = new Set(ids(operation.ids).map(id => resolve(id).id));
for (const id of [...removed]) {
+9 -6
View File
@@ -19,11 +19,11 @@ export const CLI_COMMANDS: Record<CLICommand, CommandDescriptor> = {
schema: { description: "Inspect one command's fields and side effects", fields: { action: "Command to describe" }, example: { action: "create" } },
api: { description: "Search EA documentation or the supported installed Lib reference", fields: { surface: "ea (default) or lib", name: "Exact method name", query: "Case-insensitive search" }, example: { surface: "ea", name: "addText" } },
list: { description: "List drawing paths without opening them", fields: { folder: "Optional exact folder", ...page }, example: { limit: 50 } },
read: { description: "Read an explicit live or disk drawing; no base64 asset bodies", fields: { ...target, ...source, ...page, detail: "summary (default) or elements", selectedOnly: "Live selection only", ids: "JSON array of element IDs" }, example: { path: "Drawings/Flow.excalidraw.md", source: "live", detail: "elements" } },
read: { description: "Read an explicit live or disk drawing; no base64 asset bodies", fields: { ...target, ...source, ...page, detail: "summary (default), elements, or images (asset metadata only)", selectedOnly: "Live selection only", ids: "JSON array of element IDs" }, example: { path: "Drawings/Flow.excalidraw.md", source: "live", detail: "elements" } },
open: { description: "Explicitly open a ready Excalidraw view; normal drawing scripts can run", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md" } },
create: { description: "Create an exact new path using EA's serializer; never overwrite", fields: { ...write, path: target.path, template: "Optional exact drawing template; no picker", elements: "Validated batch of installed Excalidraw skeletons" }, writes: true, example: { requestId: "flow-1", path: "Drawings/Flow.excalidraw.md", elements: [{ id: "a", type: "rectangle", x: 0, y: 0, width: 200, height: 80, label: { text: "Start" } }] } },
apply: { description: "Apply one bounded edit to an explicit live revision and report its save outcome", fields: { ...write, ...target, expectedRevision: "Fresh revision from live read", operations: "Array of add, update, delete, connect, group, ungroup, image, or latex operations" }, writes: true, example: { requestId: "flow-2", path: "Drawings/Flow.excalidraw.md", expectedRevision: "from-read", operations: [{ op: "update", id: "actual-id", set: { backgroundColor: "#e7f5ff" } }] } },
export: { description: "Render SVG/PNG to an explicit vault path; existing remote assets may use normal network permissions", fields: { ...write, ...target, ...source, out: "Exact .svg or .png output path", overwrite: "Explicit permission to replace an existing output", selectedOnly: "Live selection only", theme: "light or dark", padding: "0 to 200, default 10", scale: "PNG scale 0.1 to 4, default 1", area: "JSON object with x,y,width,height" }, writes: true, example: { requestId: "preview-1", path: "Drawings/Flow.excalidraw.md", out: "Drawings/Flow.png" } },
apply: { description: "Apply one bounded edit to an explicit live revision and report its save outcome", fields: { ...write, ...target, expectedRevision: "Fresh revision from live read", operations: "Array of add, update, delete, connect, group, ungroup, image, imageMetadata, or latex operations" }, writes: true, example: { requestId: "flow-2", path: "Drawings/Flow.excalidraw.md", expectedRevision: "from-read", operations: [{ op: "update", id: "actual-id", set: { backgroundColor: "#e7f5ff" } }] } },
export: { description: "Render SVG/PNG to an explicit vault path; existing remote assets may use normal network permissions", fields: { ...write, ...target, ...source, out: "Exact .svg or .png output path", overwrite: "Explicit permission to replace an existing output", selectedOnly: "Live selection only", theme: "light or dark", padding: "0 to 200, default 10", scale: "PNG scale 0.1 to 4, default 1", maxWidth: "Optional output maximum pixel width", maxHeight: "Optional output maximum pixel height", maxPixels: "Optional maximum output pixels", maxArtifactBytes: "Optional cap, 1024 to 33554432", imagePolicy: "Optional JSON {default,rules,thumbnailMaxDimension,labels}; no loss unless requested", area: "JSON object with x,y,width,height" }, writes: true, example: { requestId: "preview-1", path: "Drawings/Flow.excalidraw.md", out: "Drawings/Flow.png" } },
script: { description: "Run an explicitly trusted local EA script once; arbitrary code is not transactional or sandboxed", fields: { ...write, ...target, script: "Exact existing .md or enabled .js script path", trusted: "Required explicit true", args: "JSON passed as utils.input; never interpolated into code" }, writes: true, example: { requestId: "script-1", script: "Scripts/Inspect.md", trusted: true, args: {} } },
skill: { description: "Return offline portable agent instructions without installing them", fields: { format: "json (default) or markdown for native stdout" }, example: { format: "markdown" } },
result: { description: "Look up a session-only operation receipt after a client timeout", fields: { requestId: write.requestId }, example: { requestId: "flow-2" } },
@@ -58,14 +58,17 @@ All results use apiVersion 1. Check ok, mutation and persistence; process exit z
Put large requests in a visible vault-relative JSON file and pass input="<file>". Inline json is for small requests.
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY only after read-back.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
:result requestId=<id> recovers a receipt after lost stdout. Receipts expire after 15 minutes/reload; unknown outcome requires read-back before another write.
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Remote assets follow existing permissions.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
imageMetadata apply operations set bounded descriptive label/tags, with null clearing; request-only imagePolicy.labels does not persist. Thumbnail mode uses thumbnailMaxDimension=512 by default; only PNG/JPEG/WebP with safe preflight dimensions are decoded (24 MiB / 16 million pixels maximum).
maxWidth/maxHeight/maxPixels bound output dimensions; maxArtifactBytes caps final bytes. Source revision covers originals; representationId identifies the preview. SVG width controls display size, not embedded raster payload size; use imagePolicy for that.
Use :schema for exact fields, operation limits, and runnable examples. Do not edit compressed drawing Markdown directly or install another Excalidraw CLI.
`;
+65
View File
@@ -0,0 +1,65 @@
/** Request-owned content checks for disk exports; never trust attachment mtimes alone. */
import type { EventRef, TFile, Vault } from "obsidian";
import { CLIError } from "./cliProtocol";
/**
* Observe files before the loader consumes them (including nested drawings), and
* re-read their content before publication. Keep only per-file SHA-256 digests,
* process reads sequentially, and reject any intervening Vault mutation. This
* also catches a change followed by restoration while rendering. External edits
* without Vault events are detected by the final content read, even with equal stats.
*/
export class CLIDiskDependencies {
private files = new Map<string, { file: TFile; digest: string }>();
private refs: EventRef[];
private changed = false;
private disposed = false;
/** Optional policy-specific source check, invoked before the loader may decode it. */
public preflight?: (file: TFile, bytes: ArrayBuffer) => void;
public constructor(private readonly vault: Vault, private readonly isCurrent: () => boolean) {
const changed = () => { this.changed = true; };
this.refs = [vault.on("modify", changed), vault.on("delete", changed), vault.on("rename", changed)];
}
/** Fail synchronously after the final awaited read and immediately before writing. */
public assertCurrent(): void {
if (this.disposed || !this.isCurrent()) throw new CLIError("NOT_READY", "Disk export session ended.");
if (this.changed) throw new CLIError("STALE_REVISION", "Vault dependencies changed during disk rendering; retry from a fresh snapshot.");
}
private async digest(file: TFile): Promise<string> {
this.assertCurrent();
if (this.vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "A disk dependency was replaced.");
const bytes = await this.vault.readBinary(file);
this.preflight?.(file, bytes);
const digest = await crypto.subtle.digest("SHA-256", bytes);
this.assertCurrent();
if (this.vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "A disk dependency was replaced.");
return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
}
/** Invoked by the request's loader before every local source, never omitted images. */
public observe = async (file: TFile): Promise<void> => {
const digest = await this.digest(file), previous = this.files.get(file.path);
if (previous && (previous.file !== file || previous.digest !== digest)) throw new CLIError("STALE_REVISION", "Disk dependency content changed during rendering.");
this.files.set(file.path, { file, digest });
};
/** Content-aware validation covers same-size, same-mtime and last-byte replacements. */
public async validate(): Promise<void> {
for (const { file, digest } of this.files.values()) {
if (await this.digest(file) !== digest) throw new CLIError("STALE_REVISION", "Disk dependency content changed during rendering.");
}
this.assertCurrent();
}
/** Idempotent operation/unload cleanup releases every listener and captured handle. */
public destroy = (): void => {
this.disposed = true;
for (const ref of this.refs) this.vault.offref(ref);
this.refs = [];
this.files.clear();
this.preflight = undefined;
};
}
+138 -40
View File
@@ -1,22 +1,44 @@
/** Visual feedback through the existing asset loader and rendering helpers. */
/** Bounded CLI SVG/PNG export with request-local, opt-in image representations (#3004). */
import { TFile } from "obsidian";
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import type { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
import { getTemplate } from "src/utils/excalidrawAutomateUtils";
import { getSVG, getPNG } from "src/utils/utils";
import { checkAndCreateFolder } from "src/utils/fileUtils";
import { createExportAreaAnchor, getElementsIntersectionArea } from "src/utils/excalidrawElementUtils";
import { cropPNGBlob } from "src/utils/imageExportUtils";
import { CLIError, boolean, number, object, string } from "./cliProtocol";
import { CLIError, boolean, canonical, fingerprint, number, object, string } from "./cliProtocol";
import { diskSnapshot, drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { fields } from "./cliElements";
import { decideImage, parseImagePolicy, prepareImagePreview, type ImageDecision } from "./cliImages";
import { CLIDiskDependencies } from "./cliDependencies";
import { rasterDimensions } from "./cliImageDimensions";
import { frameExportGeometry } from "./cliExportGeometry";
/** Bounds limit allocation before rendering, including any area intermediate. */
export function exportBounds(width: number, height: number, scale: number): void {
if (![width, height].every(value => Number.isFinite(value) && value > 0 && value * scale <= 16384) || width * height * scale * scale > 16000000) throw new CLIError("INVALID_INPUT", "Export exceeds 16 million pixels or 16384 pixels on either side.");
}
/** Explicit output limits may derive a scale below 0.1; do not silently upscale. */
export function previewScale(width: number, height: number, scale: number, maxWidth?: number, maxHeight?: number, maxPixels?: number): number {
const effective = Math.min(scale, maxWidth === undefined ? Infinity : maxWidth / width,
maxHeight === undefined ? Infinity : maxHeight / height,
maxPixels === undefined ? Infinity : Math.sqrt(maxPixels / (width * height)));
if (!(effective > 0) || !Number.isFinite(effective)) throw new CLIError("INVALID_INPUT", "Invalid preview output bounds.");
exportBounds(width, height, effective);
return effective;
}
/** Filter geometry and retain existing stacking/order semantics. */
function scopedElements(elements: readonly ExcalidrawElement[], rectangle?: { x: number; y: number; width: number; height: number }): ExcalidrawElement[] {
const visible = elements.filter(element => !element.isDeleted);
return rectangle ? [...getElementsIntersectionArea(visible, rectangle, { includeBoundElements: true }), createExportAreaAnchor(rectangle)] : visible;
}
/** Does not save the source drawing; writes only an explicitly named image artifact. */
export async function exportDrawing(cli: ExcalidrawCLI, request: Record<string, unknown>, out: string): Promise<Partial<ExcalidrawCLIResult>> {
const plugin = cli.plugin, vault = plugin.app.vault, file = drawingFile(plugin, request.path);
@@ -37,90 +59,166 @@ export async function exportDrawing(cli: ExcalidrawCLI, request: Record<string,
if (current !== originalOutput || (current instanceof TFile && JSON.stringify(current.stat) !== outputStat)) throw new CLIError("STALE_REVISION", "Output changed during rendering.", "out");
};
const padding = number(request.padding, "padding", 10, 0, 200), scale = number(request.scale, "scale", 1, 0.1, 4);
const maxWidth = request.maxWidth === undefined ? undefined : number(request.maxWidth, "maxWidth", 16384, 1, 16384);
const maxHeight = request.maxHeight === undefined ? undefined : number(request.maxHeight, "maxHeight", 16384, 1, 16384);
const maxPixels = request.maxPixels === undefined ? undefined : number(request.maxPixels, "maxPixels", 16000000, 1, 16000000);
const artifactBudget = number(request.maxArtifactBytes, "maxArtifactBytes", 32 * 1024 * 1024, 1024, 32 * 1024 * 1024);
if ([maxWidth, maxHeight, maxPixels, artifactBudget].some(value => value !== undefined && !Number.isInteger(value))) throw new CLIError("INVALID_INPUT", "Preview bounds must be integers.");
const policy = parseImagePolicy(request.imagePolicy);
const theme = request.theme === undefined ? undefined : string(request.theme, "theme");
if (theme !== undefined && theme !== "light" && theme !== "dark") throw new CLIError("INVALID_INPUT", "Expected light or dark.", "theme");
const area = request.area === undefined ? undefined : object(request.area, "area");
if (area) { fields(area, ["x", "y", "width", "height"]); for (const key of ["x", "y", "width", "height"]) if (area[key] === undefined) throw new CLIError("INVALID_INPUT", "Area requires x, y, width and height.", "area"); }
const rectangle = area ? { x: number(area.x, "area.x", 0, -1000000, 1000000), y: number(area.y, "area.y", 0, -1000000, 1000000), width: number(area.width, "area.width", 1, 0.1, 100000), height: number(area.height, "area.height", 1, 0.1, 100000) } : undefined;
const api = view?.excalidrawAPI;
let identity = view ? liveIdentity(view) : null;
// Existing view asset loading can finish independently; never publish a
// placeholder export as complete or initiate optional-feature consent UI.
const api = view?.excalidrawAPI, model = view?.excalidrawData;
const identity = view ? liveIdentity(view) : null;
const dependencies = view ? null : new CLIDiskDependencies(vault, cli.isCurrent);
const releaseDependencies = dependencies ? cli.registerOperationCleanup(dependencies.destroy) : () => {};
try {
if (dependencies) await dependencies.observe(file);
const snapshot = view ? null : await diskSnapshot(plugin, file, cli.isCurrent);
const firstScene = view ? view.getScene(selectedOnly) : snapshot.scene;
let elements = scopedElements(firstScene.elements, rectangle);
if (elements.length > 5000) throw new CLIError("INVALID_INPUT", "Exports are limited to 5000 elements.");
if (!elements.length) throw new CLIError("INVALID_INPUT", "Nothing to export.");
// Always check against the complete *original* set, not the scoped/replaced preview.
const assetPaths = view ? [...model.getFileEntries()].map(([, asset]) => asset?.file?.path).filter(Boolean) : snapshot.assetPaths;
if (assetPaths.includes(out)) throw new CLIError("INVALID_INPUT", "Output cannot replace a referenced source asset.", "out");
const decisions = new Map<string, ImageDecision>();
for (const element of elements) if (element.type === "image") decisions.set(element.id, decideImage(element, element.fileId ? firstScene.files?.[element.fileId] : undefined, policy));
const required = new Set<FileId>([...decisions.values()]
.filter(item => item.mode !== "placeholder" && item.fileId !== null)
.map(item => item.fileId as FileId));
// Refuse impossible output geometry before decoding/loading any image sources.
const geometry = async (items: ExcalidrawElement[], appState: typeof firstScene.appState) => {
const rendered = items.filter(element => !(element.type === "frame" && element.frameRole === "marker"));
const frames = new Set(rendered.filter(element => element.type === "frame" || element.type === "magicframe").map(element => element.id));
const roots = rendered.filter(element => !element.frameId || !frames.has(element.frameId));
if (!roots.length) throw new CLIError("INVALID_INPUT", "Nothing to export.");
const bounds = plugin.getCLIRuntime().getCommonBounds(roots);
return frames.size ? frameExportGeometry(rendered, appState, padding, bounds)
: { x: bounds[0] - padding, y: bounds[1] - padding, width: bounds[2] - bounds[0] + padding * 2, height: bounds[3] - bounds[1] + padding * 2 };
};
const initialGeometry = await geometry(elements, firstScene.appState);
previewScale(initialGeometry.width, initialGeometry.height,
format === "png" ? scale : 1, maxWidth, maxHeight, maxPixels);
if (dependencies) {
const thumbnailAssets = [...decisions.values()].filter(item => item.mode === "thumbnail")
.map(item => snapshot.assetFiles.get(item.fileId as FileId)).filter(Boolean);
if (thumbnailAssets.some(asset => !["png", "jpg", "jpeg", "webp"].includes(asset.extension.toLowerCase()))) throw new CLIError("ASSETS_UNAVAILABLE", "Disk thumbnails require direct PNG/JPEG/WebP sources; use loaded live renditions, original or placeholder.");
const thumbnailPaths = new Set(thumbnailAssets.map(asset => asset.path));
dependencies.preflight = (asset, bytes) => {
if (!thumbnailPaths.has(asset.path)) return;
if (bytes.byteLength > 24 * 1024 * 1024) throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail source exceeds 24 MiB; choose placeholder.");
if (["png", "jpg", "jpeg", "webp"].includes(asset.extension.toLowerCase())) rasterDimensions(new Uint8Array(bytes, 0, Math.min(bytes.byteLength, 262144)));
};
}
// View-owned assets may still be loading. Do not wait for intentionally omitted images.
if (view) {
for (let i = 0; i < 60; i++) {
const missing = view.getScene(selectedOnly).elements.some(element => !element.isDeleted && element.type === "image" && !api.getFiles()[element.fileId]?.dataURL);
if (!missing) break;
const available = api.getFiles();
if ([...required].every(id => available[id]?.dataURL?.startsWith("data:"))) break;
if (!cli.isCurrent() || view.file !== file || view.excalidrawAPI !== api || view.isClosingOrMigrating()) throw new CLIError("STALE_REVISION", "Target changed while waiting for assets.");
await new Promise(resolve => window.setTimeout(resolve, 50));
}
identity = liveIdentity(view);
}
const snapshot = view ? null : await diskSnapshot(plugin, file, cli.isCurrent);
const revision = view ? cli.targets.revision(view, identity) : snapshot.revision;
const checkSource = async () => {
dependencies?.assertCurrent();
checkOutput();
if (vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "Source file identity changed.");
if (view) {
if (view.file !== file || view.excalidrawAPI !== api || liveIdentity(view) !== identity) throw new CLIError("STALE_REVISION", "Live scene changed during rendering.");
if (view.file !== file || view.excalidrawAPI !== api || view.excalidrawData !== model || !sameCLIIdentity(liveIdentity(view), identity)) throw new CLIError("STALE_REVISION", "Live scene changed during rendering.");
} else if ((await diskSnapshot(plugin, file, cli.isCurrent)).revision !== revision) throw new CLIError("STALE_REVISION", "Disk drawing changed during rendering.");
checkOutput();
};
let scene = view ? structuredClone(view.getScene(selectedOnly)) : { ...snapshot.scene };
const assetPaths = view ? scene.elements.filter(element => element.type === "image").map(element => view.excalidrawData.getFile(element.fileId)?.file?.path) : snapshot.assetPaths;
if (assetPaths.includes(out)) throw new CLIError("INVALID_INPUT", "Output cannot replace a referenced source asset.", "out");
let scene = { ...firstScene, elements, files: { ...firstScene.files } };
if (!view) {
for (const feature of snapshot.dependencies) {
const extras = plugin.extrasGateway.getAPI();
if (!extras?.features.isActive(feature) || !plugin.extrasGateway.checkVersion(feature, extras).valid) throw new CLIError("DEPENDENCY_UNAVAILABLE", `Enable compatible Excalidraw Extras ${feature} before rendering this drawing.`);
if (required.size) {
// Only the dependencies needed for rendered originals/thumbnails are loaded.
for (const feature of snapshot.dependencies) {
if (![...required].some(id => snapshot.featureFiles[feature].has(id))) continue;
const extras = plugin.extrasGateway.getAPI();
if (!extras?.features.isActive(feature) || !plugin.extrasGateway.checkVersion(feature, extras).valid) throw new CLIError("DEPENDENCY_UNAVAILABLE", `Enable compatible Excalidraw Extras ${feature} before rendering this drawing.`);
}
if (plugin.app.metadataCache.getFirstLinkpathDest(file.path, "") !== file) throw new CLIError("NOT_FOUND", "Exact source is unavailable to the asset loader.");
const loader = new EmbeddedFilesLoader(plugin, theme === undefined ? undefined : theme === "dark");
loader.beforeFileRead = dependencies.observe;
const releaseCleanup = cli.registerOperationCleanup(() => { loader.terminate = true; });
try {
const template = await getTemplate(plugin, file.path, true, loader, 0, false, required);
if (!["idle", "completed"].includes(loader.terminalState)) throw new CLIError("ASSETS_UNAVAILABLE", "Drawing assets did not finish loading.");
scene = { ...scene, elements: scopedElements(template.elements, rectangle), files: template.files, appState: template.appState };
} finally { releaseCleanup(); loader.terminate = true; loader.beforeFileRead = undefined; loader.emptyPDFDocsMap(); }
}
if (plugin.app.metadataCache.getFirstLinkpathDest(file.path, "") !== file) throw new CLIError("NOT_FOUND", "Exact source is unavailable to the asset loader.");
const loader = new EmbeddedFilesLoader(plugin, theme === undefined ? undefined : theme === "dark");
const releaseCleanup = cli.registerOperationCleanup(() => { loader.terminate = true; });
try {
const template = await getTemplate(plugin, file.path, true, loader, 0);
if (!["idle", "completed"].includes(loader.terminalState)) throw new CLIError("ASSETS_UNAVAILABLE", "Drawing assets did not finish loading.");
scene = { ...scene, elements: template.elements, files: template.files, appState: template.appState };
} finally { releaseCleanup(); loader.terminate = true; }
await checkSource();
}
scene.elements = scene.elements.filter(element => !element.isDeleted);
if (scene.elements.length > 5000) throw new CLIError("INVALID_INPUT", "Exports are limited to 5000 elements.");
if (scene.elements.some(element => element.type === "image" && (element.status === "error" || !scene.files?.[element.fileId]?.dataURL || scene.files[element.fileId].dataURL.startsWith("http")))) throw new CLIError("ASSETS_UNAVAILABLE", "An image is missing or undecoded; retry when its normal loader is ready.");
if (rectangle) scene.elements = [...getElementsIntersectionArea(scene.elements, rectangle, { includeBoundElements: true }), createExportAreaAnchor(rectangle)];
// No original image bodies are copied into the preview scene unless needed.
await checkSource();
const converted = await prepareImagePreview(scene.elements, scene.files ?? {}, policy, decisions, () => {
if (!cli.isCurrent()) throw new CLIError("NOT_READY", "Plugin session ended.");
});
scene = { ...scene, elements: converted.elements, files: converted.files };
if (!scene.elements.length) throw new CLIError("INVALID_INPUT", "Nothing to export.");
const [minX, minY, maxX, maxY] = plugin.getCLIRuntime().getCommonBounds(scene.elements);
exportBounds(maxX - minX + padding * 2, maxY - minY + padding * 2, format === "png" ? scale : 1);
if (rectangle) exportBounds(rectangle.width + padding * 2, rectangle.height + padding * 2, format === "png" ? scale : 1);
const measured = await geometry(scene.elements, scene.appState);
const minX = measured.x + padding, minY = measured.y + padding;
const renderWidth = measured.width, renderHeight = measured.height;
const outputWidth = rectangle ? rectangle.width + padding * 2 : renderWidth;
const outputHeight = rectangle ? rectangle.height + padding * 2 : renderHeight;
let effectiveScale = previewScale(renderWidth, renderHeight, format === "png" ? scale : 1,
maxWidth, maxHeight, maxPixels);
if (rectangle) exportBounds(outputWidth, outputHeight, effectiveScale);
const effectiveTheme = theme ?? (view ? view.getViewExportTheme() : scene.appState.theme ?? "light");
scene.appState = { ...scene.appState, theme: effectiveTheme as "light" | "dark", exportEmbedScene: false };
const settings = { withBackground: true, withTheme: true, isMask: false };
let binary: ArrayBuffer, width: number, height: number;
if (format === "svg") {
// The largest unavoidable SVG strings are the selected data URLs. Reject
// them *before* building the SVG rather than stringifying an oversized DOM.
const estimatedDataBytes = Object.values(scene.files).reduce((total, data) => total + data.dataURL.length, 0);
if (estimatedDataBytes > artifactBudget - 1024) throw new CLIError("EXPORT_FAILED", "Selected image payloads exceed the SVG artifact budget; use thumbnail/placeholder rules.");
const svg = await getSVG(scene, settings, padding, file);
if (!svg) throw new CLIError("EXPORT_FAILED", "SVG rendering failed.");
if (rectangle) {
svg.setAttribute("viewBox", `${rectangle.x - minX} ${rectangle.y - minY} ${rectangle.width + padding * 2} ${rectangle.height + padding * 2}`);
svg.setAttribute("width", `${rectangle.width + padding * 2}`); svg.setAttribute("height", `${rectangle.height + padding * 2}`);
}
width = Number(svg.getAttribute("width")); height = Number(svg.getAttribute("height"));
if (rectangle) svg.setAttribute("viewBox", `${rectangle.x - minX} ${rectangle.y - minY} ${outputWidth} ${outputHeight}`);
const baseWidth = rectangle ? outputWidth : Number(svg.getAttribute("width"));
const baseHeight = rectangle ? outputHeight : Number(svg.getAttribute("height"));
const svgScale = previewScale(baseWidth, baseHeight, 1, maxWidth, maxHeight, maxPixels);
effectiveScale = svgScale;
width = baseWidth * svgScale; height = baseHeight * svgScale;
svg.setAttribute("width", `${width}`); svg.setAttribute("height", `${height}`);
binary = new TextEncoder().encode(svg.outerHTML).buffer;
} else {
let png = await getPNG(scene, settings, padding, scale);
let png = await getPNG(scene, settings, padding, effectiveScale);
if (!png) throw new CLIError("EXPORT_FAILED", "PNG rendering failed.");
if (rectangle) png = await cropPNGBlob(png, { x: (rectangle.x - minX) * scale, y: (rectangle.y - minY) * scale, width: (rectangle.width + padding * 2) * scale, height: (rectangle.height + padding * 2) * scale });
if (rectangle) png = await cropPNGBlob(png, { x: (rectangle.x - minX) * effectiveScale, y: (rectangle.y - minY) * effectiveScale, width: outputWidth * effectiveScale, height: outputHeight * effectiveScale });
binary = await png.arrayBuffer(); const header = new DataView(binary);
width = header.getUint32(16); height = header.getUint32(20);
}
exportBounds(width, height, 1);
if (binary.byteLength > 32 * 1024 * 1024) throw new CLIError("EXPORT_FAILED", "Artifact exceeds 32 MiB.");
if (width > (maxWidth ?? Infinity) + 1e-7 || height > (maxHeight ?? Infinity) + 1e-7 || width * height > (maxPixels ?? Infinity) + 1e-3) throw new CLIError("EXPORT_FAILED", "Rendered dimensions exceed the requested preview bounds.");
if (binary.byteLength > artifactBudget) throw new CLIError("EXPORT_FAILED", "Artifact exceeds the requested byte budget; choose a cheaper image policy.");
await checkSource();
await checkAndCreateFolder(out.split("/").slice(0, -1).join("/"));
await checkSource();
await dependencies?.validate();
checkOutput();
dependencies?.assertCurrent();
try {
if (originalOutput instanceof TFile) await vault.modifyBinary(originalOutput, binary);
else await vault.createBinary(out, binary);
} catch {
throw new CLIError("OUTCOME_UNKNOWN", "Artifact write was interrupted.", "out", "Inspect this exact output before retrying.", { mutation: "unknown", persistence: "unknown" });
}
return { target: { vault: vault.getName(), path: file.path, ...(view ? { viewId: view.id } : {}) }, revision, mutation: "applied", persistence: "saved", data: { path: out, format, bytes: binary.byteLength, width, height, source: view ? "live" : "disk", theme: effectiveTheme, revision }, warnings: [] };
const imageSummary = { original: 0, thumbnail: 0, placeholder: 0 };
for (const choice of decisions.values()) imageSummary[choice.mode]++;
return { target: { vault: vault.getName(), path: file.path, ...(view ? { viewId: view.id } : {}) }, revision, mutation: "applied", persistence: "saved", data: {
path: out, format, bytes: binary.byteLength, width, height, source: view ? "live" : "disk", theme: effectiveTheme,
revision, effectiveScale, imageSummary,
imageDecisions: { items: [...decisions.values()].slice(0, 50), total: decisions.size },
representationId: `preview:${fingerprint(canonical({ revision, format, policy, theme: effectiveTheme, rectangle: rectangle ?? null, selectedOnly, padding, width, height, effectiveScale, decisions: [...decisions.values()] }))}`,
sceneToPreview: { sceneBounds: { x: (rectangle?.x ?? minX) - padding, y: (rectangle?.y ?? minY) - padding, width: outputWidth, height: outputHeight }, output: { width, height } },
}, warnings: [] };
} finally { releaseDependencies(); dependencies?.destroy(); }
}
+27
View File
@@ -0,0 +1,27 @@
/** Measure frame-label export geometry through the installed renderer, without original images. */
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import { getSVG } from "src/utils/utils";
import { createExportAreaAnchor } from "src/utils/excalidrawElementUtils";
import { CLIError } from "./cliProtocol";
import { parseImagePolicy, prepareImagePreview } from "./cliImages";
/**
* Frames add renderer-owned title text above their geometric bounds. Probe with
* tiny placeholders and an invisible in-bounds linked rectangle; the rectangle's
* SVG translation exposes the actual origin without duplicating renderer font
* constants or rewriting SVG markup. The entire probe is discarded afterward.
*/
export async function frameExportGeometry(elements: ExcalidrawElement[], appState: Partial<AppState>, padding: number,
bounds: readonly number[]): Promise<{ x: number; y: number; width: number; height: number }> {
const converted = await prepareImagePreview(elements, {}, parseImagePolicy({ default: "placeholder" }), new Map());
const anchor = createExportAreaAnchor({ x: bounds[0], y: bounds[1], width: Math.min(0.1, bounds[2] - bounds[0]), height: Math.min(0.1, bounds[3] - bounds[1]) });
const link = `#excalidraw-cli-origin-${anchor.id}`;
const svg = await getSVG({ elements: [...converted.elements, { ...anchor, link }], files: converted.files, appState: { ...appState, exportEmbedScene: false } },
{ withBackground: true, withTheme: true, isMask: false }, padding, null);
const group = svg?.querySelector<SVGGElement>(`a[href="${link}"] > g`);
const matrix = group?.transform.baseVal.getItem(0)?.matrix;
const width = Number(svg?.getAttribute("width")), height = Number(svg?.getAttribute("height"));
if (!matrix || !Number.isFinite(width) || !Number.isFinite(height)) throw new CLIError("EXPORT_FAILED", "Renderer export geometry is unavailable.");
return { x: anchor.x - matrix.e, y: anchor.y - matrix.f, width, height };
}
+54
View File
@@ -0,0 +1,54 @@
/** Exact, segmented CLI identity; never serializes or hashes asset payloads as a group. */
import { CLIError } from "./cliProtocol";
/**
* Retain immutable primitive strings directly, including arbitrarily large data URLs.
* Copy every mutable container/record so in-place edits cannot mutate the earlier
* snapshot. This intentionally avoids structuredClone, JSON.stringify and hashing
* on the source assets. A view owns at most one cached identity per CLI session.
*/
export function captureCLIIdentity(value: unknown, parents = new WeakSet<object>(), depth = 0): unknown {
if (!value || typeof value !== "object") return value;
if (depth > 60 || parents.has(value)) throw new CLIError("INTERNAL_ERROR", "Live metadata could not be inspected safely.");
parents.add(value);
let result: unknown;
if (value instanceof Date) result = value.getTime();
else if (value instanceof Map) result = new Map([...(value as Map<unknown, unknown>)].map(([key, entry]) => [captureCLIIdentity(key, parents, depth + 1), captureCLIIdentity(entry, parents, depth + 1)]));
else if (value instanceof Set) result = new Set([...value].map(entry => captureCLIIdentity(entry, parents, depth + 1)));
else if (ArrayBuffer.isView(value)) result = Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
else if (value instanceof ArrayBuffer) result = Array.from(new Uint8Array(value));
else if (Array.isArray(value)) result = value.map(entry => captureCLIIdentity(entry, parents, depth + 1));
else {
const copy = Object.create(null) as Record<string, unknown>;
for (const [key, entry] of Object.entries(value)) copy[key] = captureCLIIdentity(entry, parents, depth + 1);
result = copy;
}
parents.delete(value);
return result;
}
/** Exact recursive equality: a last-byte asset change cannot collide with a hash. */
export function sameCLIIdentity(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true;
if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
if (a instanceof Map || b instanceof Map) {
if (!(a instanceof Map) || !(b instanceof Map) || a.size !== b.size) return false;
const aEntries = (a as Map<unknown, unknown>).entries(), bEntries = (b as Map<unknown, unknown>).entries();
for (let i = 0; i < a.size; i++) {
const left = aEntries.next().value as [unknown, unknown], right = bEntries.next().value as [unknown, unknown];
if (!sameCLIIdentity(left[0], right[0]) || !sameCLIIdentity(left[1], right[1])) return false;
}
return true;
}
if (a instanceof Set || b instanceof Set) {
if (!(a instanceof Set) || !(b instanceof Set) || a.size !== b.size) return false;
const left = a.values(), right = b.values();
for (let i = 0; i < a.size; i++) if (!sameCLIIdentity(left.next().value, right.next().value)) return false;
return true;
}
if (Array.isArray(a) !== Array.isArray(b)) return false;
const aKeys = Object.keys(a), bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) return false;
const left = a as Record<string, unknown>, right = b as Record<string, unknown>;
return aKeys.every((key, i) => key === bKeys[i] && sameCLIIdentity(left[key], right[key]));
}
+56
View File
@@ -0,0 +1,56 @@
/** Bounded raster-header inspection before a CLI thumbnail can invoke a decoder. */
import { CLIError } from "./cliProtocol";
/**
* Accept only formats whose encoded dimensions can be established cheaply.
* Read at most 256 KiB of encoded headers; SVG/animated/unknown input must use
* original or placeholder instead. Decoded dimensions are checked again later.
*/
export function thumbnailDimensions(url: string): { width: number; height: number } {
const comma = url.indexOf(",");
if (comma < 0 || !url.slice(0, comma).endsWith(";base64")) throw new CLIError("ASSETS_UNAVAILABLE", "Cannot preflight thumbnail dimensions; choose original or placeholder.");
let header: string;
try { header = atob(url.slice(comma + 1, comma + 1 + 349524)); }
catch { throw new CLIError("ASSETS_UNAVAILABLE", "Invalid thumbnail source encoding."); }
const bytes = Uint8Array.from(header, char => char.charCodeAt(0));
return rasterDimensions(bytes);
}
/** Inspect raw PNG/JPEG/WebP headers without asking the browser to decode pixels. */
export function rasterDimensions(bytes: Uint8Array): { width: number; height: number } {
const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const header = String.fromCharCode(...bytes.subarray(0, 16));
let width = 0, height = 0;
if (header.startsWith("\x89PNG\r\n\x1a\n") && bytes.length >= 24 && header.slice(12, 16) === "IHDR") {
width = data.getUint32(16); height = data.getUint32(20);
} else if (bytes[0] === 0xff && bytes[1] === 0xd8) {
let offset = 2;
while (offset + 4 <= bytes.length) {
if (bytes[offset++] !== 0xff) break;
while (bytes[offset] === 0xff) offset++;
const marker = bytes[offset++];
if (marker === 0xda || marker === 0xd9) break;
if (marker === 0x01 || marker >= 0xd0 && marker <= 0xd7) continue;
if (offset + 2 > bytes.length) break;
const size = data.getUint16(offset);
if (size < 2 || offset + size > bytes.length) break;
if ([0xc0, 0xc1, 0xc2].includes(marker) && size >= 8) {
height = data.getUint16(offset + 3); width = data.getUint16(offset + 5); break;
}
offset += size;
}
} else if (header.startsWith("RIFF") && header.slice(8, 12) === "WEBP" && bytes.length >= 30) {
const kind = header.slice(12, 16);
if (kind === "VP8X" && !(bytes[20] & 2)) {
width = 1 + bytes[24] + bytes[25] * 256 + bytes[26] * 65536;
height = 1 + bytes[27] + bytes[28] * 256 + bytes[29] * 65536;
} else if (kind === "VP8 " && bytes[23] === 0x9d && bytes[24] === 0x01 && bytes[25] === 0x2a) {
width = data.getUint16(26, true) & 0x3fff; height = data.getUint16(28, true) & 0x3fff;
} else if (kind === "VP8L" && bytes[20] === 0x2f) {
const packed = data.getUint32(21, true);
width = 1 + (packed & 0x3fff); height = 1 + ((packed >>> 14) & 0x3fff);
}
}
if (!width || !height || width * height > 16_000_000) throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail dimensions are unknown or exceed 16 million pixels; choose original or placeholder.");
return { width, height };
}
+179
View File
@@ -0,0 +1,179 @@
/** Request-local image inventory and safe, opt-in CLI preview representations (#3004). */
import type { BinaryFileData, BinaryFiles } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { nanoid } from "src/constants/constants";
import { CLIError, number, object } from "./cliProtocol";
import { getCLIImageMetadata } from "src/utils/elementCustomDataUtils";
import { thumbnailDimensions } from "./cliImageDimensions";
type Mode = "original" | "thumbnail" | "placeholder";
interface Rule { mode: Mode; ids?: string[]; tags?: string[]; mimeTypes?: string[]; maxBytes?: number }
/** Validated, request-local preview representations; omission retains original fidelity. */
export interface ImagePolicy { default: Mode; rules: Rule[]; thumbnailMaxDimension: number; labels: Record<string, string> }
/** Metadata-only decision trace, containing no original image payload. */
export type ImageDecision = { elementId: string; fileId: string | null; mode: Mode; reason: string; label: string; bytes: number | null; mimeType: string | null };
function strings(value: unknown, field: string, max: number, limit: number): string[] {
if (!Array.isArray(value) || !value.length || value.length > max || value.some(item => typeof item !== "string" || !item.trim() || item.length > limit)) throw new CLIError("INVALID_INPUT", "Expected a bounded list of nonempty strings.", field);
return value as string[];
}
/** No scripts, regexp, recursive predicates, or implicit lossy defaults. */
export function parseImagePolicy(raw: unknown): ImagePolicy | null {
if (raw === undefined) return null;
const policy = object(raw, "imagePolicy");
for (const key of Object.keys(policy)) if (!["default", "rules", "thumbnailMaxDimension", "labels"].includes(key)) throw new CLIError("INVALID_INPUT", "Unknown image-policy field.", key);
const mode = (value: unknown, field: string): Mode => {
if (value !== "original" && value !== "thumbnail" && value !== "placeholder") throw new CLIError("INVALID_INPUT", "Expected original, thumbnail or placeholder.", field);
return value;
};
const rules = policy.rules === undefined ? [] : policy.rules;
if (!Array.isArray(rules) || rules.length > 32) throw new CLIError("INVALID_INPUT", "Image-policy rules are limited to 32.", "imagePolicy.rules");
const parsedRules: Rule[] = rules.map((item, index) => {
const rule = object(item, `imagePolicy.rules[${index}]`);
for (const key of Object.keys(rule)) if (!["mode", "ids", "tags", "mimeTypes", "maxBytes"].includes(key)) throw new CLIError("INVALID_INPUT", "Unknown image rule field.", key);
const match = { mode: mode(rule.mode, "imagePolicy.rules.mode") } as Rule;
if (rule.ids !== undefined) match.ids = strings(rule.ids, "imagePolicy.rules.ids", 100, 100);
if (rule.tags !== undefined) match.tags = strings(rule.tags, "imagePolicy.rules.tags", 20, 32);
if (rule.mimeTypes !== undefined) match.mimeTypes = strings(rule.mimeTypes, "imagePolicy.rules.mimeTypes", 20, 80);
if (rule.maxBytes !== undefined) match.maxBytes = number(rule.maxBytes, "imagePolicy.rules.maxBytes", 0, 0, 1024 * 1024 * 1024);
if (match.maxBytes !== undefined && !Number.isInteger(match.maxBytes)) throw new CLIError("INVALID_INPUT", "Expected integral bytes.");
if (!Object.keys(match).some(key => key !== "mode")) throw new CLIError("INVALID_INPUT", "A rule must contain at least one matching condition.");
return match;
});
const rawLabels: Record<string, unknown> = policy.labels === undefined ? {} : object(policy.labels, "imagePolicy.labels");
if (Object.keys(rawLabels).length > 100) throw new CLIError("INVALID_INPUT", "Too many request-only labels.");
const labels = Object.create(null) as Record<string, string>;
for (const [id, label] of Object.entries(rawLabels)) {
if (!id || id.length > 100 || typeof label !== "string" || label.length > 80 || !label.trim()) throw new CLIError("INVALID_INPUT", "Invalid image label.", "imagePolicy.labels");
labels[id] = label;
}
const dimension = number(policy.thumbnailMaxDimension, "imagePolicy.thumbnailMaxDimension", 512, 64, 2048);
if (!Number.isInteger(dimension)) throw new CLIError("INVALID_INPUT", "Thumbnail resolution must be an integer.");
return { default: policy.default === undefined ? "original" : mode(policy.default, "imagePolicy.default"), rules: parsedRules, thumbnailMaxDimension: dimension, labels };
}
/** Constant-work base64 byte estimate; unknown/missing payloads remain unknown. */
export function dataURLBytes(url?: string): number | null {
if (!url || !url.startsWith("data:")) return null;
const comma = url.indexOf(",");
if (comma < 0) return null;
const prefix = url.slice(0, comma);
if (prefix.includes(";base64")) {
const end = url.length;
return Math.max(0, Math.floor((end - comma - 1) * 3 / 4) - (url.endsWith("==") ? 2 : url.endsWith("=") ? 1 : 0));
}
// Percent encoding cannot be inferred from the payload length without scanning it.
return null;
}
/** Report known placement/load metadata without decoding, fetching, or copying asset bodies. */
export function imageInventory(element: ExcalidrawImageElement, file?: BinaryFileData, originalBytes: number | null = null) {
const metadata = getCLIImageMetadata(element);
return {
elementId: element.id, fileId: element.fileId,
label: metadata?.label ?? null, tags: metadata?.tags ?? [], mimeType: file?.mimeType ?? null,
loadedRenditionBytes: dataURLBytes(file?.dataURL), originalBytes, intrinsicDimensions: element.crop ? { width: element.crop.naturalWidth, height: element.crop.naturalHeight } : null,
placement: { x: element.x, y: element.y, width: element.width, height: element.height, angle: element.angle },
loaded: !!file?.dataURL && file.dataURL.startsWith("data:"), status: element.status ?? null,
};
}
/** First-match policy; unknown byte sizes do not satisfy a maxBytes predicate. */
export function decideImage(element: ExcalidrawImageElement, file: BinaryFileData | undefined, policy: ImagePolicy | null): ImageDecision {
const annotation = getCLIImageMetadata(element);
const bytes = dataURLBytes(file?.dataURL), mimeType = file?.mimeType ?? null;
const chosen = policy?.rules.find(rule =>
(!rule.ids || rule.ids.includes(element.id)) &&
(!rule.tags || rule.tags.some(tag => annotation?.tags?.includes(tag))) &&
(!rule.mimeTypes || !!mimeType && rule.mimeTypes.includes(mimeType)) &&
(rule.maxBytes === undefined || bytes !== null && bytes <= rule.maxBytes));
return {
elementId: element.id, fileId: element.fileId, mode: chosen?.mode ?? policy?.default ?? "original",
reason: chosen ? `rule ${policy.rules.indexOf(chosen) + 1}` : "default",
label: policy?.labels[element.id] ?? annotation?.label ?? `Image ${element.id.slice(0, 12)}`,
bytes, mimeType,
};
}
/** ASCII XML entities prevent label injection and btoa Unicode errors. */
export function placeholderDataURL(label: string, width: number, height: number): string {
const w = Number.isFinite(width) ? Math.max(1, width) : 1, h = Number.isFinite(height) ? Math.max(1, height) : 1;
const safe = [...label.slice(0, 80)].map(char => `&#${char.codePointAt(0)};`).join("");
const fontSize = Math.max(1, Math.min(w / 10, h / 4, 28));
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><rect x="0.5" y="0.5" width="${Math.max(0, w - 1)}" height="${Math.max(0, h - 1)}" fill="#f4f4f4" stroke="#888" stroke-dasharray="5 4"/><text x="${w / 2}" y="${h / 2}" text-anchor="middle" dominant-baseline="middle" font-family="sans-serif" font-size="${fontSize}" fill="#555" textLength="${Math.min(w * 0.9, label.length * fontSize * 0.55)}" lengthAdjust="spacingAndGlyphs">${safe}</text></svg>`;
return `data:image/svg+xml;base64,${btoa(svg)}`;
}
/** Guard decoded pixels and source size; do not allocate a canvas for oversized assets. */
async function thumbnail(file: BinaryFileData, dimension: number, check: () => void): Promise<{ url: string; width: number; height: number; originalWidth: number; originalHeight: number }> {
const bytes = dataURLBytes(file.dataURL);
if (bytes === null || bytes > 24 * 1024 * 1024) throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail source exceeds safe decode bounds; select placeholder instead.");
const expected = thumbnailDimensions(file.dataURL);
check();
const img = createFragment().createEl("img");
img.src = file.dataURL;
try {
try { await img.decode(); }
catch { throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail source could not be decoded; choose placeholder."); }
check();
const originalWidth = img.naturalWidth, originalHeight = img.naturalHeight;
const matchesHeader = originalWidth === expected.width && originalHeight === expected.height
|| originalWidth === expected.height && originalHeight === expected.width; // JPEG EXIF orientation can swap axes.
if (!originalWidth || !originalHeight || originalWidth * originalHeight > 16_000_000 || !matchesHeader) throw new CLIError("ASSETS_UNAVAILABLE", "Image dimensions failed thumbnail preflight; select placeholder.");
const ratio = Math.min(1, dimension / Math.max(originalWidth, originalHeight));
const width = Math.max(1, Math.round(originalWidth * ratio)), height = Math.max(1, Math.round(originalHeight * ratio));
const canvas = createFragment().createEl("canvas");
try {
canvas.width = width; canvas.height = height;
const context = canvas.getContext("2d");
if (!context) throw new CLIError("EXPORT_FAILED", "Thumbnail canvas is unavailable.");
context.drawImage(img, 0, 0, width, height);
const url = canvas.toDataURL("image/png");
if (url.length > 8 * 1024 * 1024) throw new CLIError("EXPORT_FAILED", "Thumbnail exceeds the 6 MiB rendition budget.");
return { url, width, height, originalWidth, originalHeight };
} finally { canvas.width = 0; canvas.height = 0; }
} finally { img.removeAttribute("src"); }
}
/**
* Assemble a minimal export-only files map; each placeholder has its own file ID
* so SVG symbol reuse cannot turn another instance into the wrong representation.
* The caller keeps the original full scene identity for all staleness checks.
*/
export async function prepareImagePreview(elements: readonly ExcalidrawElement[], files: BinaryFiles, policy: ImagePolicy | null, decisions: Map<string, ImageDecision>, check: () => void = () => {}) {
const resultFiles: BinaryFiles = {};
const resultElements: ExcalidrawElement[] = [];
const thumbnails = new Map<string, Awaited<ReturnType<typeof thumbnail>>>();
for (const element of elements) {
check();
if (element.type !== "image") { resultElements.push(element); continue; }
const original = element.fileId ? files[element.fileId] : undefined;
const decision = decisions.get(element.id) ?? decideImage(element, original, policy);
if (decision.mode === "original") {
if (!original?.dataURL || !original.dataURL.startsWith("data:") || element.status === "error") throw new CLIError("ASSETS_UNAVAILABLE", "A required original image is missing or undecoded; use a placeholder policy for a structural preview.");
resultFiles[original.id] = original;
resultElements.push(element);
continue;
}
const fileId = `cli${nanoid()}` as FileId;
if (decision.mode === "placeholder") {
resultFiles[fileId] = { id: fileId, mimeType: "image/svg+xml", dataURL: placeholderDataURL(decision.label, element.width, element.height) as BinaryFileData["dataURL"], created: Date.now() };
resultElements.push({ ...element, fileId, status: "saved", crop: null,
customData: { ...element.customData, doNotInvertSVGInDarkMode: true, invertBitmapInDarkmode: false } });
} else {
if (!original?.dataURL) throw new CLIError("ASSETS_UNAVAILABLE", "A required thumbnail image is missing; select placeholder instead.");
const key = `${element.fileId}:${policy?.thumbnailMaxDimension ?? 512}`;
let reduced = thumbnails.get(key);
if (!reduced) { reduced = await thumbnail(original, policy?.thumbnailMaxDimension ?? 512, check); thumbnails.set(key, reduced); }
resultFiles[fileId] = { id: fileId, mimeType: "image/png", dataURL: reduced.url as BinaryFileData["dataURL"], created: Date.now() };
const x = reduced.width / reduced.originalWidth, y = reduced.height / reduced.originalHeight;
resultElements.push({ ...element, fileId, status: "saved", crop: element.crop ? {
x: element.crop.x * x, y: element.crop.y * y, width: element.crop.width * x, height: element.crop.height * y,
naturalWidth: reduced.width, naturalHeight: reduced.height,
} : null });
}
}
return { elements: resultElements, files: resultFiles };
}
+2 -1
View File
@@ -8,7 +8,8 @@ export const CLI_OUTPUT_LIMIT = 512 * 1024;
export class CLIError extends Error {
public constructor(public readonly code: string, message: string, public readonly field?: string,
public readonly recovery = "Read the command schema and correct the request.",
public readonly outcome: Partial<ExcalidrawCLIResult> = {}) {
public readonly outcome: Partial<ExcalidrawCLIResult> = {},
public readonly preExecutionBusy = false) {
super(message);
}
}
+23 -3
View File
@@ -11,16 +11,36 @@ const required: Partial<Record<CLICommand, string[]>> = {
};
const operationRequired: Record<string, string[]> = {
add: ["elements"], update: ["id", "set"], delete: ["ids"], connect: ["from", "to"],
group: ["ids"], ungroup: ["ids", "groupId"], image: ["asset"], latex: ["text"],
group: ["ids"], ungroup: ["ids", "groupId"], image: ["asset"], imageMetadata: ["id"], latex: ["text"],
};
function property(name: string): Record<string, unknown> {
if (["x", "y", "width", "height", "angle", "fontSize", "fontFamily", "opacity", "strokeWidth", "roughness", "offset", "limit", "padding", "scale", "scaleX", "scaleY"].includes(name)) return { type: "number" };
if (["x", "y", "width", "height", "angle", "fontSize", "fontFamily", "opacity", "strokeWidth", "roughness", "offset", "limit", "padding", "scale", "scaleX", "scaleY", "maxWidth", "maxHeight", "maxPixels", "maxArtifactBytes"].includes(name)) return { type: "number" };
if (["overwrite", "trusted", "selectedOnly", "locked"].includes(name)) return { type: "boolean" };
if (name === "ids" || name === "children") return { type: "array", items: { type: "string" } };
if (name === "elements") return { type: "array", maxItems: 500, items: { $ref: "#/$defs/skeleton" } };
if (name === "operations") return { type: "array", minItems: 1, maxItems: 100, items: { $ref: "#/$defs/operation" } };
if (name === "set") return { type: "object", additionalProperties: false, properties: Object.fromEntries(CLI_STYLE_FIELDS.map(key => [key, property(key)])) };
if (name === "args") return {};
if (name === "imagePolicy") return {
type: "object", additionalProperties: false,
properties: {
default: { enum: ["original", "thumbnail", "placeholder"] },
thumbnailMaxDimension: { type: "integer", minimum: 64, maximum: 2048 },
labels: { type: "object", maxProperties: 100, additionalProperties: { type: "string", maxLength: 80, minLength: 1 } },
rules: { type: "array", maxItems: 32, items: {
type: "object", additionalProperties: false, required: ["mode"],
properties: {
mode: { enum: ["original", "thumbnail", "placeholder"] },
ids: { type: "array", minItems: 1, maxItems: 100, items: { type: "string", maxLength: 100 } },
tags: { type: "array", minItems: 1, maxItems: 20, items: { type: "string", maxLength: 32 } },
mimeTypes: { type: "array", minItems: 1, maxItems: 20, items: { type: "string", maxLength: 80 } },
maxBytes: { type: "integer", minimum: 0, maximum: 1073741824 },
},
anyOf: [{ required: ["ids"] }, { required: ["tags"] }, { required: ["mimeTypes"] }, { required: ["maxBytes"] }],
} },
},
};
if (name === "tags") return { anyOf: [{ type: "null" }, { type: "array", maxItems: 12, uniqueItems: true, items: { type: "string", maxLength: 32 } }] };
if (["area", "roundness", "label", "start", "end"].includes(name)) return { type: "object" };
if (name === "points") return { type: "array", minItems: 2, maxItems: 100, items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
if (name === "link") return { type: ["string", "null"] };
@@ -39,7 +59,7 @@ export function commandSchema(command: CLICommand): Record<string, unknown> {
},
...(command === "create" || command === "apply" ? { $defs: {
skeleton: { type: "object", required: ["type"], additionalProperties: false, properties: { ...Object.fromEntries(skeletonFields.map(name => [name, property(name)])), type: { enum: CLI_SHAPES }, roundness: { type: ["object", "null"] }, name: { type: ["string", "null"] }, startArrowhead: { type: ["string", "null"] }, endArrowhead: { type: ["string", "null"] } } },
operation: { oneOf: Object.entries(CLI_OPERATION_FIELDS).map(([op, fields]) => ({ type: "object", required: ["op", ...operationRequired[op]], additionalProperties: false, properties: { op: { const: op }, ...Object.fromEntries(fields.map(name => [name, name === "children" ? { enum: ["delete", "detach"] } : property(name)])) } })) },
operation: { oneOf: Object.entries(CLI_OPERATION_FIELDS).map(([op, fields]) => ({ type: "object", required: ["op", ...operationRequired[op]], additionalProperties: false, properties: { op: { const: op }, ...Object.fromEntries(fields.map(name => [name, name === "children" ? { enum: ["delete", "detach"] } : op === "image" && name === "scale" ? { type: "boolean" } : op === "imageMetadata" && name === "label" ? { type: ["string", "null"], maxLength: 80 } : property(name)])) }, ...(op === "imageMetadata" ? { anyOf: [{ required: ["label"] }, { required: ["tags"] }] } : {}) })) },
} } : {}),
};
}
+2 -1
View File
@@ -4,6 +4,7 @@ import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import { CLIError, boolean, jsonValue, vaultPath } from "./cliProtocol";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
/** Source content participates in the effective request identity, including cached scripts. */
export async function prepareScript(cli: ExcalidrawCLI, request: Record<string, unknown>) {
@@ -27,7 +28,7 @@ export async function executeScript(cli: ExcalidrawCLI, request: Record<string,
const api = view?.excalidrawAPI, identity = view ? liveIdentity(view) : null;
const check = () => {
if (!cli.isCurrent() || plugin.app.vault.getFileByPath(prepared.file.path) !== prepared.file || JSON.stringify(prepared.file.stat) !== prepared.stat) throw new CLIError("STALE_REVISION", "Script or plugin identity changed before execution.");
if (view && (view.file !== drawing || view.excalidrawAPI !== api || liveIdentity(view) !== identity)) throw new CLIError("STALE_REVISION", "Drawing changed before script execution.");
if (view && (view.file !== drawing || view.excalidrawAPI !== api || !sameCLIIdentity(liveIdentity(view), identity))) throw new CLIError("STALE_REVISION", "Drawing changed before script execution.");
if (view && (view.isSameFileEditingActive() || view.isPersistenceBusy())) throw new CLIError("BUSY", "Drawing is being edited as Markdown or synchronized.");
};
check(); if (view) ea.setView(view);
+24 -8
View File
@@ -6,6 +6,7 @@ import { ExcalidrawData } from "src/shared/ExcalidrawData";
import { getTextMode } from "src/shared/TextMode";
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import { CLIError, fingerprint, vaultPath } from "./cliProtocol";
import { captureCLIIdentity, sameCLIIdentity } from "./cliIdentity";
/** Resolves an exact file; never uses basename/link lookup or the active drawing. */
export function drawingFile(plugin: ExcalidrawPlugin, value: unknown): TFile {
@@ -36,11 +37,11 @@ export function drawingView(plugin: ExcalidrawPlugin, file: TFile, id?: unknown)
}
/** Captures authoritative scene, document metadata, assets and settings for optimistic checks. */
export function liveIdentity(view: ExcalidrawView): string {
export function liveIdentity(view: ExcalidrawView): unknown {
if (!view.excalidrawAPI || !view.isLoaded || view.isClosingOrMigrating()) throw new CLIError("BUSY", "Drawing is loading, closing or migrating.", "path");
const model = view.excalidrawData;
const exportData = model.exportPreparedSaveData();
return JSON.stringify({
return captureCLIIdentity({
elements: view.excalidrawAPI.getSceneElementsIncludingDeleted(),
files: view.excalidrawAPI.getFiles(),
scene: view.getScene()?.appState,
@@ -55,16 +56,28 @@ export function liveIdentity(view: ExcalidrawView): string {
/** API identity changes invalidate old revisions even when the content is identical. */
export class CLITargets {
private generations = new WeakMap<object, number>();
private observations = new WeakMap<ExcalidrawView, { api: object; model: object; file: object; snapshot: unknown; generation: number; version: number }>();
private nextGeneration = 1;
public constructor(private readonly session: string) {}
/** Opaque session/view/runtime/content marker. */
public revision(view: ExcalidrawView, identity = liveIdentity(view)): string {
const api = view.excalidrawAPI;
if (!this.generations.has(api)) this.generations.set(api, this.nextGeneration++);
return `${this.session}:${view.id}:${this.generations.get(api)}:${fingerprint(identity)}`;
/** Exact content comparison advances a stable opaque revision without hashing images. */
public revision(view: ExcalidrawView, identity: unknown = liveIdentity(view)): string {
const api = view.excalidrawAPI, model = view.excalidrawData, file = view.file;
const previous = this.observations.get(view);
if (!previous || previous.api !== api || previous.model !== model || previous.file !== file) {
const generation = this.nextGeneration++;
this.observations.set(view, { api, model, file, snapshot: identity, generation, version: 1 });
return `${this.session}:${view.id}:${generation}:1`;
}
if (!sameCLIIdentity(previous.snapshot, identity)) {
previous.snapshot = identity;
previous.version++;
}
return `${this.session}:${view.id}:${previous.generation}:${previous.version}`;
}
/** A disposed session must release its latest captured image strings promptly. */
public destroy(): void { this.observations = new WeakMap(); }
}
/** Parses a single exact Vault read with the existing drawing model and releases it. */
@@ -80,6 +93,9 @@ export async function diskSnapshot(plugin: ExcalidrawPlugin, file: TFile, isCurr
return { scene: structuredClone(data.scene), revision: `disk:${fingerprint(text)}`,
dependencies: [...(data.equations.size ? ["mathjax" as const] : []), ...(data.mermaids.size ? ["mermaid" as const] : [])],
assetPaths: data.scene.elements.filter(element => element.type === "image").map(element => data.getFile(element.fileId)?.file?.path).filter(Boolean),
assetSizes: new Map([...data.getFileEntries()].map(([id, asset]) => [id, asset.file?.stat.size ?? null])),
assetFiles: new Map([...data.getFileEntries()].map(([id, asset]) => [id, asset.file])),
featureFiles: { mathjax: new Set([...data.equations.keys()]), mermaid: new Set([...data.mermaids.keys()]) },
};
} finally { data.destroy(); }
}
+39 -16
View File
@@ -11,9 +11,10 @@ import { t } from "src/lang/helpers";
import { CLIWriteCommands } from "src/core/cli/CLIWriteCommands";
import { prepareScript } from "src/core/cli/cliScripts";
import { commandSchema } from "src/core/cli/cliSchema";
import { imageInventory } from "src/core/cli/cliImages";
import { nanoid } from "src/constants/constants";
type Receipt = { fingerprint: string; result: ExcalidrawCLIResult; finishedAt?: number };
type Receipt = { fingerprint: string; result: ExcalidrawCLIResult; finishedAt?: number; preExecutionBusy?: boolean };
/** Optional CLI; all registrations use Plugin's own unload cleanup. */
export class ExcalidrawCLI {
@@ -39,7 +40,7 @@ export class ExcalidrawCLI {
public destroy(): void {
this.alive = false;
for (const cleanup of this.operationCleanups) cleanup();
this.operationCleanups.clear(); this.writes.destroy(); this.receipts.clear();
this.operationCleanups.clear(); this.writes.destroy(); this.receipts.clear(); this.targets.destroy();
}
/** Stops request-owned loaders at unload without retaining completed operations. */
@@ -60,8 +61,8 @@ export class ExcalidrawCLI {
if (["overwrite", "selectedOnly", "trusted"].includes(key)) {
if (!["true", "false"].includes(value)) throw new CLIError("INVALID_INPUT", "Expected true or false.", key);
params[key] = value === "true";
} else if (["offset", "limit", "scale", "padding"].includes(key)) params[key] = Number(value);
else if (["ids", "args", "area", "elements", "operations"].includes(key)) params[key] = JSON.parse(value);
} else if (["offset", "limit", "scale", "padding", "maxWidth", "maxHeight", "maxPixels", "maxArtifactBytes"].includes(key)) params[key] = Number(value);
else if (["ids", "args", "area", "elements", "operations", "imagePolicy"].includes(key)) params[key] = JSON.parse(value);
else params[key] = value;
}
if (params.input !== undefined && params.json !== undefined) throw new CLIError("INVALID_INPUT", "Choose input or json, not both.");
@@ -88,7 +89,7 @@ export class ExcalidrawCLI {
if (params.input !== undefined && payload.out === params.input) throw new CLIError("INVALID_INPUT", "Output cannot replace the request file.", "out");
const result = await this.execute({ ...payload, apiVersion: 1, command });
return result.ok && command === "skill" && payload.format === "markdown" ? CLI_SKILL : JSON.stringify(result);
} catch (error) { return JSON.stringify(this.failure(command, undefined, error)); }
} catch (error) { return JSON.stringify(this.failure(command, undefined, error instanceof SyntaxError ? new CLIError("INVALID_INPUT", "Malformed JSON request.") : error)); }
}
private base(command: string, requestId?: string): ExcalidrawCLIResult {
@@ -96,7 +97,7 @@ export class ExcalidrawCLI {
}
private failure(command: string, requestId: string | undefined, error: unknown): ExcalidrawCLIResult {
const failure = error instanceof CLIError ? error : new CLIError("INVALID_INPUT", "Request could not be completed.");
const failure = error instanceof CLIError ? error : new CLIError("INTERNAL_ERROR", "An internal CLI operation failed. Inspect the target before retrying.", undefined, "For writes, read back the target and inspect the receipt before issuing another operation.");
return { ...this.base(command, requestId), ...failure.outcome, status: "failed", ok: false,
error: { code: failure.code, message: failure.message, ...(failure.field ? { field: failure.field } : {}), recovery: failure.recovery } };
}
@@ -130,18 +131,33 @@ export class ExcalidrawCLI {
const existing = this.receipts.get(requestId);
if (existing) {
if (existing.fingerprint !== signature) throw new CLIError("INVALID_INPUT", "requestId was already used for different content.", "requestId");
return structuredClone(existing.result);
if (!existing.preExecutionBusy) return structuredClone(existing.result);
// The previous attempt never acquired a target lock or performed work.
// Preserve its canonical signature while allowing the *identical* request to retry.
existing.preExecutionBusy = false;
existing.finishedAt = undefined;
existing.result = { ...this.base(action, requestId), status: "pending", ok: null, persistence: "unknown" };
}
if (this.receipts.size >= 128) throw new CLIError("BUSY", "Session receipt capacity is exhausted.", "requestId", "Wait for completed receipts to expire; do not retry writes with a new ID blindly.");
this.receipts.set(requestId, { fingerprint: signature, result: { ...this.base(action, requestId), status: "pending", ok: null, persistence: "unknown" } });
if (!existing && this.receipts.size >= 128) throw new CLIError("BUSY", "Session receipt capacity is exhausted.", "requestId", "Wait for completed receipts to expire; do not retry writes with a new ID blindly.");
if (!existing) this.receipts.set(requestId, { fingerprint: signature, result: { ...this.base(action, requestId), status: "pending", ok: null, persistence: "unknown" } });
}
let result: ExcalidrawCLIResult;
try {
const output = descriptor.writes ? await this.writes.execute(action, request, preparedScript) : { data: await this.dispatch(action, request) };
try { result = { ...this.base(action, requestId), ...output, data: jsonValue(output.data ?? null) }; }
catch { throw new CLIError("OUTCOME_UNKNOWN", "Result could not be serialized after execution.", undefined, "Read back the target before another write.", { ...output, data: null }); }
catch {
if (!descriptor.writes) throw new CLIError("INTERNAL_ERROR", "CLI result could not be serialized.");
throw new CLIError("OUTCOME_UNKNOWN", "Result could not be serialized after execution.", undefined, "Read back the target before another write.", { ...output, data: null });
}
}
catch (error) {
result = this.failure(action, requestId, error);
if (descriptor.writes && !(error instanceof CLIError)) { result.mutation = "unknown"; result.persistence = "unknown"; }
if (descriptor.writes && error instanceof CLIError && error.preExecutionBusy) {
const receipt = this.receipts.get(requestId);
if (receipt) receipt.preExecutionBusy = true;
}
}
catch (error) { result = this.failure(action, requestId, error); }
if (descriptor.writes && this.alive) {
const receipt = this.receipts.get(requestId);
receipt.result = result; receipt.finishedAt = Date.now();
@@ -202,7 +218,7 @@ export class ExcalidrawCLI {
if (source === "live" && !view) throw new CLIError("NOT_READY", "Drawing has no live view.", "path", "Use open first.");
if (source === "disk" && request.view !== undefined) throw new CLIError("INVALID_INPUT", "A disk read cannot select a view.", "view");
if (!useLive && boolean(request.selectedOnly, "selectedOnly")) throw new CLIError("INVALID_INPUT", "Selection requires a live source.", "selectedOnly");
const snapshot = useLive ? { scene: structuredClone(view.getScene()), revision: this.targets.revision(view) } : await diskSnapshot(plugin, file, this.isCurrent);
const snapshot = useLive ? { scene: view.getScene(), revision: this.targets.revision(view), assetSizes: new Map([...view.excalidrawData.getFileEntries()].map(([id, asset]) => [id, asset.file?.stat.size ?? null])) } : await diskSnapshot(plugin, file, this.isCurrent);
let elements = snapshot.scene.elements.filter(element => !element.isDeleted);
if (request.ids !== undefined) {
if (!Array.isArray(request.ids) || request.ids.some(id => typeof id !== "string")) throw new CLIError("INVALID_INPUT", "Expected an ID array.", "ids");
@@ -212,15 +228,22 @@ export class ExcalidrawCLI {
const selected = view.excalidrawAPI.getAppState().selectedElementIds;
elements = elements.filter(element => selected[element.id]);
}
if (request.detail !== undefined && !["summary", "elements"].includes(string(request.detail, "detail"))) throw new CLIError("INVALID_INPUT", "Expected summary or elements.", "detail");
if (request.detail !== undefined && !["summary", "elements", "images"].includes(string(request.detail, "detail"))) throw new CLIError("INVALID_INPUT", "Expected summary, elements or images.", "detail");
const data = { path: file.path, source: useLive ? "live" : "disk", ...(useLive ? { viewId: view.id, dirty: view.isDirty() } : {}), revision: snapshot.revision, total: elements.length, assetIds: Object.keys(snapshot.scene.files ?? {}), types: Object.fromEntries([...new Set(elements.map(element => element.type))].map(type => [type, elements.filter(element => element.type === type).length])) };
return request.detail === "elements" ? { ...data, ...this.page(JSON.parse(JSON.stringify(elements)) as unknown[], request, snapshot.revision, "elements") } : data;
if (request.detail === "images") {
const images = elements.filter(element => element.type === "image")
.map(element => imageInventory(element, element.fileId ? snapshot.scene.files?.[element.fileId] : undefined, snapshot.assetSizes.get(element.fileId) ?? null));
return { ...data, ...this.page(images, request, snapshot.revision, "images") };
}
return request.detail === "elements"
? { ...data, ...this.page(elements, request, snapshot.revision, "elements", true) }
: data;
}
private page(values: unknown[], request: Record<string, unknown>, revision: string, field: string) {
private page(values: unknown[], request: Record<string, unknown>, revision: string, field: string, clonePage = false) {
const offset = number(request.offset, "offset", 0, 0, values.length), limit = number(request.limit, "limit", 50, 1, 200);
if (!Number.isInteger(offset) || !Number.isInteger(limit)) throw new CLIError("INVALID_INPUT", "Pagination requires integers.");
if ((offset > 0 || request.revision !== undefined) && request.revision !== revision) throw new CLIError("STALE_REVISION", "Pagination snapshot changed.", "revision", "Read the first page again.");
return { [field]: values.slice(offset, offset + limit), total: values.length, revision, nextOffset: offset + limit < values.length ? offset + limit : null };
return { [field]: clonePage ? JSON.parse(JSON.stringify(values.slice(offset, offset + limit))) as unknown[] : values.slice(offset, offset + limit), total: values.length, revision, nextOffset: offset + limit < values.length ? offset + limit : null };
}
}
+4
View File
@@ -18,6 +18,10 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.29.1": `
## Excalidraw CLI
- Fixed image-heavy drawing revisions without concatenating image data, and corrected image-insertion scale validation. Refused operations can retry the same request ID only when no work started. [#3004](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3004)
- Added opt-in image inventory, bounded image labels/tags, mixed-fidelity SVG/PNG previews and output limits. Originals remain untouched and full fidelity stays the default. [#3004](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3004)
## Fixed
- Drawing-load warnings now name the affected file. Select **More information** to learn about missing or malformed drawing data and device-local backups, and see the reported error. Warnings without a local backup also include a **Dismiss** button. Existing recovery actions are unchanged. [#2995](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2995)
+13 -2
View File
@@ -804,6 +804,8 @@ export class EmbeddedFilesLoader {
public terminate = false;
public terminalState: EmbeddedFilesLoaderTerminalState = "idle";
public uid: string;
/** Request-local export guard. Its presence also bypasses stat-keyed rendition caches. */
public beforeFileRead?: (file: TFile) => Promise<void>;
constructor(plugin: ExcalidrawPlugin, isDark?: boolean) {
this.plugin = plugin;
@@ -930,6 +932,7 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
);
const shouldUseCache =
!this.beforeFileRead &&
!bypassCache &&
!hasColorMap &&
this.plugin.settings.allowImageCacheInScene &&
@@ -1159,6 +1162,13 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.isMarkdownSection : false;
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
if (this.beforeFileRead) {
// Remote/local-machine sources cannot participate in a Vault snapshot.
// Let the CLI refuse them rather than claim a current disk artifact.
if (isHyperLink || isLocalLink || !file) throw new Error("Export source is not a local Vault file.");
await this.beforeFileRead(file);
if (this.terminate) return null;
}
if (file && markdownRendererRecursionWatcthdog.has(file)) {
new Notice(
`Loading of ${file.path}. Please check if there is an inifinite loop of one file embedded in the other.`,
@@ -1566,7 +1576,7 @@ export class EmbeddedFilesLoader {
if (loader.terminate) {
return;
}
const shouldForceReload = forceReloadFileIDs?.has(id);
const shouldForceReload = !!loader.beforeFileRead || forceReloadFileIDs?.has(id);
const deferredValidation = deferredCacheValidation?.get(id);
if (
cacheValidation === "validated" &&
@@ -1800,6 +1810,7 @@ export class EmbeddedFilesLoader {
excalidrawData.scene.elements,
);
for (const element of mermaidElements) {
if (fileIDWhiteList && !fileIDWhiteList.has(element.fileId)) continue;
yield createSafeLoadTask(
async () => {
if (loader.terminate) {
@@ -2118,7 +2129,7 @@ export class EmbeddedFilesLoader {
const requestedScale =
options?.pdfScale ?? this.plugin.settings.pdfScale;
const shouldUseCache =
!options?.bypassCache &&
!this.beforeFileRead && !options?.bypassCache &&
getImageCache().isReady() &&
(!options || this.plugin.settings.allowImageCacheInScene);
const cacheKey: ImageKey = {
+40
View File
@@ -54,3 +54,43 @@ export function addAppendUpdateCustomData(
}
return el;
}
/** Versioned, bounded descriptive image annotations for CLI previews (#3004). */
export const CLI_IMAGE_CUSTOM_DATA_KEY = "excalidrawCLI";
export type CLIImageMetadata = {
version: 1;
label?: string;
tags?: string[];
};
/** Ignore malformed/forward-versioned annotations without dropping other customData. */
export function getCLIImageMetadata(element: ExcalidrawImageElement): CLIImageMetadata | null {
const value: unknown = (element as ExcalidrawImageWithCustomData).customData?.[CLI_IMAGE_CUSTOM_DATA_KEY];
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const metadata = value as Record<string, unknown>;
if (metadata.version !== 1) return null;
return {
version: 1,
...(typeof metadata.label === "string" && metadata.label.length <= 80 ? { label: metadata.label } : {}),
...(Array.isArray(metadata.tags) && metadata.tags.length <= 12 && metadata.tags.every(tag => typeof tag === "string" && tag.length <= 32) ? { tags: metadata.tags as string[] } : {}),
};
}
/** Reject unbounded or invalid metadata before a guarded element mutation. */
export function cliImageMetadataPatch(element: ExcalidrawImageElement, label: unknown, tags: unknown): ExcalidrawCustomData {
const customData = element.customData as ExcalidrawCustomData | undefined;
const previous = customData?.[CLI_IMAGE_CUSTOM_DATA_KEY];
if (previous !== undefined && (!previous || typeof previous !== "object" || Array.isArray(previous) || previous.version !== 1)) throw new Error("Unsupported image metadata version; existing annotations were preserved.");
const next: Record<string, ExcalidrawCustomDataValue> = { ...(previous as Record<string, ExcalidrawCustomDataValue> | undefined), version: 1 };
if (label !== undefined) {
if (label !== null && (typeof label !== "string" || !label.trim() || label.length > 80)) throw new Error("Image label must be 1–80 characters or null to clear.");
if (label === null) delete next.label;
else next.label = label as string;
}
if (tags !== undefined) {
if (tags !== null && (!Array.isArray(tags) || tags.length > 12 || tags.some(tag => typeof tag !== "string" || !tag.trim() || tag.length > 32) || new Set(tags).size !== tags.length)) throw new Error("Image tags must be a list of up to 12 unique short strings or null to clear.");
if (tags === null) delete next.tags;
else next.tags = [...(tags as string[])];
}
return { ...(element.customData ?? {}), [CLI_IMAGE_CUSTOM_DATA_KEY]: next };
}
+7
View File
@@ -304,6 +304,7 @@ export async function getTemplate(
loader: EmbeddedFilesLoader,
depth: number,
convertMarkdownLinksToObsidianURLs: boolean = false,
cliFileIdAllowList?: Set<FileId>, // #3004 -- CLI export may load only images needed by its preview policy
): Promise<{
elements: ExcalidrawElement[];
appState: Partial<AppState>;
@@ -434,6 +435,11 @@ export async function getTemplate(
);
}
if (cliFileIdAllowList) {
// #3004: intersect with existing group/frame filters; never broaden the loader scope.
fileIDWhiteList = new Set(fileIDWhiteList ? [...fileIDWhiteList].filter(id => cliFileIdAllowList.has(id)) : cliFileIdAllowList);
}
if (loadFiles) {
//debug({where:"getTemplate",template:file.name,loader:loader.uid});
await loader.loadSceneFiles({
@@ -458,6 +464,7 @@ export async function getTemplate(
},
depth,
fileIDWhiteList,
validationConcurrency: loader.beforeFileRead ? 1 : undefined,
});
}
+30
View File
@@ -0,0 +1,30 @@
# CLI image-preview validation (#3004)
Generated in the dedicated `excalidraw-test` vault on macOS with Obsidian 1.14.4
(installer 1.14.0), using the declared Excalidraw 0.18.143 package. These are
synthetic, non-private fixtures produced by the native CLI regression on
2026-10-15. The runner retains the full matrix beside its `report.json`.
Compare [original](light-original.png), [mixed](light-mixed.png), and
[thumbnails](live-thumbnails.png): the same source appears uncropped, cropped,
mirrored, rotated with reduced opacity, and clipped inside a frame. The original
also includes a small SVG icon and transparent raster regions. Thumbnail crops
and frame clipping retain their placement. Placeholder labels intentionally rotate
and mirror with the image. The [dark placeholders](dark-placeholder.png) exercise
Unicode and XML punctuation; [placeholder SVG](light-placeholder.svg) contains no
original image payloads. Preview generation preserved source text, elements, and
dirty state in the regression.
The native feature assertions passed, including actual same-size/same-mtime disk
attachment replacement rejection. Its overall clean-error gate failed because
Obsidian reported repeated `ResizeObserver loop completed with undelivered
notifications` during teardown. A separate blank-popout control reproduced that
warning without preview operations. It is not suppressed. Popout inventory/export
also completed in a separate run, with the same teardown warning.
The optional native stress used 387 file records with 811,609,434 aggregate payload
characters, above V8's 536,870,888 single-string limit. Stable reads, last-byte
invalidation, stale apply refusal, and placeholder export passed. Shared immutable
backing strings make this an allocation-path regression, not a real 570 MB drawing
or peak-memory benchmark. That drawing was unavailable. Windows and physical mobile
were not tested.
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@@ -0,0 +1,2 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 660 352.3216819549389" width="660" height="352.3216819549389" class="excalidraw-svg"><!-- svg-source:excalidraw --><metadata></metadata><defs><symbol id="image-cliwSgvPFv3-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMjAwIDEwMCI+PHJlY3QgeD0iMC41IiB5PSIwLjUiIHdpZHRoPSIxOTkiIGhlaWdodD0iOTkiIGZpbGw9IiNmNGY0ZjQiIHN0cm9rZT0iIzg4OCIgc3Ryb2tlLWRhc2hhcnJheT0iNSA0Ii8+PHRleHQgeD0iMTAwIiB5PSI1MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IiM1NTUiIHRleHRMZW5ndGg9IjE1NCIgbGVuZ3RoQWRqdXN0PSJzcGFjaW5nQW5kR2x5cGhzIj4mIzczOyYjMTA5OyYjOTc7JiMxMDM7JiMxMDE7JiMzMjsmIzEwMjsmIzExNDsmIzk3OyYjMTA5OyYjMTAxOyYjMTA1OyYjMTA5OyYjMTAzOzwvdGV4dD48L3N2Zz4=" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><symbol id="image-cliiKaxqE91-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMjAwIDEwMCI+PHJlY3QgeD0iMC41IiB5PSIwLjUiIHdpZHRoPSIxOTkiIGhlaWdodD0iOTkiIGZpbGw9IiNmNGY0ZjQiIHN0cm9rZT0iIzg4OCIgc3Ryb2tlLWRhc2hhcnJheT0iNSA0Ii8+PHRleHQgeD0iMTAwIiB5PSI1MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IiM1NTUiIHRleHRMZW5ndGg9IjE1NCIgbGVuZ3RoQWRqdXN0PSJzcGFjaW5nQW5kR2x5cGhzIj4mIzczOyYjMTA5OyYjOTc7JiMxMDM7JiMxMDE7JiMzMjsmIzExNjsmIzExNzsmIzExNDsmIzExMDsmIzQ4OyYjNDg7JiM0ODsmIzQ5OzwvdGV4dD48L3N2Zz4=" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><symbol id="image-cliTCdzt7qk-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMjAwIDEwMCI+PHJlY3QgeD0iMC41IiB5PSIwLjUiIHdpZHRoPSIxOTkiIGhlaWdodD0iOTkiIGZpbGw9IiNmNGY0ZjQiIHN0cm9rZT0iIzg4OCIgc3Ryb2tlLWRhc2hhcnJheT0iNSA0Ii8+PHRleHQgeD0iMTAwIiB5PSI1MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IiM1NTUiIHRleHRMZW5ndGg9IjE1NCIgbGVuZ3RoQWRqdXN0PSJzcGFjaW5nQW5kR2x5cGhzIj4mIzczOyYjMTA5OyYjOTc7JiMxMDM7JiMxMDE7JiMzMjsmIzEwMjsmIzEwODsmIzEwNTsmIzExMjsmIzQ4OyYjNDg7JiM0ODsmIzQ5OzwvdGV4dD48L3N2Zz4=" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><symbol id="image-cliXAb8TNml-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMjAwIDEwMCI+PHJlY3QgeD0iMC41IiB5PSIwLjUiIHdpZHRoPSIxOTkiIGhlaWdodD0iOTkiIGZpbGw9IiNmNGY0ZjQiIHN0cm9rZT0iIzg4OCIgc3Ryb2tlLWRhc2hhcnJheT0iNSA0Ii8+PHRleHQgeD0iMTAwIiB5PSI1MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IiM1NTUiIHRleHRMZW5ndGg9Ijc3IiBsZW5ndGhBZGp1c3Q9InNwYWNpbmdBbmRHbHlwaHMiPiYjNjc7JiMxMTQ7JiMxMTE7JiMxMTI7JiMxMTI7JiMxMDE7JiMxMDA7PC90ZXh0Pjwvc3ZnPg==" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><symbol id="image-cliBqSHiL0x-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDQ4IDQ4Ij48cmVjdCB4PSIwLjUiIHk9IjAuNSIgd2lkdGg9IjQ3IiBoZWlnaHQ9IjQ3IiBmaWxsPSIjZjRmNGY0IiBzdHJva2U9IiM4ODgiIHN0cm9rZS1kYXNoYXJyYXk9IjUgNCIvPjx0ZXh0IHg9IjI0IiB5PSIyNCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iNC44IiBmaWxsPSIjNTU1IiB0ZXh0TGVuZ3RoPSIzNi45NjAwMDAwMDAwMDAwMSIgbGVuZ3RoQWRqdXN0PSJzcGFjaW5nQW5kR2x5cGhzIj4mIzczOyYjMTA5OyYjOTc7JiMxMDM7JiMxMDE7JiMzMjsmIzg5OyYjNTA7JiMxMTk7JiMxMTk7JiM4MjsmIzEwMjsmIzEwMDsmIzg1OzwvdGV4dD48L3N2Zz4=" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><symbol id="image-cliluvhWIm8-no-invert-svg"><image href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMjAwIDEwMCI+PHJlY3QgeD0iMC41IiB5PSIwLjUiIHdpZHRoPSIxOTkiIGhlaWdodD0iOTkiIGZpbGw9IiNmNGY0ZjQiIHN0cm9rZT0iIzg4OCIgc3Ryb2tlLWRhc2hhcnJheT0iNSA0Ii8+PHRleHQgeD0iMTAwIiB5PSI1MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IiM1NTUiIHRleHRMZW5ndGg9IjE3NiIgbGVuZ3RoQWRqdXN0PSJzcGFjaW5nQW5kR2x5cGhzIj4mIzgyOyYjMTAxOyYjMTAwOyYjMzI7JiMzODsmIzMyOyYjNjA7JiMxMDM7JiMxMTQ7JiMxMDE7JiMxMDE7JiMxMTA7JiM2MjsmIzMyOyYjMjM0MzM7JiMyMDg0MDs8L3RleHQ+PC9zdmc+" preserveAspectRatio="none" width="100%" height="100%"></image></symbol><clipPath id="IUf-0uZrCedXjpjAs_8aM"><rect transform="translate(510 30.5) rotate(0 70 70)" width="140" height="140" rx="8" ry="8"></rect></clipPath><style class="style-fonts">
</style></defs><rect x="0" y="0" width="660" height="352.3216819549389" fill="#FFFFFF"></rect><g transform="translate(10 40.5) rotate(0 100 50)"><use href="#image-cliluvhWIm8-no-invert-svg" width="200" height="100" opacity="1"></use></g><g transform="translate(590 260.5) rotate(0 24 24)"><use href="#image-cliBqSHiL0x-no-invert-svg" width="48" height="48" opacity="1"></use></g><g transform="translate(250 40.5) rotate(0 100 50)"><use href="#image-cliXAb8TNml-no-invert-svg" width="200" height="100" opacity="1"></use></g><g transform="translate(10 190.5) rotate(0 100 50)"><use href="#image-cliTCdzt7qk-no-invert-svg" width="200" height="100" opacity="1" transform="translate(100 50) scale(-1 1) translate(-100 -50)"></use></g><g transform="translate(250 200.5) rotate(28.64788975654116 100 50)"><use href="#image-cliiKaxqE91-no-invert-svg" width="200" height="100" opacity="0.65"></use></g><g clip-path="url(#IUf-0uZrCedXjpjAs_8aM)"><g transform="translate(500 40.5) rotate(11.459155902616464 100 50)"><use href="#image-cliwSgvPFv3-no-invert-svg" width="200" height="100" opacity="1"></use></g></g><g transform="translate(510 10) rotate(0 25.29296875 8.75)"><text x="0" y="12.5302734375" font-family="Helvetica, sans-serif, Segoe UI Emoji" font-size="14px" fill="#999999" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">Clipping</text></g><rect transform="translate(510 30.5) rotate(0 70 70)" width="140px" height="140px" rx="8" ry="8" fill="none" stroke="#bbb" stroke-width="rgba(0, 0, 200, 0.04)"></rect></svg>

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB