# fabric-editor-sdk Public integration documentation: https://fabric-editor-sdk.pages.dev/example. That Pages project serves documentation only; the consuming sites host the immutable browser engine and codec assets described below. Private, versioned shared Fabric browser engine for Coffee Frame and EditGator. The engine runs in the browser. Hosting uses the consuming Pages deployment, not the former fabric-editor Worker. No database or secret is required. ## Integration Install the committed, SHA-256-checked package archive. In the remote Cloudflare build, call `installAssets(distDirectory)` from `fabric-editor-sdk/assets` after the website build. Route `/api/fabric-editor/*` to `handleFabricEditorRequest` from `fabric-editor-sdk/cloudflare-pages`, passing the incoming Request and the Pages `env.ASSETS` binding. Never forward these requests to a Worker. The facade preserves GET/HEAD, conditional requests, byte ranges and immutable release paths. It accepts only the packaged module graph. Cookies and bearer headers are not forwarded. The manifest keeps the existing browser contract, including the exact public limits previously provided by the Worker. Package 1.1.13 also serves every packaged license as `text/plain`; the facade checks exact media types for text, JavaScript and WASM separately. The earlier facade incorrectly expected JavaScript for `.txt` licenses and returned 502. The immutable engine files and their content-addressed releases are unchanged. Remote consumer tests cover all fourteen license paths, GET/HEAD and rejection of HTML/JavaScript substitutions. EditGator Full commit `5f7956fe`, deployment `80e356cf-fa45-4ec4-a622-1d3cce03ecba`, passes the SDK tests; all fourteen public licenses now match the immutable package bytes with HTTP 200 and immutable caching. CoffeeFrame Full commit `6d747d7`, deployment `eba3b424-9e98-4631-9cea-51d20294b5c4`, also passes the license tests; all fourteen public license files match the immutable input bytes there too. Release 1.1.44 includes only `sha256-b7bc9a3dfd73220c` with its third-party licenses. Canvas snapshots and copied selections use the public Canvas serializer so selected objects retain their world transforms. Capturing does not discard the active selection. The remote SDK tests compare transformed matrices for two non-centred objects after snapshot and clipboard round-trips. The Fabric drawer accepts `onDocumentMutation({ revision, reason })`. It emits one frozen notification per changed document commit, independently of visual selection/transform previews and legacy `onActionEnd`. Initialization and snapshot loading establish a baseline without notifying. Identical commits do not create notifications or history entries. Successful Undo/Redo notify after restoration; failed restoration leaves their stacks intact. Undo skips the current committed state and restores the preceding state immediately. Revisions increase within the editor lifetime. Consumers schedule page sync and autosave from this callback rather than from visual/action callbacks. Remote consumer tests execute the owning commit and history method bodies; browser gesture coverage remains a separate integration requirement. EditGator transform notifications retain `phase: live | commit` and add `gesture: move | rotate | resize | null` and `gesturePhase: start | update | end`. The first actual scaling event emits `resize/start` immediately; subsequent updates retain the bounded preview scheduler. Selection alone emits no resize notification. Product interfaces can retain dimensions until selection changes without treating movement or rotation as a resize. Resize and the general editor show source pixels outside the original reference. Straighten opts into `clipSourceToDocument` for a fixed original frame. Live source transforms reuse that clip; document synchronization compares accepted commands to avoid rebuilding the source raster on every angle update. Selection dimensions describe the selected image layer in document pixels. A `source-transform` command changes its placement, size and rotation inside the existing document; it does not resize the document canvas. `getImageEditDimensions(sourceWidth, sourceHeight, commands)` accounts for crop and quarter-turn commands, while `renderImageEdit` draws source transforms on that resulting canvas. Consumers must keep selection dimensions separate from export dimensions and explicitly apply `getImageResizeDimensions` and `resizeImageCanvas` when resizing the complete output. For example, changing a layer to 800×600 inside a 975×788 document preserves a 975×788 raster export unless the consumer separately requests output resizing. The bundled HEIC codec uses a fast preset and honors export quality. See [codec source and build notes](codecs/heic/README.md). On a synthetic 4032×3024 RGBA test, encoding fell from 17.4s to 9.3s at quality 75 on the same host; output was 12.6 MB versus 6.6 MB. These timings are not a mobile performance guarantee. The manifest and package expose the same single release. `npm pack --ignore-scripts` packages the reviewed source without building or querying any service. Website validation runs remotely through the native GitHub main → Cloudflare Pages workflow. Package 1.1.29 retains the same immutable runtime releases and extends facade verification to conditional and partial license responses in both release graphs. Tests preserve GET/HEAD, ETag and Range behavior and reject successful HTML substitutions for JavaScript modules and WebAssembly. Package 1.1.30 retains those runtime bytes and adds a transformed multi-selection Undo/Redo test comparing real Fabric world matrices before capture and after restoring each history state. Package 1.1.31 also verifies that a failed Redo preserves its cursor and document, and that a new commit after Undo discards the old Redo branch. Package 1.1.32 suppresses deferred selection notifications after destruction, before accessing disposed Fabric state or calling the consumer. Its regression test invokes a previously scheduled notification after destroying the drawer. Package 1.1.38 also verifies closed twenty-point drawing loops before a frame. Deferred text focus stops after destruction or removal. The package compares isolated export pixels for both a single object and a group, including overlapping unrelated layers, transparent or opaque backgrounds, negative coordinates, pan and zoom. Codec worker responses receive a dedicated same-origin CSP permitting WebAssembly. The document policy is unchanged. New immutable worker URLs prevent cached pre-fix security headers from continuing to block compression after upgrading. ## Universal interaction API Import `createToolInteraction` from `fabric-editor-sdk/interaction`. The same module owns the frame queue used by Fabric, bounded settings scheduling, validated product event transport, and action stage coordination. Call `begin(initial)` at gesture start, `update(sample)` for pointer samples, `commit(finalSample)` on release, `cancel()` on cancellation or target changes, and `dispose()` on teardown. `project` uses cached geometry and returns a precise draft; `visual` paints it without publishing document state. `values` publishes changed presentation values at most every 32ms, flushed immediately on commit. `onCommit` alone commits the gesture to the document. `onCancel` restores the initial presentation. Input notifications must never become commands back to the originating renderer. For expensive asynchronous previews use `effect`, `onEffectResult`, and `onError`: one effect runs at a time, only the latest queued request survives, and obsolete results cannot publish. `execute(operation, input)` is explicit and supplies an AbortSignal; obsolete results reject with AbortError. Non-abortable codec work still requires the product's target/run checks before applying its result. Adapters retain tool algorithms and rendering: Fabric owns transforms and strokes; HTML crop overlays use the frame queue; effects retain bounded work; codecs and remote operations only run on explicit execution. Draw adapters must retain their ordered stroke data rather than treating a path as one position. No application state, secret, network service, or Cloudflare Worker is added. Quarter-turn rotation preserves the fitted display scale, zoom, and screen center; resetting orientation restores the original bounds without refitting. The EditGator interactive editor accepts `setTool({id: 'view'})` for fixed image previews without selection, transform handles, or editing shortcuts. Viewport zoom remains available. Other tool modes retain their behavior. The HEIC binary disables dynamic JavaScript execution; its WASM test enforces the same restriction as the browser CSP. ## Source placement and undo history `setSourceTransform(command, {phase: 'commit'})` records a changed source placement in native history and emits one normal `onChange` callback. Repeating an identical committed state does not create another history entry. Null commits reset source placement and remain reversible. Preview is noncommitting. `setSourceTransform(null, {phase: 'cancel'})` restores the pre-preview placement without a document callback/history entry; it returns false without an active preview. Loading/rebuilding a document invalidates the previous preview baseline. The history tests execute the actual method bodies with isolated rendering doubles. They prove command/history/callback transitions, not browser geometry, pixel output or integration with an existing consumer. Baked watermarks accept a decoded image, repeated in staggered rows through the shared renderer. Image dimensions, asset budgets, and baked mode are validated. Text watermarks retain their existing command contract. Interactive image movement publishes presentation values through the shared 32ms scheduler and flushes the exact transform on commit. Neutral adjustments reuse the original render canvas without reading or rewriting pixels. `inspectImageEditTransparency` defers work off the commit callback and checks every output pixel in bounded 256×256 tiles, yielding after a 4ms work budget. It supports cancellation and releases its temporary raster on completion/abort. This is an exact alpha scan, not a reduced-resolution estimate. Image Editor select mode accepts optional boolean `rotationOnly`. It shows the native Fabric rotation handle and connector, hides all resize handles, and selects the first image when entering this mode without an image selected. Live and committed rotation use the existing transform callbacks and history. Leaving rotation mode restores the normal resize handles. Crop allows background viewport panning in both complete and standalone editors. Object selection/movement remains disabled. Viewport callbacks keep the crop overlay aligned, and pinch start cancels an active pan. Standalone empty-touch page scrolling yields to viewport panning while Crop is active. Canvas snapshots and hit-testing use the universal `excludeFromExport` and visibility flags. The legacy guide object is removed only when loading saved snapshots, preserving compatibility without repeated name-based exclusions. Canvas `loadCanvasSnapshot(snapshot, { history })` and `loadSnapshot` accept `history: "reset"` (default) or `"preserve"`. A successful reset replaces both history stacks with the loaded document baseline, without a mutation event. Undo/Redo restore with preserve internally. Consumers reset at page/document boundaries, including empty pages; they do not clear the outgoing document as a historical edit. Invalid policies fail before loading. Page navigation thus intentionally discards that page's session Undo/Redo history. Snapshot loads decode through the public Fabric `util.enlivenObjects` API while the current scene remains visible and editable. Before the synchronous scene commit, the drawer checks load generation and the current document snapshot. Only the latest admitted load can commit. Any intervening document edit rejects replacement with `FABRIC_EDITOR.SNAPSHOT_LOAD_DOCUMENT_CHANGED`; a superseded or destroyed load rejects with `FABRIC_EDITOR.SNAPSHOT_LOAD_SUPERSEDED`. Both errors carry `documentCommit: false`; consumers must preserve the current scene rather than rolling it back. Rejected prepared objects are disposed. The restoring guard exists only during the synchronous scene swap, not during decoding. Internal paste regenerates `studioNodeId` recursively on cloned objects, group children and clip paths, avoiding all existing document IDs. Opaque asset references remain unchanged. Snapshot loading rejects duplicate IDs across objects, nested groups and clip paths before decoding. Present IDs must be strings; missing legacy IDs remain accepted. Rejections before any scene mutation carry `documentCommit: false`, including decoding errors. The remote consumer gate checks real Fabric group serialization and targeted image asset attachment/replacement through the owning drawer methods. Image add/replace and internal paste accept an optional `signal` and combine it with editor lifetime cancellation. After decoding they recheck lifetime and document generation; replacement also requires the original target instance to remain in the current document. Stale prepared objects are disposed without insertion, selection or success notification. Image decode cancellation clears timers, handlers and source; Fabric hydration receives the lifetime signal. Clear/load document boundaries invalidate pending edits. `destroy()` aborts synchronously and returns the same `Promise` on repeated calls. It settles after Fabric disposal: true on success, false on a reported disposal failure. Keyboard paste/Undo/Redo failures are handled by `onOperationError(error, operation)` when supplied, otherwise by the runtime diagnostic reporter; they never leave an unattended rejection. The Canva initializer requires a `memoryBudget` object containing ten positive safe integer fields: `maxCanvasDimension`, `maxExportBytes`, `maxExportPixels`, `maxHistoryBytes`, `maxImageBytes`, `maxImageDimension`, `maxImagePixels`, `maxSnapshotBytes`, `maxSnapshotObjects`, and `maxSnapshotPoints`. Canvas dimensions apply to the backing canvas after render density; image dimensions apply to decoded source pixels. Image bytes/pixels/dimensions and stroke points also respect the manifest caps. Snapshots include nested groups and clip paths in object/point accounting. Undo and redo share the history byte budget; the current baseline must fit before history entries are replaced. Raster admission reads PNG, JPEG, GIF and WebP dimensions from encoded headers. Unknown headers reject explicitly before browser decoding. URL sources use bounded streaming reads, and prepared object URLs are released after decoding while Fabric serialization retains the original source. Export pixel bounds precede rendering; encoded PNG bytes are checked before returning the result. `tests/canvas-resource-budget.test.js` contains boundary and owning-method verification for remote consumer execution. The remote consumer Full gate executes these boundary checks. Selection PNG export renders world-space clones on an independent canvas with a transparent default background. An explicit background color is supported. The working viewport, original objects and unrelated layers remain outside that render. Missing or removed selections reject explicitly. The remote consumer provides @napi-rs/canvas 1.0.10 for real Fabric PNG/pixel comparisons in tests/canvas-selection-export.test.js; no native renderer enters browser assets. Native drawing accumulates ordered move/coalesced samples before frame scheduling. The scheduler throttles preview painting only. Pointer cancellation and a stroke point-cap rejection clear pending rendering without committing a stroke. The owning handlers are covered by tests/canvas-stroke-samples.test.js in remote Full. Cancellation verification covers Draw, Brush, Rectangle and Ellipse with omitted coordinates, no object/action commit, and exactly one commit for equivalent pointerup. This package retains the same immutable runtime release. Canva accepts `shortcutsEnabled: () => boolean`, evaluated on every keyboard event. The callback defaults to true; the drawer additionally requires a connected, visible container and a live instance. Consumers own route/modal admission through that public predicate. Toggling admission preserves instance, selection and clipboard. Default image placement maps the visible viewport center through its inverse matrix. Explicit x/y remain scene coordinates. `fitBox` defaults to scene coordinates; `fitBoxSpace: "viewport"` maps a rectangle in canvas viewport pixels to scene space. The viewport fit conversion supports the same affine matrix as placement. Clipboard paste rechecks the live snapshot and history budgets after decoding, before inserting clones or changing selection. Rejected clones are disposed. The remote pixel gate also covers real image selections with clip paths and shadows, overlapping images, transparent/opaque backgrounds and pan/zoom. Attaching an image asset reference commits history and emits the document mutation signal once when persisted fields change. Reattaching identical references emits no document mutation. Snapshot/history budget rejection restores the original reference fields before returning the error, without changing history or selection. ## Pages publication commands From this repository, publish canonical main with `github-publish-main "message"`. The shared launcher at scripts/project-command.mjs owns build admission and Fast/Full selection. Pages runs `npm run build:cloudflare`; a single `[cloudflare:full]` commit marker additionally runs the guarded `npm run check:full` after generating the same output. Local dev/build/test/deploy aliases are blocked. `publication.json` requires verification of the exact deployed commit. Install Git hooks with `git config core.hooksPath git-hooks`. No install lifecycle hook is added to packaged SDK consumers; their immutable archives remain unchanged. Canvas image watermarks prepare every selected image before committing any target. Decode failures, cancellation, navigation, disposal or a concurrent document edit leave the targets unchanged. Snapshot/history admission failures restore all image sources. A successful batch emits one document mutation for autosave. Remote contract tests exercise these paths through the owning watermark method with controlled image decoding and storage-free fixtures. Legacy image identities are normalized recursively during snapshot admission, without modifying the caller snapshot or emitting a document mutation. Existing identities are preserved. Selection identity queries never change the document.