diff --git a/cep.config.ts b/cep.config.ts index b2bb9c33..e735f82b 100644 --- a/cep.config.ts +++ b/cep.config.ts @@ -19,6 +19,15 @@ const isDevelopmentBuild = const startingDebugPort = Number( process.env.CEP_DEBUG_BASE ?? (isDevelopmentBuild ? 9170 : 8970), ); + +/** + * First port of the OS ephemeral/dynamic range on macOS and Windows + * (49152-65535). `.debug` ports are baked into the bundle at build time and + * cannot be reprobed on the machine that installs it, so they must stay below + * this floor: Windows Hyper-V/WSL `excludedportrange` reservations live in the + * ephemeral range and made CEPHtmlEngine fail to bind devtools there (#682). + */ +const CEP_DEBUG_EPHEMERAL_PORT_FLOOR = 49152; const disableGpu = /^(1|true|yes)$/i.test( String(process.env.CEP_DISABLE_GPU ?? ""), ); @@ -60,6 +69,23 @@ export const CEP_EXTENSION_BUNDLE_ID = isDevelopmentBuild ? "app.ty-plus.dev" : "app.ty-plus"; +/** + * Window>Extensions menu label per panel. Dev and release bundles can be + * installed side by side (#86 / ADR-0005), but AE resolves + * `findMenuCommandId`/`executeCommand` by menu name and identical labels + * made dev and release entries ambiguous (#835). Dev labels get a ` dev` + * suffix so they never collide with the release labels, which must stay + * exactly `ty-plus` / `ty-plus panel N` for installed users. + */ +const panelMenuDisplayName = (panelNumber: number): string => { + if (isDevelopmentBuild) { + return panelNumber === 1 + ? "ty-plus dev" + : `ty-plus dev panel ${panelNumber}`; + } + return panelNumber === 1 ? "ty-plus" : `ty-plus panel ${panelNumber}`; +}; + export const OPERATION_WORKER_EXPECTED_TRUST_MODE = isDevelopmentBuild ? DEVELOPMENT_UNSIGNED_TRUST_MODE : RELEASE_TRUST_MODE; @@ -140,7 +166,7 @@ const config: CEP_Config = { mainPath: CEP_PANEL_HTML_BY_NUMBER[1], scriptPath: CEP_HOST_SCRIPT, name: "panel1", - panelDisplayName: "ty-plus", + panelDisplayName: panelMenuDisplayName(1), autoVisible: true, type: "Panel", width: CEP_PANEL_FRAME.width, @@ -150,7 +176,7 @@ const config: CEP_Config = { mainPath: CEP_PANEL_HTML_BY_NUMBER[panelNumber], scriptPath: CEP_HOST_SCRIPT, name: `panel${panelNumber}`, - panelDisplayName: `ty-plus panel ${panelNumber}`, + panelDisplayName: panelMenuDisplayName(panelNumber), // Must stay true: AE/CEF often leaves aux panels blank from the Window menu when false // (Motion Tools Pro uses true for every panel row; see docs/no-use/decisions.md). autoVisible: true, @@ -309,4 +335,22 @@ const config: CEP_Config = { copyAssets: [], copyZipAssets: [], }; + +// vite-cep-plugin assigns `.debug` ports sequentially from +// `startingDebugPort`, one per panel per host. Warn when the span reaches the +// OS ephemeral range — the baked ports may fail to bind on some machines. +const lastDebugPort = + startingDebugPort + config.panels.length * config.hosts.length - 1; +if ( + startingDebugPort < 1024 || + lastDebugPort >= CEP_DEBUG_EPHEMERAL_PORT_FLOOR +) { + console.warn( + `[cep.config] .debug port span ${startingDebugPort}-${lastDebugPort} ` + + `reaches the OS ephemeral range (>=${CEP_DEBUG_EPHEMERAL_PORT_FLOOR}); ` + + "devtools/CDP may fail to bind on machines with reserved port ranges " + + "(#682). Set CEP_DEBUG_BASE below 49152.", + ); +} + export default config; diff --git a/docs/architecture/quality/ui-render-contract.md b/docs/architecture/quality/ui-render-contract.md index 65f9cb38..96a544a7 100644 --- a/docs/architecture/quality/ui-render-contract.md +++ b/docs/architecture/quality/ui-render-contract.md @@ -21,6 +21,8 @@ | DOM adapter | `measureBox` / `isRendered` / `assertWithinViewport` / `assertWithinAncestor` / `assertNotClipped` / `assertNoOverlap` / `assertRendered` | `storybook` browser project のみ | | 複合監査 | `auditCanvas` / `expectCanvasLayout` | 同上 | | 操作 settle | `hoverAndAssert` / `focusAndAssert` / `nextPaint` | 同上 | +| 描画 fit(#726) | `fit.ts` の `expectContainerWidthTracking` / `assertMatchesWidth` / `assertSingleRow` / `assertIconAspect` / `assertScrollbarThumbVisible` | 同上 | +| 状態別 border(#726) | `border.ts` の `assertBorderToken`(`resolveBorderToken` probe 経由) | 同上 | | negative 証明 | `captureLayoutError` + `contract.stories.tsx` | 同上 | ### `expectCanvasLayout(root, options)` が検査するもの @@ -100,6 +102,27 @@ geometry 層は `layout.test.ts`(unit project)で境界値を固定する。 +## 描画結果契約(Issue #726) + +#721–#724 / #730–#736 / #741 の退行は全て「共有スタイル/トークンを使って +いる」ことを品質とみなした結果、最終描画結果の契約違反を検出できな +かった。`fit.ts` はその層の共有 vocabulary で、computed style ではなく +**実測値**(`getBoundingClientRect` / `clientWidth` / `scrollHeight`)を +assert する。CEF99 は container query 非対応(#700)のため、全て px 実測。 + +| 契約 | helper | consumer 例 | +| --- | --- | --- | +| コンテナ幅追従 | `expectContainerWidthTracking` + `assertMatchesWidth` | `SearchField/TracksContainerWidth`, `QuickActions/ActionList/SearchFieldTracksWidgetWidth` | +| strip 単一行 | `assertSingleRow` | `SegmentedControl/AdaptiveLabels`, `OverflowScrollsHorizontally` | +| 状態別 border token | `assertBorderToken` | `Button/AllVariants`, `SegmentedControl/HoveredSegment`, `Input/Focused`(focus→`interactive.focus`) | +| アイコン比率 | `assertIconAspect` | `Icon/KeepsAspectRatio` | +| scroll affordance | `assertScrollbarThumbVisible` | `ScrollArea/Default` | + +機械判定できない境界(helper の doc comment にも明記): アイコンの +グリフ品質・ストロークの見た目、`scrollbar-color` を解釈しない環境での +thumb 描画、ラベル内容の「読みやすさ」(幾何と文字列差し替えは検査するが +可読性は人間受入)。 + ## 既知の限界 - audit は interactive 要素とページ overflow が対象。非 interactive な diff --git a/docs/architecture/ui-reconstruction/storybook.md b/docs/architecture/ui-reconstruction/storybook.md index 366de6b2..70a0aba0 100644 --- a/docs/architecture/ui-reconstruction/storybook.md +++ b/docs/architecture/ui-reconstruction/storybook.md @@ -245,9 +245,12 @@ header に inline で書いてある。 - `core/easing/Component.stories.tsx`, `core/align/Component.stories.tsx` — `useWidgetRuntime` が noop に fallback するため storage 連携は無効 (Wave 4.3)。 -- `workspace/surface/GridTile.stories.tsx` — `Widget` → - `renderDescriptor` の依存ツリーが Storybook decorator chain に未供給 - (Wave 4.1)。 +- `workspace/surface/GridTile.stories.tsx` — 解消済み (Issue #719)。 + `Widget → renderDescriptor` は実 widget registry (`import.meta.glob` + eager aggregation) と既存 decorator chain (`PanelStateProvider` / + `useWidgetRuntime` noop fallback) でそのまま render できるため、 + 追加の seam は不要だった。preset / widget (menu, align) / missing-row / + selected / menu-open / hover の story を実 component でカバー。 - `preset/group/{WorkspaceCatalogTileBody,WorkspaceLayer,PanelOverlay}.stories.tsx` — `PanelContext` 未供給 (Wave 4.2)。 diff --git a/docs/architecture/widget/tutorial-mode.md b/docs/architecture/widget/tutorial-mode.md index 2f697f5f..7f92d6fc 100644 --- a/docs/architecture/widget/tutorial-mode.md +++ b/docs/architecture/widget/tutorial-mode.md @@ -71,6 +71,13 @@ spotlight/coach-mark ツアー(画面を順にハイライトして進める - B の hint は widget の初回 mount(その widget 種別で初めて workspace に置かれた時) のみ発火し、dismiss/timeout/操作開始のいずれかで消える。再表示は settings の 「tips を再表示」相当の手段からのみ。 +- ツアーの同時表示は **1 パネル surface あたり最大 1 件**とする(Issue #823)。 + 別 widget 種別の初回条件が同時に満たされた場合、先に mount された側が開き、 + 残りは FIFO でキューイングして現在のツアー終了後に順に開く。ツアー保持中に + widget が unmount された場合もスロットを解放する。 + パネルを跨ぐ同時表示はスコープ外: `panel1`…`panel5` は別 CEP surface で + 視覚的に重ならず、seen/dismiss は `settings/tutorial-state.json` 経由で + 既に共有されている。 - A の help は明示的なユーザー操作でのみ開き、勝手に割り込まない。 - いずれの UI も既存 ErrorBoundary / surface 縮退の内側に置き、tutorial 側の失敗が widget 本体を巻き込まない。 diff --git a/docs/verification/distributed-0-13-1/README.md b/docs/verification/distributed-0-13-1/README.md new file mode 100644 index 00000000..f9f2c4de --- /dev/null +++ b/docs/verification/distributed-0-13-1/README.md @@ -0,0 +1,41 @@ +# v0.13.1 配布物の実利用経路検証 (Issue #666) + +公開済み GitHub Release `v0.13.1` の配布物を、開発用 dev bundle ではなく +実際のインストール経路で配置し、After Effects 実機上で起動・ +アップデート検出を確認した記録。対象 Issue: #666。 + +## 手順 + +- macOS: 公開 `ty-plus-v0.13.1-macos.zip` を + `~/Library/Application Support/Adobe/CEP/extensions/app.ty-plus` に展開配置。 + 旧版からの更新検出確認のため、別途 `ty-plus-v0.13.0-macos.zip` を + manifest Version のみ 0.13.1 → 0.13.0 に書き換えた検証用コピーを同経路に配置して確認。 +- Windows: `device-windows` (Windows 11 + AE2027) の + `%APPDATA%\Adobe\CEP\extensions\app.ty-plus` に公開 + `ty-plus-v0.13.1-windows.zip` を配置。既存インストールは v0.10.3。 +- いずれも Window > Extensions からパネルを起動し、Settings > Updates を + CDP (`Page.captureScreenshot`) で撮影。 + +## 証跡 + +| ファイル | 環境 | 内容 | +| --- | --- | --- | +| `macos-update-available-0.13.0.png` | macOS / AE2027 | Installed 0.13.0 → 「新しいバージョンがあります: 0.13.1」 | +| `macos-up-to-date-0.13.1.png` | macOS / AE2027 | Installed 0.13.1 → 「最新です」 | +| `windows-update-available-0.10.3.png` | Windows / AE2027 | Installed 0.10.3 → 「New version available: 0.13.1」 | +| `windows-up-to-date-0.13.1.png` | Windows / AE2027 | Installed 0.13.1 → 「Up to date」 | + +## 結果 + +- 両 OS とも配布 zip の展開・CEP への配置・AE からの起動を確認。 +- アプリ内更新検出は双方向で正常: 旧版 (0.13.0 / 0.10.3) から 0.13.1 を + 「利用可能」と判定し、0.13.1 自身は「最新」と判定した。 +- 製品不具合は検出されなかった。 + +## 残件 + +- Windows 側で旧 `ty-plus` 0.10.3 ディレクトリ (system 領域 + `C:\Program Files (x86)\Common Files\Adobe\CEP\extensions\`) の置き換えは + 管理者権限が必要で未実施。0.13.1 は user 領域に別フォルダ名で配置して検証した。 +- feed 判定ロジック自体は `src/management/online/update/feed.ts` と + GitHub Releases API に対する contract test で担保済み。 diff --git a/docs/verification/distributed-0-13-1/macos-up-to-date-0.13.1.png b/docs/verification/distributed-0-13-1/macos-up-to-date-0.13.1.png new file mode 100644 index 00000000..5605c1dc Binary files /dev/null and b/docs/verification/distributed-0-13-1/macos-up-to-date-0.13.1.png differ diff --git a/docs/verification/distributed-0-13-1/macos-update-available-0.13.0.png b/docs/verification/distributed-0-13-1/macos-update-available-0.13.0.png new file mode 100644 index 00000000..6335c100 Binary files /dev/null and b/docs/verification/distributed-0-13-1/macos-update-available-0.13.0.png differ diff --git a/docs/verification/distributed-0-13-1/windows-up-to-date-0.13.1.png b/docs/verification/distributed-0-13-1/windows-up-to-date-0.13.1.png new file mode 100644 index 00000000..be580c89 Binary files /dev/null and b/docs/verification/distributed-0-13-1/windows-up-to-date-0.13.1.png differ diff --git a/docs/verification/distributed-0-13-1/windows-update-available-0.10.3.png b/docs/verification/distributed-0-13-1/windows-update-available-0.10.3.png new file mode 100644 index 00000000..e5d827af Binary files /dev/null and b/docs/verification/distributed-0-13-1/windows-update-available-0.10.3.png differ diff --git a/docs/verification/e2e-acceptance/README.md b/docs/verification/e2e-acceptance/README.md index 68cff6ed..7d6f86e1 100644 --- a/docs/verification/e2e-acceptance/README.md +++ b/docs/verification/e2e-acceptance/README.md @@ -26,7 +26,7 @@ ## 実行方法 -自動化ハーネスは `scripts/verify/e2e/` にある。前提: 対象ビルドが CEP extensions にインストール済みで、After Effects が起動し対象パネルが開いていること(パネルを開く操作自体が UC の対象になる場合を除く)。 +自動化ハーネスは `scripts/verify/e2e/` にある。前提: 対象ビルドが CEP extensions にインストール済みで、After Effects が起動していること。パネルが開いていない場合でも `--ensure-panels` を付けると、ハーネスが ae-a8n の in-AE dispatcher 経由で AE へ attach し、Window メニューコマンド(先頭パネル)と `requestOpenExtension`(残り)でパネルを自律的に開く。dispatcher の導入は `ae-a8n dispatcher prepare` + `ae-a8n startup install`(`a8n-dispatcher.jsx` が `/Scripts/Startup` に置かれ、AE 起動時に自己活性化。heartbeat は `~/.ae-a8n/dispatcher`)。Windows ではこの dispatcher 経路が唯一の attach 手段である。フラグなしでは従来どおり live surface が無ければ即座に失敗する。 ```sh # dev build の例。managed root は AE インストール内の ty-plus-init.json から自動検出する diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/a8n-session.json new file mode 100644 index 00000000..05b0329d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\catalog\\ae-session\\staging\\a8n-host.js", + "pid": 109648 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/trace.jsonl new file mode 100644 index 00000000..fd6a4e10 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:09:42.726Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/run.json new file mode 100644 index 00000000..d2ea1a91 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/run.json @@ -0,0 +1,75 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "catalog", + "capturedAt": "2026-11-28T19:09:52.770Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-09-42-735Z-109648/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-09-42-735Z-109648/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:09:52.768Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 1, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-C15", + "title": "preset with missing asset: record survives boot, host verify reports missing", + "status": "PASS", + "detail": "stale record 19de8f96-82ad-4a2b-a0f5-849d4f89e628 → /tmp/ty-plus-e2e-missing-e315d7a7-b81c-4624-af80-77becfb3b8f7.ffx", + "checks": [ + { + "name": "panel boots with workspace grid after stale record added", + "ok": true, + "detail": "body=67796 grid=true tiles=7" + }, + { + "name": "stale preset record not dropped or rewritten on boot", + "ok": true, + "detail": "filePath=/tmp/ty-plus-e2e-missing-e315d7a7-b81c-4624-af80-77becfb3b8f7.ffx" + }, + { + "name": "sibling preset records unaffected", + "ok": true, + "detail": "before=3 after=4" + }, + { + "name": "host verifyPresetAsset reports exists:false for stale path", + "ok": true, + "detail": "raw={\"ok\":true,\"hostId\":\"after-effects\",\"value\":{\"exists\":false,\"path\":\"C:\\\\tmp\\\\ty-plus-e2e-missing-e315d7a7-b81c-4624-af80-77becfb3b8f7.ffx\"}}" + }, + { + "name": "presets/presets.json restored after case", + "ok": true, + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-09-42-735Z-109648\\ty-plus\\presets\\presets.json 888 bytes" + } + ], + "evidence": [], + "durationMs": 3298 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/sandbox-integrity.json new file mode 100644 index 00000000..d21dd69b --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/catalog/sandbox-integrity.json @@ -0,0 +1,11 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:09:52.768Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/a8n-session.json new file mode 100644 index 00000000..1277f2e6 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\debug\\ae-session\\staging\\a8n-host.js", + "pid": 67568 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/trace.jsonl new file mode 100644 index 00000000..78738215 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:09:54.401Z","op":"session.launch","status":"error","durationMs":0,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/run.json new file mode 100644 index 00000000..5ba7b978 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/run.json @@ -0,0 +1,117 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "debug", + "capturedAt": "2026-11-28T19:10:33.788Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-09-54-409Z-67568/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-09-54-409Z-67568/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:10:33.785Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 2, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-G02", + "title": "debug console reopen replays previously logged messages", + "status": "PASS", + "detail": "close → reopen replay", + "checks": [ + { + "name": "marker persisted to shared log store", + "ok": true, + "detail": "in ty_plus_debug_logs_v1" + }, + { + "name": "debug console opens", + "ok": true, + "detail": "live" + }, + { + "name": "marker message visible in first open", + "ok": true, + "detail": "msgs=128 marker=true" + }, + { + "name": "debug console closes", + "ok": true, + "detail": "closed" + }, + { + "name": "debug console reopens", + "ok": true, + "detail": "live" + }, + { + "name": "reopened console replays history (msg count > 0)", + "ok": true, + "detail": "msgs=128 (first open had 128)" + }, + { + "name": "replayed history includes pre-close marker", + "ok": true, + "detail": "hasMarker=true" + } + ], + "evidence": [], + "durationMs": 23253 + }, + { + "uc": "UC-G03", + "title": "operation worker verify: spawn → accept → result → exit", + "status": "PASS", + "detail": "worker pid=115168 sha=afddef100f91", + "checks": [ + { + "name": "rowCount > 0", + "ok": true, + "detail": "rows=511" + }, + { + "name": "progress stages reach finished", + "ok": true, + "detail": "discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>discovering>finished" + }, + { + "name": "worker accepted + final response + stdout EOF + exit 0", + "ok": true, + "detail": "accepted=true final=true eof=true exit=0" + } + ], + "evidence": [ + "uc-g03-operation-worker.json" + ], + "durationMs": 3698 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/sandbox-integrity.json new file mode 100644 index 00000000..f330da6e --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:10:33.785Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/uc-g03-operation-worker.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/uc-g03-operation-worker.json new file mode 100644 index 00000000..d2cb50d1 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/debug/uc-g03-operation-worker.json @@ -0,0 +1,532 @@ +{ + "ok": true, + "worker": { + "artifactRelativePath": "worker/versions/afddef100f9145db51de50e0752c85b7eeeaff091c1481e9fae302c1870d4161/windows/operation-worker.exe", + "artifactSha256": "afddef100f9145db51de50e0752c85b7eeeaff091c1481e9fae302c1870d4161", + "pid": 115168, + "requestId": "request-9d3f0fff-8ef7-423b-8931-5f46cf2efbdb", + "sessionId": "ae-1795893023577", + "accepted": true, + "finalResponse": true, + "stdoutEof": true, + "closeExitCode": 0 + }, + "rowCount": 511, + "warningCount": 0, + "progressStages": [ + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "discovering", + "finished" + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/a8n-session.json new file mode 100644 index 00000000..7120f6a8 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\host\\ae-session\\staging\\a8n-host.js", + "pid": 34448 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/trace.jsonl new file mode 100644 index 00000000..02b80633 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:10:35.456Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/run.json new file mode 100644 index 00000000..def987f7 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/run.json @@ -0,0 +1,65 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "host", + "capturedAt": "2026-11-28T19:10:47.216Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-10-35-480Z-34448/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-10-35-480Z-34448/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:10:47.215Z", + "driftBeforeRepair": { + "changed": 3, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json", + "cache/layout-undo/panel-1/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 1, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-A04", + "title": "resident host contract answers getHostContext with app context", + "status": "PASS", + "detail": "AE 27.0x78", + "checks": [ + { + "name": "app.version responds", + "ok": true, + "detail": "27.0x78" + }, + { + "name": "getHostContext returns structured host context", + "ok": true, + "detail": "raw={\"ok\":true,\"hostId\":\"after-effects\",\"value\":{\"appRoot\":\"D:\\\\4_apps\\\\adobe\\\\Adobe After Effects 2027/support files\",\"supportRoot\":\"C:\\\\Users\\\\rebui\\\\AppData\\\\Roaming\",\"sessionId\":\"ae-1795893040524\"}}" + } + ], + "evidence": [], + "durationMs": 505 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/sandbox-integrity.json new file mode 100644 index 00000000..8ab5056f --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/host/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:10:47.215Z", + "driftBeforeRepair": { + "changed": 3, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json", + "cache/layout-undo/panel-1/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/a8n-session.json new file mode 100644 index 00000000..5acefe32 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\journey\\ae-session\\staging\\a8n-host.js", + "pid": 109460 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/trace.jsonl new file mode 100644 index 00000000..f963a8fa --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:10:48.779Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/run.json new file mode 100644 index 00000000..b5c12485 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/run.json @@ -0,0 +1,142 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "journey", + "capturedAt": "2026-11-28T19:11:30.813Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-10-48-784Z-109460/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-10-48-784Z-109460/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:11:30.811Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 2, + "FAIL": 1, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-C11", + "title": "script preset (.jsx) run from catalog executes in AE", + "status": "PASS", + "detail": "marker=1795893056436|27.0x78", + "checks": [ + { + "name": "catalog lists dg-script-marker preset", + "ok": true, + "detail": "true" + }, + { + "name": "catalog Run button clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "ExtendScript side effect: marker.txt written by AE", + "ok": true, + "detail": "content=1795893056436|27.0x78" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus\\dg-presets\\marker.txt" + ], + "durationMs": 2147 + }, + { + "uc": "UC-C10", + "title": ".ffx preset run applies effect to selected AE layer", + "status": "PASS", + "detail": "effects 0→2: [\"ADBE CM AutoscrollVertical|Autoscroll - vertical\",\"ADBE Tile|(Motion Tile)\"]", + "checks": [ + { + "name": "AE comp + selected layer ready", + "ok": true, + "detail": "{\"comp\":\"TYPlus E2E Comp\",\"layers\":1,\"effectsBefore\":0}" + }, + { + "name": "catalog lists dg-ffx-fadein preset", + "ok": true, + "detail": "true" + }, + { + "name": "catalog Run button clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "layer gained effects from .ffx preset", + "ok": true, + "detail": "before=0 after=2 fx=[\"ADBE CM AutoscrollVertical|Autoscroll - vertical\",\"ADBE Tile|(Motion Tile)\"]" + } + ], + "evidence": [], + "durationMs": 2796 + }, + { + "uc": "UC-H02", + "title": "preset journey: create via dialog → tile placed → run → reload → re-run (UC-J02 chain)", + "status": "FAIL", + "detail": "preset journey completed (presetId=none)", + "checks": [ + { + "name": "toolbar create-file-preset clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "preset path field accepts file path", + "ok": true, + "detail": "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus-e2e\\e2e-journey.jsx" + }, + { + "name": "preset name field accepts title", + "ok": true, + "detail": "E2E Journey Script" + }, + { + "name": "Create submitted", + "ok": false, + "detail": "missing-button:Create|Creating…" + }, + { + "name": "presets.json persisted new record", + "ok": false, + "detail": "no record with fixture path" + }, + { + "name": "presets.json restored after journey", + "ok": true, + "detail": "before=3 after=3" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-10-48-784Z-109460\\ty-plus\\presets\\presets.json" + ], + "durationMs": 28585 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/sandbox-integrity.json new file mode 100644 index 00000000..fd735105 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journey/sandbox-integrity.json @@ -0,0 +1,11 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:11:30.811Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/a8n-session.json new file mode 100644 index 00000000..fe77c9d0 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\journeys\\ae-session\\staging\\a8n-host.js", + "pid": 104440 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/trace.jsonl new file mode 100644 index 00000000..ddafe127 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:11:32.407Z","op":"session.launch","status":"error","durationMs":0,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/run.json new file mode 100644 index 00000000..ade468f8 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/run.json @@ -0,0 +1,216 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "journeys", + "capturedAt": "2026-11-28T19:13:42.902Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-11-32-413Z-104440/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-11-32-413Z-104440/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:13:42.900Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 4, + "FAIL": 0, + "BLOCKED": 2, + "SKIP": 1 + }, + "results": [ + { + "uc": "UC-J02", + "title": "preset journey: create → place → run → edit → delete-attempt (host confirm gate)", + "status": "BLOCKED", + "detail": "Create not clickable: missing-button:Create|Creating…", + "checks": [], + "evidence": [], + "durationMs": 21747 + }, + { + "uc": "UC-J03", + "title": "layout journey: widget + preset tile + snapshot → reload → restore", + "status": "PASS", + "detail": "widget+preset layout snapshot round-trip", + "checks": [ + { + "name": "widget added via Add Widget dialog", + "ok": true, + "detail": "id=0bcdccce-1644-4425-b7d0-0f3b53a6dbe2" + }, + { + "name": "snapshot saved to snapshots.json", + "ok": true, + "detail": "snap=1795893133090" + }, + { + "name": "layout mutated with second widget", + "ok": true, + "detail": "second=fd6a36da-1786-418b-b0ff-0a4e22acca28" + }, + { + "name": "mutated layout survives reload", + "ok": true, + "detail": "cells=10" + }, + { + "name": "snapshot restore returned gridCells to saved state", + "ok": true, + "detail": "start=8 after=9" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-11-32-413Z-104440\\ty-plus\\workspaces\\history\\snapshots.json" + ], + "durationMs": 10702 + }, + { + "uc": "UC-J04", + "title": "appearance journey: accent/grid/locale change → live → reload persists", + "status": "PASS", + "detail": "accent/grid/locale round-trip through settings files", + "checks": [ + { + "name": "locale ja applied after reload", + "ok": true, + "detail": "lang=ja" + }, + { + "name": "accent color reached theme.css token", + "ok": true, + "detail": "accent=#336699" + }, + { + "name": "grid cell size reached panel CSS var", + "ok": true, + "detail": "cell=120px" + }, + { + "name": "app.json persisted accent+locale+grid", + "ok": true, + "detail": "accent=#336699 lang=ja cell=120" + }, + { + "name": "theme.css persisted accent token", + "ok": true, + "detail": "" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-11-32-413Z-104440\\ty-plus\\settings\\app.json" + ], + "durationMs": 3260 + }, + { + "uc": "UC-J05", + "title": "recovery journey: backup export → corrupt files → boot fallback → import restore", + "status": "PASS", + "detail": "export→corrupt→boot→import→verify recovery chain", + "checks": [ + { + "name": "backup bundle exported via settings UI", + "ok": true, + "detail": "5205 bytes" + }, + { + "name": "panel responsive after corruption", + "ok": true, + "detail": "eval=2" + }, + { + "name": "corrupt workspace file not silently destroyed", + "ok": true, + "detail": "file still present" + }, + { + "name": "app.json restored by backup import", + "ok": true, + "detail": "after={\"version\":2,\"core\":{\"paths\":{\"supportRoot\":\"C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-11-32-4" + }, + { + "name": "workspace-1.json restored to valid JSON", + "ok": true, + "detail": "parses" + } + ], + "evidence": [], + "durationMs": 14285 + }, + { + "uc": "UC-J06", + "title": "preset handoff: export bundle → wipe catalog → import → run preset in AE", + "status": "BLOCKED", + "detail": "dialog-presets surface did not open", + "checks": [], + "evidence": [], + "durationMs": 52963 + }, + { + "uc": "UC-J07", + "title": "daily work: quick-actions runs script then ffx preset consecutively", + "status": "PASS", + "detail": "consecutive quick-action runs: script marker + ffx effects=2", + "checks": [ + { + "name": "quick-actions run #1 (script) clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "script preset produced AE-side marker", + "ok": true, + "detail": "1795893212277|27.0x78" + }, + { + "name": "quick-actions run #2 (ffx) clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "ffx preset applied effects to selected layer", + "ok": true, + "detail": "effects=2" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus\\dg-presets\\marker.txt" + ], + "durationMs": 4703 + }, + { + "uc": "UC-J08", + "title": "real preset pack: grouped catalog, sibling thumbnails, .ffx execution", + "status": "SKIP", + "detail": "real preset pack not found (TY_PLUS_E2E_PRESET_PACK / ../ty-plus-e2e-assets)", + "checks": [], + "evidence": [], + "durationMs": 0 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/sandbox-integrity.json new file mode 100644 index 00000000..9d60333e --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/journeys/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:13:42.900Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/a8n-session.json new file mode 100644 index 00000000..4af2f66b --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\onboarding\\ae-session\\staging\\a8n-host.js", + "pid": 71516 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/trace.jsonl new file mode 100644 index 00000000..34ded2c2 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:14:53.829Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/run.json new file mode 100644 index 00000000..d27a78bc --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/run.json @@ -0,0 +1,92 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "onboarding", + "capturedAt": "2026-11-28T19:15:19.604Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-14-53-834Z-71516/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-14-53-834Z-71516/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:15:19.602Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 1, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-A01", + "title": "first-run: missing locator shows onboarding shell + step transition; restored locator hides it", + "status": "PASS", + "detail": "locator=D:\\4_apps\\adobe\\Adobe After Effects 2027\\Support Files\\ty-plus-init.json; full 10-step completion deferred (native dialogs)", + "checks": [ + { + "name": "onboarding shell shown while locator is missing", + "ok": true, + "detail": "shell=true" + }, + { + "name": "intro step title rendered", + "ok": true, + "detail": "title=\"1. ようこそ\" expected~\"ようこそ\"" + }, + { + "name": "step progress indicator rendered", + "ok": true, + "detail": "progress=\"1 / 10\"" + }, + { + "name": "next button clicked", + "ok": true, + "detail": "result=clicked" + }, + { + "name": "step advanced to language step", + "ok": true, + "detail": "title=\"2. 言語を選ぶ\"" + }, + { + "name": "onboarding not shown again after locator restore", + "ok": true, + "detail": "workspace=true" + }, + { + "name": "ty-plus-init.json bytes restored", + "ok": true, + "detail": "D:\\4_apps\\adobe\\Adobe After Effects 2027\\Support Files\\ty-plus-init.json 167 bytes" + } + ], + "evidence": [ + "D:\\4_apps\\adobe\\Adobe After Effects 2027\\Support Files\\ty-plus-init.json" + ], + "durationMs": 2432 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/sandbox-integrity.json new file mode 100644 index 00000000..c9e9624a --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/onboarding/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:15:19.602Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/a8n-session.json new file mode 100644 index 00000000..16b47ae9 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\online\\ae-session\\staging\\a8n-host.js", + "pid": 97556 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/trace.jsonl new file mode 100644 index 00000000..630f01be --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:13:44.476Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/run.json new file mode 100644 index 00000000..d26fcc94 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/run.json @@ -0,0 +1,254 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "online", + "capturedAt": "2026-11-28T19:14:52.188Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-13-44-482Z-97556/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-13-44-482Z-97556/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:14:52.186Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 3, + "FAIL": 2, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-F02", + "title": "notification center: seeded list → detail auto-marks read → toggle persists to cache", + "status": "FAIL", + "detail": "list/detail/read-state round-trip on seeded cache", + "checks": [ + { + "name": "dialog-messages surface opened", + "ok": true, + "detail": "port=9188" + }, + { + "name": "notification list renders seeded items", + "ok": true, + "detail": "count=2 listed=true" + }, + { + "name": "detail view shows selected notification", + "ok": true, + "detail": "E2E Alpha Notice" + }, + { + "name": "opening detail persisted read state to cache/notifications.json", + "ok": true, + "detail": "readAtById.e2e-n1-alpha=true" + }, + { + "name": "mark-unread toggle persisted to cache", + "ok": true, + "detail": "click=clicked persisted=true" + }, + { + "name": "mark-read toggle persisted to cache", + "ok": true, + "detail": "persisted=true" + }, + { + "name": "back navigation returns to notification list", + "ok": true, + "detail": "listItems=restored" + }, + { + "name": "cache/notifications.json restored after case", + "ok": false, + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\cache\\notifications.json 0 bytes" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\cache\\notifications.json" + ], + "durationMs": 11575 + }, + { + "uc": "UC-F01", + "title": "preset library: surface chrome, search field, view-mode switch, degraded empty state", + "status": "PASS", + "detail": "browse chrome verified; download→catalog leg needs live gateway (deferred)", + "checks": [ + { + "name": "dialog-preset-library surface opened", + "ok": true, + "detail": "port=9187" + }, + { + "name": "preset library root mounted", + "ok": true, + "detail": "true" + }, + { + "name": "search field rendered", + "ok": true, + "detail": "inputs=1" + }, + { + "name": "view-mode toggle exposes gallery/cards/list", + "ok": true, + "detail": "viewButtons=3" + }, + { + "name": "list view mode activates", + "ok": true, + "detail": "aria-label=\"List view\"" + }, + { + "name": "results area settles (items or degraded empty state)", + "ok": true, + "detail": "{\"empty\":true,\"reason\":\"\",\"cards\":0,\"table\":0}" + }, + { + "name": "degraded empty state exposes gateway boot reason", + "ok": true, + "detail": "reason=\"\"" + } + ], + "evidence": [], + "durationMs": 14976 + }, + { + "uc": "UC-F04", + "title": "settings → Updates: provided surfaces only, feed check reaches a terminal status", + "status": "PASS", + "detail": "update check terminal=up-to-date; network-dependent content deferred", + "checks": [ + { + "name": "dialog-settings surface opened", + "ok": true, + "detail": "port=9189" + }, + { + "name": "unprovided network/cloud-sync section is not presented", + "ok": true, + "detail": "present=false" + }, + { + "name": "Updates section mounted", + "ok": true, + "detail": "true" + }, + { + "name": "channel selector offers exactly stable/beta/insider", + "ok": true, + "detail": "options=3" + }, + { + "name": "update feed check reaches a terminal status", + "ok": true, + "detail": "status=up-to-date labels={\"upToDate\":\"Up to date\",\"unavailable\":\"Update check unavailable\"}" + }, + { + "name": "check-now affordance present and clickable", + "ok": true, + "detail": "result=clicked" + }, + { + "name": "manual re-check reaches a terminal status", + "ok": true, + "detail": "status=up-to-date" + } + ], + "evidence": [], + "durationMs": 10451 + }, + { + "uc": "UC-F05", + "title": "notification feed: empty cache triggers remote sync and settles to items or empty state", + "status": "FAIL", + "detail": "feed sync reached a settled state; live feed content needs network", + "checks": [ + { + "name": "dialog-messages surface opened", + "ok": true, + "detail": "port=9188" + }, + { + "name": "notification center settles after feed sync (items or empty)", + "ok": true, + "detail": "settled=empty" + }, + { + "name": "store remains valid JSON with items array after refresh", + "ok": true, + "detail": "items=0" + }, + { + "name": "cache/notifications.json restored after case", + "ok": false, + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\cache\\notifications.json 0 bytes" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\cache\\notifications.json" + ], + "durationMs": 12306 + }, + { + "uc": "UC-E07", + "title": "update channel change persists ui.updateChannel to settings/app.json", + "status": "PASS", + "detail": "channel change → settings persistence round-trip", + "checks": [ + { + "name": "dialog-settings surface opened", + "ok": true, + "detail": "port=9189" + }, + { + "name": "Updates section channel selector mounted", + "ok": true, + "detail": "true" + }, + { + "name": "channel option clicked", + "ok": true, + "detail": "trigger=true option=clicked" + }, + { + "name": "ui.updateChannel persisted to settings/app.json", + "ok": true, + "detail": "before=insider persisted=beta target=beta" + }, + { + "name": "settings/app.json restored after case", + "ok": true, + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\settings\\app.json 1352 bytes" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-13-44-482Z-97556\\ty-plus\\settings\\app.json" + ], + "durationMs": 10647 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/sandbox-integrity.json new file mode 100644 index 00000000..c2614a05 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/online/sandbox-integrity.json @@ -0,0 +1,11 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:14:52.186Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/a8n-session.json new file mode 100644 index 00000000..9b7b8061 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\preset-create\\ae-session\\staging\\a8n-host.js", + "pid": 47284 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/trace.jsonl new file mode 100644 index 00000000..5be39547 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:15:21.311Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/run.json new file mode 100644 index 00000000..aa289125 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/run.json @@ -0,0 +1,115 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "preset-create", + "capturedAt": "2026-11-28T19:19:45.348Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-15-21-317Z-47284/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-15-21-317Z-47284/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:19:45.346Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 0, + "FAIL": 0, + "BLOCKED": 8, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-C01", + "title": "path preset: missing asset rejected, footage inferred, duplicate path → distinct record", + "status": "BLOCKED", + "detail": "dialog-preset-add did not open", + "checks": [], + "evidence": [], + "durationMs": 32549 + }, + { + "uc": "UC-C02", + "title": "group preset: rejection + folder scan → presets.json + groups.json + group tile + catalog expansion", + "status": "BLOCKED", + "detail": "dialog-preset-add-folder did not open for ty.ctx.create-folder-preset", + "checks": [], + "evidence": [], + "durationMs": 31554 + }, + { + "uc": "UC-C03", + "title": "animation preset: Create without detected .ffx rejected; step-3 reaches host no-selection guard", + "status": "BLOCKED", + "detail": "dialog-animation-preset did not open for ty.ctx.create-animation-preset", + "checks": [], + "evidence": [], + "durationMs": 31976 + }, + { + "uc": "UC-C04", + "title": "code preset: panel-authored script → .jsx on disk + catalog record", + "status": "BLOCKED", + "detail": "dialog-code-preset did not open for ty.ctx.create-code-preset", + "checks": [], + "evidence": [], + "durationMs": 31758 + }, + { + "uc": "UC-C05", + "title": "layer/comp preset: AE-state-consistent outcome, no ghost record on failure", + "status": "BLOCKED", + "detail": "dialog-layer-comp-preset did not open for ty.ctx.create-layer-comp-preset", + "checks": [], + "evidence": [], + "durationMs": 31825 + }, + { + "uc": "UC-C06", + "title": "footage + import preset dialogs → records with mode/strategy; footage runs into AE", + "status": "BLOCKED", + "detail": "dialog-footage-preset did not open for ty.ctx.create-footage-preset", + "checks": [], + "evidence": [], + "durationMs": 31497 + }, + { + "uc": "UC-C07", + "title": "easing preset: cubic-bezier curve → .jsx under scriptRoot + data.easing record", + "status": "BLOCKED", + "detail": "dialog-preset-create did not open for ty.ctx.create-easing-preset", + "checks": [], + "evidence": [], + "durationMs": 31979 + }, + { + "uc": "UC-C08", + "title": "group edit: member list renders, member Run executes, rename persists to groups.json", + "status": "BLOCKED", + "detail": "dialog-presets surface did not open", + "checks": [], + "evidence": [], + "durationMs": 32084 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/sandbox-integrity.json new file mode 100644 index 00000000..abb6c658 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/preset-create/sandbox-integrity.json @@ -0,0 +1,11 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:19:45.346Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/a8n-session.json new file mode 100644 index 00000000..7b3eab2e --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\resilience\\ae-session\\staging\\a8n-host.js", + "pid": 84628 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/trace.jsonl new file mode 100644 index 00000000..dc93d1fa --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:07:40.383Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/run.json new file mode 100644 index 00000000..ebfafd94 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/run.json @@ -0,0 +1,185 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "resilience", + "capturedAt": "2026-11-28T19:08:01.951Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-07-40-389Z-84628/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-07-40-389Z-84628/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:08:01.949Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 5, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-I01", + "title": "corrupt workspaces/workspace-1.json: banner shown, bytes preserved", + "status": "PASS", + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-07-40-389Z-84628\\ty-plus\\workspaces\\workspace-1.json", + "checks": [ + { + "name": "workspaces/workspace-1.json overwritten with corrupt bytes", + "ok": true, + "detail": "29 bytes" + }, + { + "name": "panel boots with non-trivial DOM after corrupt file", + "ok": true, + "detail": "body=89847 grid=true tiles=7" + }, + { + "name": "layout restore banner reports corrupt", + "ok": true, + "detail": "present" + }, + { + "name": "workspaces/workspace-1.json not silently destroyed on boot", + "ok": true, + "detail": "corrupt bytes preserved" + } + ], + "evidence": [], + "durationMs": 2929 + }, + { + "uc": "UC-I02", + "title": "corrupt widgets/widgets.json: boots, bytes preserved (UC-D12 alias)", + "status": "PASS", + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-07-40-389Z-84628\\ty-plus\\widgets\\widgets.json", + "checks": [ + { + "name": "widgets/widgets.json overwritten with corrupt bytes", + "ok": true, + "detail": "39 bytes" + }, + { + "name": "panel boots with non-trivial DOM after corrupt file", + "ok": true, + "detail": "body=67796 grid=true tiles=7" + }, + { + "name": "workspace grid still rendered", + "ok": true, + "detail": "present" + }, + { + "name": "widgets/widgets.json not silently destroyed on boot", + "ok": true, + "detail": "corrupt bytes preserved" + } + ], + "evidence": [], + "durationMs": 2438 + }, + { + "uc": "UC-I04", + "title": "corrupt styles/theme.css: defaults fallback, file preserved or repaired", + "status": "PASS", + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-07-40-389Z-84628\\ty-plus\\styles\\theme.css", + "checks": [ + { + "name": "panel boots and applies fallback theme", + "ok": true, + "detail": "body=67796 grid=true accent=#58a6ff" + }, + { + "name": "styles/theme.css preserved or regenerated", + "ok": true, + "detail": "corrupt bytes preserved (defaults applied)" + } + ], + "evidence": [], + "durationMs": 2487 + }, + { + "uc": "UC-I05", + "title": "corrupt settings/app.json: defaults fallback, bytes preserved", + "status": "PASS", + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-07-40-389Z-84628\\ty-plus\\settings\\app.json", + "checks": [ + { + "name": "settings/app.json overwritten with corrupt bytes", + "ok": true, + "detail": "50 bytes" + }, + { + "name": "panel boots with non-trivial DOM after corrupt file", + "ok": true, + "detail": "body=67580 grid=true tiles=7" + }, + { + "name": "workspace grid still rendered", + "ok": true, + "detail": "present" + }, + { + "name": "settings/app.json not silently destroyed on boot", + "ok": true, + "detail": "corrupt bytes preserved" + } + ], + "evidence": [], + "durationMs": 2403 + }, + { + "uc": "UC-C16", + "title": "corrupt presets/presets.json: boots, records preserved", + "status": "PASS", + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-07-40-389Z-84628\\ty-plus\\presets\\presets.json", + "checks": [ + { + "name": "presets/presets.json overwritten with corrupt bytes", + "ok": true, + "detail": "39 bytes" + }, + { + "name": "panel boots with non-trivial DOM after corrupt file", + "ok": true, + "detail": "body=67796 grid=true tiles=7" + }, + { + "name": "workspace grid still rendered", + "ok": true, + "detail": "present" + }, + { + "name": "presets/presets.json not silently destroyed on boot", + "ok": true, + "detail": "corrupt bytes preserved" + } + ], + "evidence": [], + "durationMs": 2371 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/sandbox-integrity.json new file mode 100644 index 00000000..121a04e7 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/resilience/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:08:01.949Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/a8n-session.json new file mode 100644 index 00000000..28628d09 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\smoke\\ae-session\\staging\\a8n-host.js", + "pid": 49164 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/trace.jsonl new file mode 100644 index 00000000..6f175133 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:06:59.810Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/run.json new file mode 100644 index 00000000..bba7781d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/run.json @@ -0,0 +1,243 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "smoke", + "capturedAt": "2026-11-28T19:07:38.743Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-06-59-821Z-49164/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-06-59-821Z-49164/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:07:38.739Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 5, + "FAIL": 1, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-A03", + "title": "live surfaces boot with CEP bridge and extension origin", + "status": "PASS", + "detail": "4 live surfaces checked", + "checks": [ + { + "name": "at least one surface is live", + "ok": true, + "detail": "4 live surfaces" + }, + { + "name": "panel-1 is live", + "ok": true, + "detail": "panel-1,panel-3,panel-4,panel-5" + }, + { + "name": "panel-1 boots", + "ok": true, + "detail": "readyState=complete body=92270 cs=true" + }, + { + "name": "panel-1 loads from CEP extensions", + "ok": true, + "detail": "file:///C:/Users/rebui/AppData/Roaming/Adobe/CEP/extensions/app.ty-plus.dev/panel/index.html" + }, + { + "name": "panel-3 boots", + "ok": true, + "detail": "readyState=complete body=2789 cs=true" + }, + { + "name": "panel-3 loads from CEP extensions", + "ok": true, + "detail": "file:///C:/Users/rebui/AppData/Roaming/Adobe/CEP/extensions/app.ty-plus.dev/panel/index.html" + }, + { + "name": "panel-4 boots", + "ok": true, + "detail": "readyState=complete body=2789 cs=true" + }, + { + "name": "panel-4 loads from CEP extensions", + "ok": true, + "detail": "file:///C:/Users/rebui/AppData/Roaming/Adobe/CEP/extensions/app.ty-plus.dev/panel/index.html" + }, + { + "name": "panel-5 boots", + "ok": true, + "detail": "readyState=complete body=2789 cs=true" + }, + { + "name": "panel-5 loads from CEP extensions", + "ok": true, + "detail": "file:///C:/Users/rebui/AppData/Roaming/Adobe/CEP/extensions/app.ty-plus.dev/panel/index.html" + } + ], + "evidence": [ + "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\smoke\\smoke-panel-1.png", + "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\smoke\\smoke-panel-3.png", + "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\smoke\\smoke-panel-4.png", + "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\smoke\\smoke-panel-5.png" + ], + "durationMs": 329 + }, + { + "uc": "UC-H01", + "title": "ExtendScript host responds and host bundle contract is callable", + "status": "PASS", + "detail": "AE 27.0x78", + "checks": [ + { + "name": "app.version responds", + "ok": true, + "detail": "27.0x78" + }, + { + "name": "host bundle exposes callable contract", + "ok": true, + "detail": "contract-ok" + } + ], + "evidence": [], + "durationMs": 72 + }, + { + "uc": "UC-A02", + "title": "persisted settings/layout/theme files exist and parse", + "status": "PASS", + "detail": "managed root files", + "checks": [ + { + "name": "settings/app.json parses", + "ok": true, + "detail": "ok" + }, + { + "name": "workspaces/workspace-1.json parses", + "ok": true, + "detail": "ok" + }, + { + "name": "presets/presets.json parses", + "ok": true, + "detail": "ok" + }, + { + "name": "styles/theme.css state consistent with overrides", + "ok": true, + "detail": "122 bytes" + } + ], + "evidence": [], + "durationMs": 3 + }, + { + "uc": "UC-B04", + "title": "grid settings persisted value reaches panel CSS variables", + "status": "PASS", + "detail": "grid token convergence", + "checks": [ + { + "name": "settings.workspace.grid.cellSize resolves (persisted or default)", + "ok": true, + "detail": "cellSize=48 persisted=48" + }, + { + "name": "--ty-ws-cell reflects persisted grid", + "ok": true, + "detail": "computed=48px expected=48px" + } + ], + "evidence": [], + "durationMs": 1 + }, + { + "uc": "UC-E02", + "title": "ui accent color persisted in app.json reaches theme.css tokens", + "status": "PASS", + "detail": "ui.* → theme pipeline", + "checks": [ + { + "name": "ui.accentColor present in app.json", + "ok": true, + "detail": "accent=#e2b701" + }, + { + "name": "theme.css accent token matches ui.* projection", + "ok": true, + "detail": "--color-ty-accent: #e2b701" + } + ], + "evidence": [], + "durationMs": 1 + }, + { + "uc": "UC-G01", + "title": "debug console surface aggregates logs and evaluates JS", + "status": "FAIL", + "detail": "debug console eval/filter/clear", + "checks": [ + { + "name": "debug console DOM mounted", + "ok": true, + "detail": "body=10152 msgs=1" + }, + { + "name": "console REPL input accepted expression", + "ok": true, + "detail": "sent:" + }, + { + "name": "evaluated result logged as console message", + "ok": false, + "detail": "rowWithResult=false" + }, + { + "name": "throwing expression logged as error row", + "ok": true, + "detail": "rowWithError=true" + }, + { + "name": "level filter isolates error rows", + "ok": true, + "detail": "click={\"ok\":true,\"pressed\":\"false\"} rows=1 nonError=0 marker=true" + }, + { + "name": "clear empties the console buffer", + "ok": true, + "detail": "click=clicked lastRows=0" + } + ], + "evidence": [], + "durationMs": 29981 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/sandbox-integrity.json new file mode 100644 index 00000000..af99718a --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:07:38.739Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-1.png b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-1.png new file mode 100644 index 00000000..016c78fe Binary files /dev/null and b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-1.png differ diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-3.png b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-3.png new file mode 100644 index 00000000..c9d9e594 Binary files /dev/null and b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-3.png differ diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-4.png b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-4.png new file mode 100644 index 00000000..c9d9e594 Binary files /dev/null and b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-4.png differ diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-5.png b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-5.png new file mode 100644 index 00000000..c9d9e594 Binary files /dev/null and b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/smoke/smoke-panel-5.png differ diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/a8n-session.json new file mode 100644 index 00000000..c2c0eac1 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\widgets\\ae-session\\staging\\a8n-host.js", + "pid": 56584 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/trace.jsonl new file mode 100644 index 00000000..6cafea5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:08:03.547Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/run.json new file mode 100644 index 00000000..6d9c9936 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/run.json @@ -0,0 +1,180 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "widgets", + "capturedAt": "2026-11-28T19:09:41.103Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-08-03-555Z-56584/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-08-03-555Z-56584/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:09:41.101Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 1, + "FAIL": 1, + "BLOCKED": 0, + "SKIP": 5 + }, + "results": [ + { + "uc": "UC-D11", + "title": "easing widget state file restores mode after reload (legacy loop coerces to curve)", + "status": "SKIP", + "detail": "easing widget 5019574b-1c02-43e8-840c-15b88a9ecf39 not mounted on panel-1", + "checks": [], + "evidence": [], + "durationMs": 5 + }, + { + "uc": "UC-D02", + "title": "easing Apply with no AE keyframe selection surfaces the structured no-selection notice", + "status": "SKIP", + "detail": "easing apply button not mounted", + "checks": [], + "evidence": [], + "durationMs": 2 + }, + { + "uc": "UC-D05", + "title": "align widget aligns two selected AE layers (align-left)", + "status": "SKIP", + "detail": "align widget not mounted", + "checks": [], + "evidence": [], + "durationMs": 3 + }, + { + "uc": "UC-D06", + "title": "anchor-point widget moves AE anchor to top-left of selected layer", + "status": "SKIP", + "detail": "anchor-point widget not mounted", + "checks": [], + "evidence": [], + "durationMs": 2 + }, + { + "uc": "UC-D07", + "title": "info widget shows preset details when a preset tile is selected", + "status": "SKIP", + "detail": "info widget or preset tile not mounted", + "checks": [], + "evidence": [], + "durationMs": 2 + }, + { + "uc": "UC-D08", + "title": "font-viewer widget lists fonts and search filters the catalog", + "status": "PASS", + "detail": "font-viewer add + search round-trip", + "checks": [ + { + "name": "font-viewer widget record created", + "ok": true, + "detail": "id=03cc634c-ab2d-4cdc-ba7f-b3c648a5330b" + }, + { + "name": "font-viewer list mounted", + "ok": true, + "detail": "true" + }, + { + "name": "font catalog settled (rows or explicit empty/error state)", + "ok": true, + "detail": "rows=298 settled=298" + }, + { + "name": "font search field mounted", + "ok": true, + "detail": "aria=\"Search fonts\"" + }, + { + "name": "search filters font list to zero matches", + "ok": true, + "detail": "{\"rows\":0,\"noMatch\":true}" + }, + { + "name": "clearing search restores font rows", + "ok": true, + "detail": "rows=298" + } + ], + "evidence": [], + "durationMs": 13175 + }, + { + "uc": "UC-D09", + "title": "directory-browser widget opens a folder, lists entries, filters, and navigates", + "status": "FAIL", + "detail": "directory-browser open/search/navigate", + "checks": [ + { + "name": "directory-browser widget record created", + "ok": true, + "detail": "id=22faf49d-32d4-44e1-8e5f-7d2dd0fa12e7" + }, + { + "name": "directory-browser search UI mounted", + "ok": true, + "detail": "true" + }, + { + "name": "browser-open-dir event dispatched", + "ok": true, + "detail": "dispatched" + }, + { + "name": "fixture folder entries listed", + "ok": true, + "detail": "entries=4" + }, + { + "name": "search filters entries to the matching file", + "ok": false, + "detail": "filtered=null" + }, + { + "name": "sub-directory entry clicked", + "ok": false, + "detail": "missing-dir-entry" + }, + { + "name": "navigation into sub-directory listed its file", + "ok": false, + "detail": "subEntries=null" + }, + { + "name": "go-up affordance enabled inside sub-directory", + "ok": false, + "detail": "canGoUp=null" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus-e2e\\dir-browser-e2e" + ], + "durationMs": 77497 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/sandbox-integrity.json new file mode 100644 index 00000000..ae084b87 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/widgets/sandbox-integrity.json @@ -0,0 +1,11 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:09:41.101Z", + "driftBeforeRepair": { + "changed": 0, + "added": 0, + "removed": 0 + }, + "filesRepaired": [], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/a8n-session.json new file mode 100644 index 00000000..ea8208ab --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-all-040657\\workspace\\ae-session\\staging\\a8n-host.js", + "pid": 113188 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/trace.jsonl new file mode 100644 index 00000000..37fe5a60 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:19:47.049Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/run.json new file mode 100644 index 00000000..b29804b4 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/run.json @@ -0,0 +1,304 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "workspace", + "capturedAt": "2026-11-28T19:22:38.997Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-19-47-056Z-113188/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-19-47-056Z-113188/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:22:38.990Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 3, + "FAIL": 2, + "BLOCKED": 2, + "SKIP": 4 + }, + "results": [ + { + "uc": "UC-B02", + "title": "Add Widget dialog places an info tile", + "status": "PASS", + "detail": "widget=ff9557c0-4d03-4c32-bac4-04264d7d0483 cells 8→8", + "checks": [ + { + "name": "widgets.json gained info record", + "ok": true, + "detail": "id=ff9557c0-4d03-4c32-bac4-04264d7d0483" + }, + { + "name": "info tile mounted on panel", + "ok": true, + "detail": "true \"\"" + }, + { + "name": "workspace-1.json gridCells grew", + "ok": true, + "detail": "before=8 after=9" + }, + { + "name": "layout restored after case", + "ok": true, + "detail": "before=8 restored=8" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\widgets\\widgets.json", + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\workspaces\\workspace-1.json" + ], + "durationMs": 12851 + }, + { + "uc": "UC-B05", + "title": "layout snapshot save → mutate → restore → delete round-trip", + "status": "PASS", + "detail": "snapshot=1795893609532 cells 8", + "checks": [ + { + "name": "save-snapshot clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "snapshots.json gained a new entry", + "ok": true, + "detail": "id=1795893609532" + }, + { + "name": "snapshot row rendered in dropdown", + "ok": true, + "detail": "true" + }, + { + "name": "layout mutated (widget tile added)", + "ok": true, + "detail": "cells 8→9 widget=e69c02e7-a9ad-4abb-94bb-a7397de24fce" + }, + { + "name": "restore-snapshot clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "gridCells restored to snapshot state", + "ok": true, + "detail": "before=8 mutated=9 restored=8" + }, + { + "name": "added widget tile removed by restore", + "ok": true, + "detail": "tile=e69c02e7-a9ad-4abb-94bb-a7397de24fce" + }, + { + "name": "delete-snapshot clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "snapshot removed from snapshots.json", + "ok": true, + "detail": "snapId=1795893609532" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\workspaces\\history\\snapshots.json" + ], + "durationMs": 14344 + }, + { + "uc": "UC-D10", + "title": "quick-actions palette runs script preset twice consecutively", + "status": "PASS", + "detail": "quick-actions runs=2 marker=1795893626174|27.0x78", + "checks": [ + { + "name": "quick-actions search focused + query typed", + "ok": true, + "detail": "focused:DG" + }, + { + "name": "palette lists dg-script-marker run action", + "ok": true, + "detail": "true" + }, + { + "name": "palette run clicked", + "ok": true, + "detail": "clicked" + }, + { + "name": "run #1 produced AE-side marker", + "ok": true, + "detail": "1795893625065|27.0x78" + }, + { + "name": "run #2 consecutive re-execution produced new marker", + "ok": true, + "detail": "m1=1795893625065|27.0x78 m2=1795893626174|27.0x78" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus\\dg-presets\\marker.txt" + ], + "durationMs": 3898 + }, + { + "uc": "UC-C12", + "title": "footage preset (.png) created via dialog → run imports into AE project", + "status": "BLOCKED", + "detail": "Create not clickable: missing-button:Create|Creating…", + "checks": [], + "evidence": [], + "durationMs": 22995 + }, + { + "uc": "UC-C14", + "title": "run preset with deleted asset fails without blocking modal", + "status": "BLOCKED", + "detail": "cannot resolve Folder.userData: e2e-error:ReferenceError: CSInterface is not defined", + "checks": [], + "evidence": [], + "durationMs": 564 + }, + { + "uc": "UC-B03", + "title": "widget tile move + resize via pointer gestures persist to workspace-1.json", + "status": "SKIP", + "detail": "no gridCell for widget e6f6b730-4dc1-458e-8efc-b8540fe7f146", + "checks": [], + "evidence": [], + "durationMs": 18 + }, + { + "uc": "UC-B06", + "title": "widget tile move is undoable/redoable via status bar buttons", + "status": "SKIP", + "detail": "widget tile e6f6b730-4dc1-458e-8efc-b8540fe7f146 not mounted", + "checks": [], + "evidence": [], + "durationMs": 9 + }, + { + "uc": "UC-B09", + "title": "ControlPanel collapse toggle persists to panels/panel-1.json", + "status": "FAIL", + "detail": "control panel collapse round-trip", + "checks": [ + { + "name": "control panel + collapse toggle mounted", + "ok": false, + "detail": "false" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\panels\\panel-1.json" + ], + "durationMs": 35278 + }, + { + "uc": "UC-B10", + "title": "Layout Lock widget blocks tile move gestures until unlocked", + "status": "SKIP", + "detail": "widget tile or lock button not mounted", + "checks": [], + "evidence": [], + "durationMs": 47 + }, + { + "uc": "UC-D10", + "title": "menu widget flyout lists workspace actions and toggles layout lock", + "status": "SKIP", + "detail": "menu widget opener not mounted", + "checks": [], + "evidence": [], + "durationMs": 3 + }, + { + "uc": "UC-D09", + "title": "directory-browser widget: mount, entry listing, dir navigation, file selection", + "status": "FAIL", + "detail": "widget=3bf5ce99-842a-479b-a4f7-352b34eb0604 cells 8→8", + "checks": [ + { + "name": "directory-browser widget record added", + "ok": true, + "detail": "id=3bf5ce99-842a-479b-a4f7-352b34eb0604" + }, + { + "name": "directory-browser widget chrome mounted", + "ok": true, + "detail": "search=true" + }, + { + "name": "toolbar + path field + browse-mode select rendered", + "ok": true, + "detail": "{\"scope\":true,\"toolbar\":1,\"pathInputs\":1,\"browseSelects\":1}" + }, + { + "name": "directory entries listed", + "ok": true, + "detail": "entries=205 dirs=117 files=88" + }, + { + "name": "detailed filters panel toggles open", + "ok": true, + "detail": "label=\"Filters\"" + }, + { + "name": "directory navigation changes current path", + "ok": false, + "detail": "click=missing before=\"C:/Users/rebui\" after=null" + }, + { + "name": "go-up returns to previous directory", + "ok": false, + "detail": "back=null" + }, + { + "name": "file row selection registers selected path", + "ok": true, + "detail": "selected=\"C:/Users/.DS_Store\"" + }, + { + "name": "layout restored after case", + "ok": true, + "detail": "before=8 restored=8" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\widgets\\widgets.json", + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-19-47-056Z-113188\\ty-plus\\workspaces\\workspace-1.json" + ], + "durationMs": 67741 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/sandbox-integrity.json new file mode 100644 index 00000000..a4087f7d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-all/workspace/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:22:38.990Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/a8n-session.json new file mode 100644 index 00000000..d205c802 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-pc\\preset-create\\ae-session\\staging\\a8n-host.js", + "pid": 59064 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/trace.jsonl new file mode 100644 index 00000000..35ed6023 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:31:39.224Z","op":"session.launch","status":"error","durationMs":1,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/run.json new file mode 100644 index 00000000..761bf2a3 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/run.json @@ -0,0 +1,159 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "preset-create", + "capturedAt": "2026-11-28T19:46:13.041Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-31-39-247Z-59064/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": { + "dir": null, + "error": "no attached AE session" + }, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-31-39-247Z-59064/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:46:12.616Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 0, + "FAIL": 1, + "BLOCKED": 7, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-C01", + "title": "path preset: missing asset rejected, footage inferred, duplicate path → distinct record", + "status": "FAIL", + "detail": "path dialog: rejection + inference + duplicate-id contract", + "checks": [ + { + "name": "Create submitted for missing asset", + "ok": false, + "detail": "missing-button:Create|Creating…" + }, + { + "name": "missing asset produced no catalog record", + "ok": true, + "detail": "records=0" + }, + { + "name": "dialog stayed open after rejection (no ghost close)", + "ok": true, + "detail": "open=true" + }, + { + "name": "footage Create submitted", + "ok": false, + "detail": "missing-button:Create|Creating…" + }, + { + "name": "presets.json persisted footage record", + "ok": false, + "detail": "id= type=undefined" + }, + { + "name": "type inferred as footage", + "ok": false, + "detail": "type=undefined" + }, + { + "name": "duplicate path registration yields distinct catalog id", + "ok": false, + "detail": "ids=" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Roaming\\ty-plus-e2e\\e2e-c01-footage.png", + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-31-39-247Z-59064\\ty-plus\\presets\\presets.json" + ], + "durationMs": 150512 + }, + { + "uc": "UC-C02", + "title": "group preset: rejection + folder scan → presets.json + groups.json + group tile + catalog expansion", + "status": "BLOCKED", + "detail": "dialog-presets surface did not open", + "checks": [], + "evidence": [], + "durationMs": 150324 + }, + { + "uc": "UC-C03", + "title": "animation preset: Create without detected .ffx rejected; step-3 reaches host no-selection guard", + "status": "BLOCKED", + "detail": "dialog-animation-preset did not open for ty.ctx.create-animation-preset", + "checks": [], + "evidence": [], + "durationMs": 156317 + }, + { + "uc": "UC-C04", + "title": "code preset: panel-authored script → .jsx on disk + catalog record", + "status": "BLOCKED", + "detail": "CDP timeout: Runtime.evaluate :: (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst cs = new CSInterface();\n\t\t\t\t\treturn await new Promise((res) =>\n\t\t\t\t\t\tcs.evalScript(\"", + "checks": [], + "evidence": [], + "durationMs": 65307 + }, + { + "uc": "UC-C05", + "title": "layer/comp preset: AE-state-consistent outcome, no ghost record on failure", + "status": "BLOCKED", + "detail": "CDP timeout: Runtime.evaluate :: (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst cs = new CSInterface();\n\t\t\t\t\treturn await new Promise((res) =>\n\t\t\t\t\t\tcs.evalScript(\"", + "checks": [], + "evidence": [], + "durationMs": 60449 + }, + { + "uc": "UC-C06", + "title": "footage + import preset dialogs → records with mode/strategy; footage runs into AE", + "status": "BLOCKED", + "detail": "cannot resolve Folder.userData: e2e-error:ReferenceError: CSInterface is not defined", + "checks": [], + "evidence": [], + "durationMs": 59721 + }, + { + "uc": "UC-C07", + "title": "easing preset: cubic-bezier curve → .jsx under scriptRoot + data.easing record", + "status": "BLOCKED", + "detail": "ty.ctx.create-easing-preset not clickable: missing-anchor", + "checks": [], + "evidence": [], + "durationMs": 74776 + }, + { + "uc": "UC-C08", + "title": "group edit: member list renders, member Run executes, rename persists to groups.json", + "status": "BLOCKED", + "detail": "cannot resolve Folder.userData: e2e-error:ReferenceError: CSInterface is not defined", + "checks": [], + "evidence": [], + "durationMs": 72732 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/sandbox-integrity.json new file mode 100644 index 00000000..a813a2ea --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-preset-create/preset-create/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:46:12.616Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/a8n-session.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/a8n-session.json new file mode 100644 index 00000000..d6c71da6 --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/a8n-session.json @@ -0,0 +1,7 @@ +{ + "v": 1, + "transport": "script-invocation", + "hostScript": "C:\\Users\\rebui\\ty-plus\\node_modules\\@ido-bata\\ae-a8n\\host\\a8n-host.js", + "stagedHostScript": "C:\\Users\\rebui\\ty-e2e\\results-rerun-settings\\settings\\ae-session\\staging\\a8n-host.js", + "pid": 80788 +} \ No newline at end of file diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-host.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-host.js new file mode 100644 index 00000000..c31d8a9c --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-host.js @@ -0,0 +1,1571 @@ +/*! + * a8n-host.js — the part of ae-a8n that actually runs inside After Effects. + * + * Contract with the driver: the generated bootstrap sets a global `__a8n` + * with the request and result paths, then evals this file. This script reads + * the request, dispatches to a method, and publishes the result by rename. + * + * The identical file is evaluated against the in-repo fake host during tests — + * only the peer supplying `app` differs. Keep it that way: any logic that + * needs to differ per-peer belongs in the peer, not here. + * + * ES3 only. ExtendScript has no `let`/`const`, no arrow functions, no `JSON`, + * no `String.prototype.trim`, and no `Error.captureStackTrace`. + */ + +(function () { + // ---------------------------------------------------------------- codec -- + + function loadJson() { + // Always the bundled codec. AE's engine has no `JSON` of its own; one that + // is present was put there by another extension (observed on 26.5x89: a + // Babel-built polyfill, present once startup finished and absent on a cold + // start), so preferring it made the host behave differently cold and warm. + // + // The codec comes back as `$.evalFile`'s completion value. Looking it up + // on the global object does not work: called from inside a function, a + // real AE keeps the included file's `var`s in that function's scope. + var codec = $.evalFile(new File($.fileName).parent.fsName + "/a8n-json.js"); + if ( + codec === undefined || + codec === null || + typeof codec.parse !== "function" || + typeof codec.stringify !== "function" + ) { + throw new Error("a8n-json.js did not produce a JSON codec"); + } + return codec; + } + + // ------------------------------------------------------------------ fs --- + + function readTextFile(path) { + var file = new File(path); + file.encoding = "UTF-8"; + if (!file.exists) { + throw new Error("request file not found: " + path); + } + if (!file.open("r")) { + throw new Error("cannot open request file: " + path); + } + var text = file.read(); + file.close(); + return text; + } + + function writeTextFile(path, text) { + var file = new File(path); + file.encoding = "UTF-8"; + // ExtendScript cannot create intermediate directories, and the driver + // already created them. Opening for write truncates. + if (!file.open("w")) { + throw new Error("cannot open result file for writing: " + path); + } + // ExtendScript can report an I/O failure with false instead of throwing. + // Never rename a staging file unless both the write and the close succeed. + var wrote = false; + var closed = false; + try { + wrote = file.write(text) !== false; + } finally { + closed = file.close() !== false; + } + if (!wrote || !closed) { + throw new Error("cannot finish writing result file: " + path); + } + } + + function parentOf(path) { + var file = new File(path); + return file.parent.fsName; + } + + // -------------------------------------------------------------- errors --- + + function toErrorPayload(error) { + var payload = { + name: "Error", + message: "unknown host error" + }; + if (error === null || typeof error !== "object") { + payload.message = String(error); + return payload; + } + if (error.name !== undefined && error.name !== null) { + payload.name = String(error.name); + } + if (error.message !== undefined && error.message !== null) { + payload.message = String(error.message); + } else { + payload.message = String(error); + } + if (error.line !== undefined && typeof error.line === "number") { + payload.line = error.line; + } + // AE raises errors carrying `errorNumber` (e.g. 5023 for a missing effect). + if (error.errorNumber !== undefined && typeof error.errorNumber === "number") { + payload.aeError = error.errorNumber; + } + // Set by the host's own typed errors (NoValueError) for the API to branch on. + if (typeof error.kind === "string") { + payload.kind = error.kind; + } + if (error.matchName !== undefined && error.matchName !== null) { + payload.message = payload.message + " (matchName: " + String(error.matchName) + ")"; + } + return payload; + } + + // ------------------------------------------------------------- helpers --- + + // ExtendScript's Object.prototype has members a plain `object[key]` finds + // (functions named "+", "-", "*", "/", `toSource`, `watch`, ... observed on + // AE 26.5x89), so a key that came from a request is looked up as own only. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function requireParam(params, name) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + throw new Error("missing required parameter: " + name); + } + return params[name]; + } + + function optionalParam(params, name, fallback) { + if (params === null || params === undefined || !has(params, name) || params[name] === undefined) { + return fallback; + } + return params[name]; + } + + function getProject() { + if (app.project === null || app.project === undefined) { + throw new Error("no project is open"); + } + return app.project; + } + + function findComp(name) { + // A real Project has no lookup by name (`itemByName` is undefined on AE + // 26.5x89), so walk the items. Names are not unique in AE; the first + // composition with the name wins, and a non-composition item that shares + // it is skipped. + var project = getProject(); + var sawOther = false; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item.name === name) { + if (item instanceof CompItem) { + return item; + } + sawOther = true; + } + } + if (sawOther) { + throw new Error("item is not a composition: " + name); + } + var missing = new Error("composition not found: " + name); + // The API turns exactly this into EntityNotFoundError; anything else a + // lookup raises is reported as itself. + missing.name = "NotFoundError"; + throw missing; + } + + function findLayer(comp, name) { + var layer = comp.layer(name); + if (layer === null || layer === undefined) { + throw new Error("layer not found in '" + comp.name + "': " + name); + } + return layer; + } + + function effectParade(layer) { + var parade = layer.property("ADBE Effect Parade"); + if (parade === null || parade === undefined) { + throw new Error("layer has no effect parade: " + layer.name); + } + return parade; + } + + /** + * Effects are addressed by match name internally, but callers know display + * names. Try the given identifier as a match name first (the documented, + * locale-independent path), then fall back to scanning by display name. + */ + function findEffect(layer, identifier) { + var parade = effectParade(layer); + var byName = parade.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = parade.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = parade.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + function applyEffect(layer, identifier) { + var parade = effectParade(layer); + var existing = findEffect(layer, identifier); + if (existing !== null && existing !== undefined) { + return { effect: existing, created: false }; + } + try { + // Match-name form: the deterministic path for third-party plugins. + var created = parade.addProperty(identifier); + if (created === null || created === undefined) { + throw new Error("addProperty returned nothing for: " + identifier); + } + return { effect: created, created: true }; + } catch (matchNameError) { + // Display-name form: some plugins register under their menu label. + var byLabel = parade.addProperty(identifier); + if (byLabel === null || byLabel === undefined) { + throw matchNameError; + } + return { effect: byLabel, created: true }; + } + } + + function findParameter(effect, identifier) { + var byName = effect.property(identifier); + if (byName !== null && byName !== undefined) { + return byName; + } + var count = effect.numProperties; + for (var i = 1; i <= count; i++) { + var candidate = effect.property(i); + if (candidate.name === identifier || candidate.matchName === identifier) { + return candidate; + } + } + return null; + } + + // PropertyValueType member names, in Adobe's order. Looked up on the live + // enum, so the numbers come from the host, not from here. + var VALUE_TYPE_NAMES = [ + "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", + "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", + "TEXT_DOCUMENT" + ]; + + function valueTypeName(property) { + var type = property.propertyValueType; + for (var i = 0; i < VALUE_TYPE_NAMES.length; i++) { + // Constant keys, not request data: a plain lookup is safe here, and + // AE's enums are host objects that need not report own properties. + var member = PropertyValueType[VALUE_TYPE_NAMES[i]]; + if (member !== undefined && member === type) { + return VALUE_TYPE_NAMES[i]; + } + } + return String(type); + } + + /** + * The value shapes this API carries, by value type: `min`/`max` array + * lengths that `setValue` accepts on AE 26.5x89, or 0/0 for a single + * number. ThreeD takes 2 (z becomes 0) and COLOR 3 (alpha becomes 1). + * Anything else (MARKER, SHAPE, TEXT_DOCUMENT) is not carried. + */ + function valueShape(name) { + if (name === "OneD" || name === "LAYER_INDEX" || name === "MASK_INDEX") { + return { min: 0, max: 0, text: "a number" }; + } + if (name === "TwoD" || name === "TwoD_SPATIAL") { + return { min: 2, max: 2, text: "an array of 2 numbers" }; + } + if (name === "ThreeD" || name === "ThreeD_SPATIAL") { + return { min: 2, max: 3, text: "an array of 2 or 3 numbers" }; + } + if (name === "COLOR") { + return { min: 3, max: 4, text: "an array of 3 or 4 numbers" }; + } + return null; + } + + /** + * Whether a script can read this property's value, without reading it. + * On AE 26.5x89 reading `value` throws for PropertyValueType.NO_VALUE + * (e.g. ADBE Tint-0004, ADBE Ramp-0008) and CUSTOM_VALUE (Levels' + * histogram, Curves), and a group (Compositing Options) has no value. + * Value types this API does not carry count as "custom-value". + */ + function propertyKind(property) { + if (property.propertyType !== PropertyType.PROPERTY) { + return "group"; + } + var name = valueTypeName(property); + if (name === "NO_VALUE") { + return "no-value"; + } + return valueShape(name) === null ? "custom-value" : "value"; + } + + function describeProperty(property) { + var kind = propertyKind(property); + var out = { name: property.name, kind: kind }; + if (property.matchName !== undefined && property.matchName !== null) { + out.matchName = property.matchName; + } + if (kind !== "group") { + out.valueType = valueTypeName(property); + } + if (kind === "value") { + out.value = property.value; + } + return out; + } + + function isFiniteNumber(value) { + return typeof value === "number" && isFinite(value); + } + + // Not `instanceof Array`: request values come from the codec, which may run + // in another realm (as a8n-json.js notes for its own check). + function isArray(value) { + return Object.prototype.toString.call(value) === "[object Array]"; + } + + /** + * Refuses, before touching the property, a write it cannot take: a + * property without a value (NoValueError), or a value of the wrong shape + * for its type (ValueShapeError). AE itself would coerce some of these + * (observed: `[]` written to a OneD property becomes 0). + */ + function requireWritableValue(property, value) { + var kind = propertyKind(property); + var error; + if (kind !== "value") { + error = new Error( + "property has no value to write (" + kind + "): " + property.matchName + ); + error.name = "NoValueError"; + error.kind = kind; + throw error; + } + var name = valueTypeName(property); + var shape = valueShape(name); + var fits; + if (shape.max === 0) { + fits = isFiniteNumber(value); + } else { + fits = isArray(value) && value.length >= shape.min && value.length <= shape.max; + for (var i = 0; fits && i < value.length; i++) { + fits = isFiniteNumber(value[i]); + } + } + if (!fits) { + error = new Error( + property.matchName + " (" + name + ") takes " + shape.text + ); + error.name = "ValueShapeError"; + error.kind = name; + throw error; + } + } + + function zeroPad(value, width) { + var text = String(value); + while (text.length < width) { + text = "0" + text; + } + return text; + } + + // ------------------------------------------------------------- methods --- + + var methods = {}; + + methods["app.info"] = function () { + var info = { version: String(app.version) }; + // AE exposes the build as `app.buildNumber`; `app.build` is undefined on a + // real host (observed on 26.5x89). An absent value is left out rather than + // reported as the string "undefined". + try { + var build = app.buildNumber; + if (build !== undefined && build !== null && String(build) !== "") { + info.build = String(build); + } + } catch (e) { + // build is not guaranteed; version alone is enough for a readiness probe. + } + return info; + }; + + /** + * Refuses when the open project has unsaved changes, unless the caller + * explicitly allowed discarding them. Named, so the driver can tell a + * decision the caller must make from a failure. + */ + function guardUnsavedChanges(params, action) { + var project = app.project; + if (project === null || project === undefined || !project.dirty) { + return false; + } + if (optionalParam(params, "discardUnsavedChanges", false) !== true) { + var refused = new Error("the open project has unsaved changes; " + action + " would discard them"); + refused.name = "UnsavedChangesError"; + throw refused; + } + return true; + } + + /** + * Shows a modal dialog in After Effects and waits until it is closed. + * + * The dialog is native, not scripted: it is the one case an ExtendScript + * call cannot get out of on its own. It exists so the GUI fallback — the + * path that closes a dialog for a host that stopped answering — can be + * exercised against a dialog whose appearance and dismissal are known. + * + * `alert` blocks the script, so the result is written only after the + * dialog has been closed. A caller that gave up on the call must not send + * it again; the request is still running inside After Effects. + */ + methods["ui.alert"] = function (params) { + var message = String(requireParam(params, "message")); + // The GUI fallback may only press a window it has measured. Its one known + // class requires a static text beginning "ae-a8n:", so the marker is put + // on here, whatever the caller passed: a dialog this method raises has to + // be closable by the fallback it exists for. + var text = /^\s*ae-a8n:/.test(message) ? message : "ae-a8n: " + message; + alert(text); + return { dismissed: true, message: text }; + }; + + methods["app.quit"] = function (params) { + if (guardUnsavedChanges(params, "quitting")) { + // Closed first, untitled or not: a dirty project would otherwise put a + // save prompt in front of the quit. + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + app.quit(); + return { quitting: true }; + }; + + methods["project.open"] = function (params) { + var path = String(requireParam(params, "path")); + var file = new File(path); + if (!file.exists) { + throw new Error("project file not found: " + path); + } + // Opening replaces the open project; with unsaved changes AE would put a + // save prompt in front of the script, and the changes may be someone + // else's work. + if (guardUnsavedChanges(params, "opening another project")) { + app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES); + } + var opened = app.open(file); + // app.open answers with the Project it opened; the path is on + // project.file. An absent file (an untitled project) reports null. + var openedFile = opened === null || opened === undefined ? null : opened.file; + var openedPath = openedFile === null || openedFile === undefined + ? null + : openedFile.fsName || openedFile.name; + return { file: openedPath === null || openedPath === undefined ? null : String(openedPath) }; + }; + + methods["project.close"] = function (params) { + var save = optionalParam(params, "save", false); + if (save !== true) { + guardUnsavedChanges(params, "closing without saving"); + } + var closed = getProject().close( + save ? CloseOptions.SAVE_CHANGES : CloseOptions.DO_NOT_SAVE_CHANGES + ); + if (closed === false) { + var cancelled = new Error("project close was cancelled"); + cancelled.name = "ProjectCloseCancelled"; + throw cancelled; + } + return { closed: true }; + }; + + methods["project.info"] = function () { + var project = getProject(); + return { + file: project.file === null ? null : String(project.file.fsName), + name: project.file === null ? null : String(project.file.name), + itemCount: project.numItems + }; + }; + + methods["project.comps"] = function () { + var project = getProject(); + var out = []; + for (var i = 1; i <= project.numItems; i++) { + var item = project.item(i); + if (item instanceof CompItem) { + out.push({ + name: item.name, + width: item.width, + height: item.height, + duration: item.duration, + frameRate: item.frameRate, + layerCount: item.numLayers + }); + } + } + return out; + }; + + methods["comp.info"] = function (params) { + return compInfo(findComp(String(requireParam(params, "name")))); + }; + + methods["comp.layers"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + var out = []; + for (var i = 1; i <= comp.numLayers; i++) { + out.push(layerInfo(comp.layer(i))); + } + return out; + }; + + methods["comp.layer"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + return layerInfo(layer); + }; + + methods["layer.effects"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var parade = effectParade(layer); + var out = []; + for (var i = 1; i <= parade.numProperties; i++) { + out.push({ name: parade.property(i).name, matchName: parade.property(i).matchName }); + } + return out; + }; + + methods["layer.applyEffect"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var identifier = String(requireParam(params, "effect")); + var result = applyEffect(layer, identifier); + return { + name: result.effect.name, + matchName: result.effect.matchName, + created: result.created + }; + }; + + methods["effect.parameters"] = function (params) { + var effect = resolveEffect(params); + var out = []; + for (var i = 1; i <= effect.numProperties; i++) { + out.push(describeProperty(effect.property(i))); + } + return out; + }; + + methods["effect.getParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + return describeProperty(property); + }; + + methods["effect.setParameter"] = function (params) { + var effect = resolveEffect(params); + var property = requireProperty(effect, String(requireParam(params, "parameter"))); + var value = requireParam(params, "value"); + requireWritableValue(property, value); + property.setValue(value); + return describeProperty(property); + }; + + function resolveEffect(params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var effect = findEffect(layer, String(requireParam(params, "effect"))); + if (effect === null || effect === undefined) { + throw new Error("effect not found on layer '" + layer.name + "': " + params.effect); + } + return effect; + } + + function requireProperty(effect, identifier) { + var property = findParameter(effect, identifier); + if (property === null || property === undefined) { + var missing = new Error("parameter not found on effect '" + effect.name + "': " + identifier); + // Named and kinded like findComp's NotFoundError, so the API turns + // exactly this into EntityNotFoundError(kind: "parameter"); the kind + // keeps a missing composition inside the same call distinct. + missing.name = "NotFoundError"; + missing.kind = "parameter"; + throw missing; + } + return property; + } + + methods["comp.renderFrame"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var frame = Number(requireParam(params, "frame")); + var outputDir = String(requireParam(params, "outputDir")); + var namePrefix = String(optionalParam(params, "prefix", comp.name)); + + var folder = new Folder(outputDir); + if (!folder.exists && !folder.create()) { + throw new Error("cannot create output directory: " + outputDir); + } + var target = new File(folder.fsName + "/" + namePrefix + "." + zeroPad(frame, 5) + ".png"); + if (target.exists) { + target.remove(); + } + + // `saveFrameToPng`, not the render queue: a localised AE has no output + // module template named "PNG Sequence" (ja 26.5x89 lists none) and an + // output module's "Format" is read-only to setSettings, so the queue + // cannot be told to write PNG. `saveFrameToPng` renders at the viewer's + // resolution, so full resolution is forced for the frame and restored. + var previousResolution = comp.resolutionFactor; + comp.resolutionFactor = [1, 1]; + try { + var pending = comp.saveFrameToPng(frame * comp.frameDuration, target); + // It returns before the file is written (observed: 0 bytes at first); + // `wait()` blocks until it is, and throws if it failed. + try { + pending.wait(); + } catch (waitError) { + var cause = pending._exception !== undefined && pending._exception !== null + ? String(pending._exception) + : String(waitError.message); + throw new Error("frame " + frame + " of '" + comp.name + "' was not rendered: " + cause); + } + } finally { + comp.resolutionFactor = previousResolution; + } + + var size = readPngSize(target); + return { + path: String(target.fsName), + frame: frame, + width: size.width, + height: size.height + }; + }; + + /** Width and height from a PNG's IHDR: what was written, not what was asked for. */ + function readPngSize(file) { + if (!file.exists) { + throw new Error("rendered frame is missing: " + file.fsName); + } + file.encoding = "BINARY"; + if (!file.open("r")) { + throw new Error("cannot open rendered frame: " + file.fsName); + } + var head = file.read(24); + file.close(); + if (head.length < 24 || head.substring(12, 16) !== "IHDR") { + throw new Error("rendered frame is not a PNG: " + file.fsName); + } + function u32(offset) { + return head.charCodeAt(offset) * 16777216 + + head.charCodeAt(offset + 1) * 65536 + + head.charCodeAt(offset + 2) * 256 + + head.charCodeAt(offset + 3); + } + return { width: u32(16), height: u32(20) }; + } + + + // -------------------------------------------------- scene construction --- + + function layerType(layer) { + // Most specific first: a ShapeLayer and a TextLayer are also AVLayers. + if (typeof TextLayer !== "undefined" && layer instanceof TextLayer) { + return "text"; + } + if (typeof ShapeLayer !== "undefined" && layer instanceof ShapeLayer) { + return "shape"; + } + if (typeof AVLayer !== "undefined" && layer instanceof AVLayer) { + return "av"; + } + return "other"; + } + + function layerInfo(layer) { + return { + id: layer.id, + name: layer.name, + index: layer.index, + enabled: layer.enabled, + selected: layer.selected, + type: layerType(layer) + }; + } + + function compInfo(comp) { + return { + name: comp.name, + width: comp.width, + height: comp.height, + duration: comp.duration, + frameRate: comp.frameRate, + layerCount: comp.numLayers + }; + } + + function requireNumber(params, name, min) { + var value = requireParam(params, name); + if (!isFiniteNumber(value) || value < min) { + throw new Error(name + " must be a number >= " + min); + } + return value; + } + + function requireNumbers(value, name, length) { + if (!isArray(value) || value.length !== length) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + for (var i = 0; i < value.length; i++) { + if (!isFiniteNumber(value[i])) { + throw new Error(name + " must be an array of " + length + " numbers"); + } + } + return value; + } + + methods["project.createComp"] = function (params) { + var project = getProject(); + var name = String(requireParam(params, "name")); + // Comps are addressed by name, so a second comp with the name could never + // be reached; refuse instead of creating it. + for (var i = 1; i <= project.numItems; i++) { + if (project.item(i).name === name) { + throw new Error("an item named '" + name + "' already exists"); + } + } + var comp = project.items.addComp( + name, + requireNumber(params, "width", 4), + requireNumber(params, "height", 4), + optionalParam(params, "pixelAspect", 1), + requireNumber(params, "duration", 0.001), + requireNumber(params, "frameRate", 1) + ); + return compInfo(comp); + }; + + methods["comp.openInViewer"] = function (params) { + var comp = findComp(String(requireParam(params, "name"))); + comp.openInViewer(); + return { name: comp.name, active: app.project.activeItem === comp }; + }; + + methods["comp.addText"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var text = String(requireParam(params, "text")); + // Reject every invalid optional value before creating a layer: a failed + // request must not leave an orphan text layer in the user's project. + var name = optionalParam(params, "name", null); + var font = optionalParam(params, "font", null); + var fontSize = optionalParam(params, "fontSize", null); + var fillColor = optionalParam(params, "fillColor", null); + var position = optionalParam(params, "position", null); + if (fontSize !== null) { + fontSize = requireNumber(params, "fontSize", 1); + } + if (fillColor !== null) { + fillColor = requireNumbers(fillColor, "fillColor", 3); + } + if (position !== null) { + position = requireNumbers(position, "position", 2); + } + + var layer = comp.layers.addText(text); + if (name !== null) { + layer.name = String(name); + } + var source = layer.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + if (font !== null) { + doc.font = String(font); + } + if (fontSize !== null) { + doc.fontSize = fontSize; + } + if (fillColor !== null) { + doc.applyFill = true; + doc.fillColor = fillColor; + } + doc.applyStroke = false; + source.setValue(doc); + if (position !== null) { + layer.property("ADBE Transform Group").property("ADBE Position") + .setValue(position); + } + var applied = source.value; + var info = layerInfo(layer); + // What AE settled on, not what was asked for: an unknown font falls back. + info.font = String(applied.font); + info.fontSize = applied.fontSize; + return info; + }; + + methods["comp.selectLayers"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var names = requireParam(params, "layers"); + if (!isArray(names)) { + throw new Error("layers must be an array of layer names"); + } + var wanted = []; + for (var i = 0; i < names.length; i++) { + wanted.push(findLayer(comp, String(names[i]))); + } + // Exactly the named layers: deselect everything else first. + for (var j = 1; j <= comp.numLayers; j++) { + comp.layer(j).selected = false; + } + for (var k = 0; k < wanted.length; k++) { + wanted[k].selected = true; + } + var selected = []; + for (var n = 1; n <= comp.numLayers; n++) { + if (comp.layer(n).selected) { + selected.push(comp.layer(n).name); + } + } + return { selected: selected }; + }; + + methods["layer.setEnabled"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var enabled = requireParam(params, "enabled"); + if (enabled !== true && enabled !== false) { + throw new Error("enabled must be a boolean"); + } + layer.enabled = enabled; + return layerInfo(layer); + }; + + methods["layer.transform"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + var group = layer.property("ADBE Transform Group"); + return { + anchorPoint: group.property("ADBE Anchor Point").value, + position: group.property("ADBE Position").value, + scale: group.property("ADBE Scale").value, + rotation: group.property("ADBE Rotate Z").value, + opacity: group.property("ADBE Opacity").value + }; + }; + + function collectShapePaths(group, groups, out) { + for (var i = 1; i <= group.numProperties; i++) { + var child = group.property(i); + if (child.matchName === "ADBE Vector Group") { + var nested = groups.slice(0); + nested.push(child.name); + collectShapePaths(child.property("ADBE Vectors Group"), nested, out); + } else if (child.matchName === "ADBE Vector Shape - Group") { + var shape = child.property("ADBE Vector Shape").value; + out.push({ + groups: groups, + name: child.name, + closed: shape.closed, + vertices: shape.vertices, + inTangents: shape.inTangents, + outTangents: shape.outTangents + }); + } + } + } + + methods["layer.shapePaths"] = function (params) { + var comp = findComp(String(requireParam(params, "comp"))); + var layer = findLayer(comp, String(requireParam(params, "layer"))); + if (layerType(layer) !== "shape") { + throw new Error("not a shape layer: " + layer.name); + } + var out = []; + collectShapePaths(layer.property("ADBE Root Vectors Group"), [], out); + return out; + }; + + // ------------------------------------------------------- menu commands --- + + methods["app.setEnvironment"] = function (params) { + var variables = requireParam(params, "variables"); + var names = []; + for (var key in variables) { + if (has(variables, key)) { + // Process-scoped: the variable lives in this AE process only and is + // gone when it exits. Nothing is persisted to preferences. + $.setenv(key, String(variables[key])); + names.push(key); + } + } + return { names: names }; + }; + + methods["menu.find"] = function (params) { + var name = String(requireParam(params, "name")); + var id = app.findMenuCommandId(name); + if (!isFiniteNumber(id) || id <= 0) { + var missing = new Error("menu command not found: " + name); + missing.name = "NotFoundError"; + throw missing; + } + return { id: id, name: name }; + }; + + function sceneSnapshot() { + var project = app.project; + var active = project === null || project === undefined ? null : project.activeItem; + var snapshot = { + itemCount: project === null || project === undefined ? 0 : project.numItems, + comp: null, + layers: [] + }; + if (active !== null && active !== undefined && active instanceof CompItem) { + snapshot.comp = active.name; + for (var i = 1; i <= active.numLayers; i++) { + snapshot.layers.push(layerInfo(active.layer(i))); + } + } + return snapshot; + } + + methods["menu.execute"] = function (params) { + var id = requireParam(params, "id"); + if (!isFiniteNumber(id) || id <= 0 || Math.floor(id) !== id) { + throw new Error("menu command id must be a positive integer"); + } + var before = sceneSnapshot(); + var started = new Date().getTime(); + // Synchronous on AE 26.5x89, including commands an AEGP plugin registers: + // the plugin's command hook has returned when this does. + app.executeCommand(id); + var durationMs = new Date().getTime() - started; + return { + id: id, + durationMs: durationMs, + before: before, + after: sceneSnapshot() + }; + }; + + // ----------------------------------------------------------- dispatch --- + + /** + * Which sessions this engine has answered, by id. A plain object of booleans: + * the engine outlives every script, so nothing from After Effects (no item, + * comp or layer) may be kept here, or a later project switch invalidates it. + */ + function sessionStore() { + var store = $.global.__a8nSessions; + if (store === undefined || store === null) { + store = {}; + $.global.__a8nSessions = store; + } + return store; + } + + /** Refuses before doing anything when the request requires a session this engine never answered. */ + function checkSession(request) { + var session = request.session; + if (session === undefined || session === null || session.require !== true) { + return; + } + if (sessionStore()[String(session.id)] !== true) { + var mismatch = new Error( + "this After Effects instance did not answer the probe of this session, so " + String(request.method) + " was not run" + ); + mismatch.name = "SessionMismatch"; + throw mismatch; + } + } + + function rememberSession(request) { + var session = request.session; + if (session !== undefined && session !== null && session.adopt === true) { + sessionStore()[String(session.id)] = true; + } + } + + function extensionTable() { + var context = this.__a8n; + if (context === undefined || context === null || context.extensions === undefined) { + return {}; + } + return context.extensions; + } + + /** + * The extension method names actually registered in this After Effects, + * sorted. Read once at dispatcher activation: the table does not grow + * afterwards, so the heartbeat reports a fixed set (#146). + */ + function registeredExtensionNames() { + var table = extensionTable(); + var names = []; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + names.push(key); + } + } + names.sort(); + return names; + } + + /** + * A shallow copy of the registered extension functions, taken once at + * dispatcher activation. Dispatch resolves against this snapshot so the + * set the heartbeat reports is the set that actually answers (#146). + */ + function snapshotExtensionFunctions() { + var table = extensionTable(); + var copy = {}; + for (var key in table) { + if (has(table, key) && typeof table[key] === "function") { + copy[key] = table[key]; + } + } + return copy; + } + + /** + * The registration fingerprint the build prelude left on `__a8n`, or null + * when the running script was not built by `ae-a8n extension build`. It is + * copied into the heartbeat verbatim — the host never recomputes it. + */ + function extensionRegistration() { + var context = this.__a8n; + if (context === undefined || context === null) { + return null; + } + var value = context.extensionsRegistration; + return typeof value === "string" && value.length > 0 ? value : null; + } + + function dispatch(request, extensionOverride) { + if (request === null || typeof request !== "object") { + throw new Error("request envelope is not an object"); + } + // Extension methods are registered before this file loads and live in + // their own table: a built-in name always wins, because the build refuses + // a collision but the table must still not be able to replace one. + // + // Statements, not one nested conditional: measured on AE 26.5x89, + // ExtendScript evaluates `a ? x : b ? y : undefined` with the second test + // deciding the whole expression, so a name found in `methods` returned + // `extensions[name]` — undefined — and every call failed with "unknown + // method". An explicitly grouped conditional and plain `if` both evaluate + // correctly; this form is also correct in Node, so the fake host agrees. + // `extensionOverride` is the dispatcher path's activation-time snapshot + // (#146): the heartbeat reports that fixed set, so dispatch must resolve + // against the same fixed set — a later mutation of `__a8n.extensions` + // cannot widen what the dispatcher answers for. + var extensions = extensionOverride === undefined ? extensionTable() : extensionOverride; + var method; + if (has(methods, request.method)) { + method = methods[request.method]; + } else if (has(extensions, request.method)) { + method = extensions[request.method]; + } else { + method = undefined; + } + if (method === undefined) { + throw new Error("unknown method: " + String(request.method)); + } + if (typeof method !== "function") { + throw new Error("the method " + String(request.method) + " is not a function"); + } + checkSession(request); + var result = method(request.params); + rememberSession(request); + return result; + } + + function main() { + var codec = loadJson(); + var context = this.__a8n; + if (context === undefined || context === null) { + throw new Error("a8n host invoked without a __a8n context"); + } + + var started = new Date().getTime(); + var request; + var envelope; + + try { + request = codec.parse(readTextFile(context.request)); + var result = dispatch(request); + envelope = { + v: request.v, + id: request.id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } catch (error) { + var id = "unknown"; + if (request !== undefined && request !== null && request.id !== undefined) { + id = String(request.id); + } + envelope = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - started, + error: toErrorPayload(error) + }; + } + + // Publish by rename so the driver never reads a partial envelope. A + // rename on the same directory is atomic; a direct write is not, and the + // driver can only tell the difference by refusing to read a half-written + // file. So the atomic path is worth retrying before giving it up — on + // Windows a transient handle (antivirus, AE itself) is the usual cause. + publishResult(String(context.result), codec.stringify(envelope)); + } + + var PUBLISH_ATTEMPTS = 3; + var PUBLISH_RETRY_MS = 50; + + /** The last path segment, taken from the string so nothing is URI-encoded. */ + function fileNameOf(path) { + var slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return slash < 0 ? path : path.substring(slash + 1); + } + + /** + * Publishes `text` at `resultPath` and says how: "rename" or "direct". + * + * "rename": the result appeared whole, by renaming a fully written staging + * file in the same directory. A reader can never observe part of it. + * + * "direct": every rename failed and the result was written in place. A + * reader *can* observe a partial file; the driver re-reads until the + * envelope parses, so this costs latency, not correctness. + * + * Either way no staging file is left behind. + */ + function publishResult(resultPath, text) { + var staging = resultPath + ".part"; + writeTextFile(staging, text); + var finalFile = new File(resultPath); + // ExtendScript's `File.rename` takes a new *name* and keeps the file in + // its directory; given a full path it returns false (observed on AE + // 26.5x89). Passing a path would make every publication non-atomic. + var finalName = fileNameOf(resultPath); + + for (var attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) { + var stagingFile = new File(staging); + // ExtendScript's rename refuses an existing destination. + if (finalFile.exists) { + finalFile.remove(); + } + if (stagingFile.rename(finalName)) { + return "rename"; + } + if (attempt + 1 < PUBLISH_ATTEMPTS) { + $.sleep(PUBLISH_RETRY_MS); + } + } + + // Every atomic attempt failed. Write anyway rather than lose a computed + // result, then drop the staging copy so it does not accumulate. + var leftover = new File(staging); + try { + writeTextFile(resultPath, text); + } catch (directWriteError) { + // A write that reported failure must not leave a readable envelope + // behind: the driver accepts any parseable result at resultPath, so a + // complete ok:true left by a failed close would be read as success. + var partial = new File(resultPath); + if (partial.exists) { + partial.remove(); + } + if (leftover.exists) { + leftover.remove(); + } + throw directWriteError; + } + if (leftover.exists) { + leftover.remove(); + } + return "direct"; + } + + // -------------------------------------------------------- dispatcher --- + // + // Opt-in in-AE transport (#127). Instead of answering one request file per + // script run, this mode keeps an `app.scheduleTask` polling a private + // channel directory and answers the *same* named operations from the same + // `methods` table — there is no second dispatch table and no eval of + // caller-supplied code. + // + // Activation is deliberate and human: File > Scripts > Run Script File on + // the generated `activate.jsx`, or a per-user `Scripts/Startup` entry the + // user installed. This file never installs itself, never opens a socket, + // and never quits After Effects. + // + // Channel contract (mirrors the one-shot path): + // /inbox/.request.json claimed by rename before it runs + // /outbox/.result.json published by rename + // /state.json heartbeat the Node side reads + // A request that cannot be answered still gets a failure envelope when it + // can be published; when it cannot, the caller reports UNKNOWN and never + // resends — a claimed request is never replayed. + + var DISPATCHER_POLL_MS = 250; + var DISPATCHER_MIN_POLL_MS = 50; + var DISPATCHER_MAX_POLL_MS = 5000; + /** Heartbeat refresh cadence, in ticks. */ + var DISPATCHER_STATE_EVERY = 8; + /** Outbox results older than this are deleted; they are deliveries nobody read. */ + var DISPATCHER_RESULT_MAX_AGE_MS = 60 * 60 * 1000; + + function dispatcherRefusal(reason) { + var error = new Error("request refused: " + reason); + error.name = "RequestRefusedError"; + return error; + } + + function dispatcherPaths(root) { + var base = String(root); + while (base.length > 1 && base.substring(base.length - 1) === "/") { + base = base.substring(0, base.length - 1); + } + return { + root: base, + inbox: base + "/inbox", + outbox: base + "/outbox", + state: base + "/state.json" + }; + } + + /** + * Validates a claimed request and runs it through the same `dispatch` the + * one-shot path uses. Throws — the caller turns that into a failure + * envelope — for anything that is not a live, authorized, named operation. + */ + function runDispatcherRequest(state, claimed, id) { + var started = new Date().getTime(); + var request; + try { + request = state.codec.parse(readTextFile(claimed.fsName)); + } catch (parseFailure) { + throw dispatcherRefusal("the request is not valid JSON"); + } + if (request === null || typeof request !== "object" || request.v !== 1) { + throw dispatcherRefusal("unsupported request envelope"); + } + if (String(request.id) !== id) { + // The id in the envelope must be the id in the file name: a mismatch + // means the file was not addressed to this request slot. + throw dispatcherRefusal("request id does not match its file name"); + } + if (request.token !== state.token) { + throw dispatcherRefusal("request token does not match this channel"); + } + // Defence in depth for the pre-claim filter in dispatcherTick: a request + // that names a different dispatcher instance must never run here, even + // if it was claimed before the filter could see it. + if (typeof request.target === "string" && request.target !== state.instance) { + throw dispatcherRefusal("request targets a different dispatcher instance"); + } + if (typeof request.method !== "string" || request.method.length === 0) { + throw dispatcherRefusal("request names no method"); + } + if (typeof request.timeoutMs !== "number" || !isFinite(request.timeoutMs)) { + throw dispatcherRefusal("request carries no usable deadline"); + } + var now = new Date().getTime(); + if (now > claimed.modified.getTime() + request.timeoutMs) { + // The caller's deadline already passed while the request waited + // unclaimed (AE busy, dispatcher not yet active). Refuse it: running + // it now would execute work nobody is still waiting for. + var stale = new Error("request expired before the dispatcher claimed it"); + stale.name = "StaleRequestError"; + throw stale; + } + var result = dispatch(request, state.extensionFunctions); + return { + v: request.v, + id: id, + ok: true, + durationMs: new Date().getTime() - started, + result: result === undefined ? null : result + }; + } + + function writeDispatcherState(state) { + var report = { + v: 1, + token: state.token, + instance: state.instance, + aeVersion: String(app.version), + activatedAt: state.activatedAt, + lastTick: new Date().getTime(), + pollMs: state.pollMs, + // The per-delivery nonce a `ae.activateDispatcher()` script carried + // (#276). Null for a human activation; the Node side requires it to + // match its own delivery before reporting activation success. + activationNonce: state.activationNonce === undefined ? null : state.activationNonce, + // The extension set this dispatcher actually registered (#146). + // Captured once at activation into `state`; the table cannot change + // afterwards, so the heartbeat keeps reporting the fixed set — not a + // claim that the staged file matches. + extensionMethods: state.extensionMethods, + extensionsRegistration: state.extensionsRegistration + }; + try { + publishResult(state.paths.state, state.codec.stringify(report)); + } catch (stateError) { + // A heartbeat that cannot be written is not worth a modal dialog; the + // Node side reads a stale file as "not answering" and says so. + } + } + + /** Removes outbox results too old for any caller to still be waiting on. */ + function sweepDispatcherOutbox(state) { + var outbox = new Folder(state.paths.outbox); + if (!outbox.exists) { + return; + } + var horizon = new Date().getTime() - DISPATCHER_RESULT_MAX_AGE_MS; + var files = outbox.getFiles("*.result.json"); + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (file instanceof File && file.modified.getTime() < horizon) { + file.remove(); + } + } + } + + function dispatcherTick(state) { + try { + var inbox = new Folder(state.paths.inbox); + if (!inbox.exists) { + return; + } + var files = inbox.getFiles("*.request.json"); + files.sort(function (a, b) { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + }); + // One request per tick: the channel contract is strictly serial, so a + // long operation can never overlap the next claim. Files that are not + // dispatcher requests (other writers, stale names) are skipped, never + // allowed to stall the queue. + for (var i = 0; i < files.length; i++) { + var file = files[i]; + if (!(file instanceof File)) { + continue; + } + var match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.request\.json$/.exec(file.name); + if (match === null) { + continue; + } + var id = match[1]; + // Target binding (#145): a request that names a dispatcher instance + // is claimed only by that instance. Two After Effects can share one + // channel; without this check the first poller would run — or refuse + // — work addressed to the other. The file is left in place for the + // dispatcher it names; an unreadable file falls through to the + // claim path, which reports it as a refusal. + try { + var peek = state.codec.parse(readTextFile(file.fsName)); + if ( + peek !== null && + typeof peek === "object" && + typeof peek.target === "string" && + peek.target !== state.instance + ) { + continue; + } + } catch (peekError) { + // Malformed JSON is the claim path's refusal to report, not ours. + } + // Claim before running: a host restart cannot replay a claimed + // operation, and a second dispatcher cannot take the same file. + if (!file.rename(id + ".claimed")) { + continue; + } + var claimed = new File(inbox.fsName + "/" + id + ".claimed"); + var began = new Date().getTime(); + var reply; + try { + reply = runDispatcherRequest(state, claimed, id); + } catch (failure) { + reply = { + v: 1, + id: id, + ok: false, + durationMs: new Date().getTime() - began, + error: toErrorPayload(failure) + }; + } + try { + publishResult( + state.paths.outbox + "/" + id + ".result.json", + state.codec.stringify(reply) + ); + } catch (publishError) { + // The caller times out UNKNOWN; do not retry a claimed request. + } + claimed.remove(); + break; + } + state.ticks += 1; + if (state.ticks % DISPATCHER_STATE_EVERY === 0) { + writeDispatcherState(state); + sweepDispatcherOutbox(state); + } + } catch (tickError) { + // A scheduled task must never raise a modal dialog while the user + // works. With no state update the Node side reports UNKNOWN. + } + } + + function startDispatcher(config) { + var runningState = $.global.__a8nDispatcherState; + if ($.global.__a8nDispatcherTask !== undefined) { + // A dispatcher is already running in this After Effects. A freshly + // generated activation script carries a new per-delivery nonce: + // recording it re-proves that THIS delivery reached this instance, + // without starting a second dispatcher. Re-running the identical + // script (same nonce) or a human activate.jsx (no nonce) is still + // refused, exactly as before. + var deliveredNonce = + config !== null && + typeof config === "object" && + typeof config.nonce === "string" && + /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null; + if ( + runningState !== undefined && + runningState !== null && + deliveredNonce !== null && + deliveredNonce !== runningState.activationNonce + ) { + runningState.activationNonce = deliveredNonce; + writeDispatcherState(runningState); + return; + } + throw new Error( + "ae-a8n dispatcher is already active in this After Effects; " + + "refusing a second dispatcher" + ); + } + var codec = loadJson(); + var root = new Folder(String(config.root)); + // ExtendScript's Folder has no `isDirectory` (observed on AE 26.5 — the + // fake Folder models one, which is why only the real host tripped this). + // `exists` plus the inbox/outbox checks below are the real contract: a + // plain file at the root fails there with a clearer error anyway. + if (!root.exists) { + throw new Error("ae-a8n dispatcher: channel root is not a directory: " + String(config.root)); + } + var paths = dispatcherPaths(root.fsName); + var inbox = new Folder(paths.inbox); + var outbox = new Folder(paths.outbox); + if (!inbox.exists || !outbox.exists) { + throw new Error("ae-a8n dispatcher: channel folders are missing; prepare the channel first"); + } + var token = String(config.token); + if (!/^[a-f0-9]{64}$/.test(token)) { + throw new Error("ae-a8n dispatcher: channel token is malformed"); + } + var pollMs = config.pollMs; + if (typeof pollMs !== "number" || !isFinite(pollMs)) { + pollMs = DISPATCHER_POLL_MS; + } + if (pollMs < DISPATCHER_MIN_POLL_MS) { + pollMs = DISPATCHER_MIN_POLL_MS; + } + if (pollMs > DISPATCHER_MAX_POLL_MS) { + pollMs = DISPATCHER_MAX_POLL_MS; + } + if (typeof app.scheduleTask !== "function") { + throw new Error("ae-a8n dispatcher: this After Effects has no app.scheduleTask"); + } + var state = { + codec: codec, + paths: paths, + token: token, + pollMs: pollMs, + instance: + "i" + + new Date().getTime().toString(16) + + Math.floor(Math.random() * 0xffffff).toString(16), + activatedAt: new Date().getTime(), + ticks: 0, + // Fixed here, once: whatever `__a8n.extensions` holds right now is + // what this dispatcher will answer for its whole life. A host script + // built without the extension prelude leaves both empty/null. + extensionMethods: registeredExtensionNames(), + extensionsRegistration: extensionRegistration(), + // The function snapshot dispatch actually resolves against (#146): + // the heartbeat's names and this table are captured together, so a + // later mutation of `__a8n.extensions` cannot widen the answer set. + extensionFunctions: snapshotExtensionFunctions(), + // The nonce this activation script carried, if any (#276). A later + // re-delivery with a fresh nonce replaces it (see the guard above), + // which is how `ae.activateDispatcher()` proves each call reached + // this instance. + activationNonce: + typeof config.nonce === "string" && /^[a-f0-9]{32}$/.test(config.nonce) + ? config.nonce + : null + }; + // Kept on the global so a re-delivered activation script can re-prove + // delivery against the running dispatcher instead of starting a + // second one. + $.global.__a8nDispatcherState = state; + var tick = function () { + dispatcherTick(state); + }; + // The scheduled string names the global, so the function must be there + // before the first fire — pollMs later at the earliest. + $.global.__a8nDispatcherTick = tick; + $.global.__a8nDispatcherTask = app.scheduleTask( + "$.global.__a8nDispatcherTick()", + pollMs, + true + ); + writeDispatcherState(state); + } + + // The branch check must run inside a named function called plainly, not + // at the IIFE's top level: on real ExtendScript `this` inside + // `(function(){})()` is the function itself, not the global object + // (observed on AE 26.5/27.0 — the fake vm runtime cannot reproduce this). + // Inside a named function `this` is the global object, the same contract + // `main()` and the extension prelude already rely on. Evaluating + // `this.__a8n` here would always miss and silently fall into `main()`. + function boot() { + var __a8nEntry = this.__a8n; + if ( + __a8nEntry !== undefined && + __a8nEntry !== null && + __a8nEntry.dispatcher !== undefined && + __a8nEntry.dispatcher !== null + ) { + startDispatcher(__a8nEntry.dispatcher); + } else { + main(); + } + } + boot(); +})(); diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-json.js b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-json.js new file mode 100644 index 00000000..0d043d5d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/staging/a8n-json.js @@ -0,0 +1,311 @@ +/*! + * a8n-json.js — JSON codec for ExtendScript (ES3). + * + * After Effects' ExtendScript engine has no built-in `JSON`. Rather than + * assume, the host feature-detects a native one and falls back to this. + * + * The implementation is deliberately small: it covers exactly the subset the + * protocol uses (objects, arrays, strings, finite numbers, booleans, null). + * `test/fake-host.test.ts` differential-tests it against Node's JSON so the + * two encoders cannot drift apart unnoticed. + * + * ES3 only. No const/let, no arrow functions, no ES5 built-ins. + */ + +var A8NJson = (function () { + var ESCAPES = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + + // ExtendScript's Object.prototype carries non-enumerable members — among + // them functions named "+", "-", "*" and "/" (observed on AE 26.5x89) — so a + // plain `table[key]` finds one for any of those characters. Every lookup by + // a key that came from data goes through `has`. + function has(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + function quoteChar(ch) { + if (has(ESCAPES, ch)) { + return ESCAPES[ch]; + } + var code = ch.charCodeAt(0); + if (code < 0x20) { + var hex = code.toString(16); + while (hex.length < 4) { + hex = "0" + hex; + } + return "\\u" + hex; + } + return ch; + } + + function stringifyString(value) { + var out = '"'; + for (var i = 0; i < value.length; i++) { + out += quoteChar(value.charAt(i)); + } + return out + '"'; + } + + function isArray(value) { + // Not `instanceof Array`: values that crossed into this engine from a host + // (or another realm) fail an instanceof check against a local Array. + return Object.prototype.toString.call(value) === "[object Array]"; + } + + function stringify(value) { + if (value === null) { + return "null"; + } + var type = typeof value; + if (type === "boolean") { + return value ? "true" : "false"; + } + if (type === "number") { + if (!isFinite(value)) { + // Matches JSON.stringify: non-finite numbers become null. + return "null"; + } + return String(value); + } + if (type === "string") { + return stringifyString(value); + } + if (isArray(value)) { + var parts = []; + for (var i = 0; i < value.length; i++) { + var element = stringify(value[i]); + // undefined and functions serialise as null inside arrays. + parts.push(element === undefined ? "null" : element); + } + return "[" + parts.join(",") + "]"; + } + if (type === "object") { + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + var keys = []; + for (var key in value) { + if (has(value, key)) { + var serialised = stringify(value[key]); + if (serialised !== undefined) { + keys.push(stringifyString(key) + ":" + serialised); + } + } + } + return "{" + keys.join(",") + "}"; + } + return undefined; + } + + function ParseError(message, line, column) { + this.name = "A8NJsonParseError"; + this.message = message; + this.line = line; + this.column = column; + } + ParseError.prototype = new Error(); + + function parse(text) { + var pos = 0; + + function fail(message) { + var consumed = text.substring(0, pos); + var line = 1; + var lastNewline = -1; + for (var i = 0; i < consumed.length; i++) { + if (charAt(consumed, i) === "\n") { + line += 1; + lastNewline = i; + } + } + throw new ParseError(message, line, pos - lastNewline); + } + + function charAt(source, index) { + return source.charAt(index); + } + + function whitespace() { + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + pos += 1; + } else { + break; + } + } + } + + function expect(ch) { + if (text.charAt(pos) !== ch) { + fail("expected '" + ch + "'"); + } + pos += 1; + } + + function parseString() { + // Caller has already checked the opening quote. + pos += 1; + var out = ""; + while (pos < text.length) { + var ch = text.charAt(pos); + if (ch === '"') { + pos += 1; + return out; + } + if (ch === "\\") { + pos += 1; + var esc = text.charAt(pos); + if (esc === "u") { + var hex = text.substring(pos + 1, pos + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) { + fail("invalid unicode escape"); + } + out += String.fromCharCode(parseInt(hex, 16)); + pos += 5; + continue; + } + var simple = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t" + }; + if (!has(simple, esc)) { + fail("invalid escape \\" + esc); + } + out += simple[esc]; + pos += 1; + continue; + } + out += ch; + pos += 1; + } + fail("unterminated string"); + } + + function parseNumber() { + var match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec( + text.substring(pos) + ); + if (match === null) { + fail("invalid number"); + } + pos += match[0].length; + return parseFloat(match[0]); + } + + function parseArray() { + pos += 1; // [ + var items = []; + whitespace(); + if (text.charAt(pos) === "]") { + pos += 1; + return items; + } + for (;;) { + whitespace(); + items.push(parseValue()); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "]") { + pos += 1; + return items; + } + fail("expected ',' or ']'"); + } + } + + function parseObject() { + pos += 1; // { + var out = {}; + whitespace(); + if (text.charAt(pos) === "}") { + pos += 1; + return out; + } + for (;;) { + whitespace(); + if (text.charAt(pos) !== '"') { + fail("expected object key"); + } + var key = parseString(); + whitespace(); + expect(":"); + whitespace(); + out[key] = parseValue(); + whitespace(); + var ch = text.charAt(pos); + if (ch === ",") { + pos += 1; + continue; + } + if (ch === "}") { + pos += 1; + return out; + } + fail("expected ',' or '}'"); + } + } + + function parseValue() { + var ch = text.charAt(pos); + if (ch === "{") { + return parseObject(); + } + if (ch === "[") { + return parseArray(); + } + if (ch === '"') { + return parseString(); + } + if (text.substr(pos, 4) === "true") { + pos += 4; + return true; + } + if (text.substr(pos, 5) === "false") { + pos += 5; + return false; + } + if (text.substr(pos, 4) === "null") { + pos += 4; + return null; + } + if (ch === "-" || (ch >= "0" && ch <= "9")) { + return parseNumber(); + } + fail("unexpected token"); + } + + whitespace(); + var value = parseValue(); + whitespace(); + if (pos !== text.length) { + fail("trailing content"); + } + return value; + } + + return { stringify: stringify, parse: parse }; +})(); + +// The completion value, so `$.evalFile` returns the codec. A real AE scopes an +// included file's `var`s to the calling function, so the caller cannot look +// `A8NJson` up on the global object. +A8NJson; diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/trace.jsonl b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/trace.jsonl new file mode 100644 index 00000000..b68f66ee --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/ae-session/trace.jsonl @@ -0,0 +1 @@ +{"seq":0,"ts":"2026-11-28T19:05:40.576Z","op":"session.launch","status":"error","durationMs":2,"args":{"transport":"script-invocation"},"error":{"name":"AttachTargetError","message":"attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport."}} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/run.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/run.json new file mode 100644 index 00000000..79d9301d --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/run.json @@ -0,0 +1,247 @@ +{ + "schema": "ty-plus.e2e-run/1", + "suite": "settings", + "capturedAt": "2026-11-28T19:06:39.761Z", + "extensionDir": "C:\\Users\\rebui\\AppData\\Roaming\\Adobe\\CEP\\extensions\\app.ty-plus.dev", + "managedRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-05-40-587Z-80788/ty-plus", + "realManagedRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "aeSession": { + "attached": false, + "pid": null, + "ownership": null, + "version": null, + "sessionRoot": null, + "error": "attach-only is not available through script invocation on Windows: every script delivery spawns AfterFX.exe -r, which creates a process. Use transport \"in-ae-dispatcher\" (a running After Effects with the dispatcher activated) or supply your own HostTransport." + }, + "aeDiagnostics": null, + "sandbox": { + "enabled": true, + "sandboxRoot": "C:/Users/rebui/AppData/Local/Temp/ty-plus-e2e-sandbox/2026-11-28T19-05-40-587Z-80788/ty-plus", + "integrity": { + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:06:39.759Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true + } + }, + "totals": { + "PASS": 4, + "FAIL": 0, + "BLOCKED": 0, + "SKIP": 0 + }, + "results": [ + { + "uc": "UC-E01", + "title": "ui.language in app.json drives panel locale across reload", + "status": "PASS", + "detail": "locale en → ja → restored", + "checks": [ + { + "name": "settings/app.json ui.language set to ja", + "ok": true, + "detail": "language=ja" + }, + { + "name": "document.documentElement.lang reflects locale", + "ok": true, + "detail": "lang=ja expected=ja" + }, + { + "name": "settings dialog renders ja strings", + "ok": true, + "detail": "tablist aria-label=\"設定セクション\" expected=\"設定セクション\"" + }, + { + "name": "settings/app.json restored after case", + "ok": true, + "detail": "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-05-40-587Z-80788\\ty-plus\\settings\\app.json 1352 bytes" + } + ], + "evidence": [], + "durationMs": 10891 + }, + { + "uc": "UC-E01", + "title": "settings UI round-trip: Language ListSelect → app.json ui.language → reload documentElement.lang", + "status": "PASS", + "detail": "language en → ja via ListSelect → restored", + "checks": [ + { + "name": "language section opened", + "ok": true, + "detail": "" + }, + { + "name": "language ListSelect trigger opened", + "ok": true, + "detail": "clicked" + }, + { + "name": "language listbox rendered all locale options", + "ok": true, + "detail": "options=10 expected=10" + }, + { + "name": "language option ja clicked", + "ok": true, + "detail": "label=\"Japanese\"" + }, + { + "name": "app.json ui.language persisted via UI", + "ok": true, + "detail": "language=ja" + }, + { + "name": "open dialog re-rendered in new locale", + "ok": true, + "detail": "tablist aria-label=\"設定セクション\" expected=\"設定セクション\"" + }, + { + "name": "document.documentElement.lang reflects UI-chosen locale", + "ok": true, + "detail": "lang=ja expected=ja" + }, + { + "name": "reopened dialog renders persisted locale", + "ok": true, + "detail": "tablist aria-label=\"設定セクション\" expected=\"設定セクション\"" + }, + { + "name": "settings/app.json restored after case", + "ok": true, + "detail": "language=en" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-05-40-587Z-80788\\ty-plus\\settings\\app.json" + ], + "durationMs": 13092 + }, + { + "uc": "UC-E02", + "title": "settings UI round-trip: appearance ColorField + RangeField → app.json/theme.css → reload re-display", + "status": "PASS", + "detail": "accent=#3355cc widgetOpacity=63 via settings UI", + "checks": [ + { + "name": "appearance section opened", + "ok": true, + "detail": "" + }, + { + "name": "accent ColorField accepted value", + "ok": true, + "detail": "value=#3355cc" + }, + { + "name": "app.json ui.accentColor persisted", + "ok": true, + "detail": "accent=#3355cc" + }, + { + "name": "accent reached live panel theme token", + "ok": true, + "detail": "accent=#3355cc" + }, + { + "name": "widget opacity RangeField accepted value", + "ok": true, + "detail": "value=63" + }, + { + "name": "app.json ui.widget.opacity persisted", + "ok": true, + "detail": "opacity=63" + }, + { + "name": "theme.css carries accent token", + "ok": true, + "detail": "" + }, + { + "name": "appearance section reopened after reload", + "ok": true, + "detail": "" + }, + { + "name": "accent ColorField re-displays persisted value", + "ok": true, + "detail": "value=#3355cc" + }, + { + "name": "opacity RangeField re-displays persisted value", + "ok": true, + "detail": "value=63" + }, + { + "name": "settings/app.json restored after case", + "ok": true, + "detail": "accent=#e2b701" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-05-40-587Z-80788\\ty-plus\\settings\\app.json", + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-05-40-587Z-80788\\ty-plus\\styles\\theme.css" + ], + "durationMs": 13686 + }, + { + "uc": "UC-E10", + "title": "settings save failure: role=alert shown, dialog stays open, app.json untouched", + "status": "PASS", + "detail": "save failure surfaced role=alert; app.json preserved", + "checks": [ + { + "name": "appearance section opened", + "ok": true, + "detail": "" + }, + { + "name": "accent edit dispatched while save target broken", + "ok": true, + "detail": "value=#aa3355" + }, + { + "name": "role=alert banner rendered on save failure", + "ok": true, + "detail": "" + }, + { + "name": "alert shows localized save-failure message", + "ok": true, + "detail": "alert=\"Failed to save settings. The settings folder may be read-only.\" expected=\"Failed to save settings. The settings folder may be read-only.\"" + }, + { + "name": "failed save left no partial-write residue", + "ok": true, + "detail": "entries=[]" + }, + { + "name": "dialog stayed open after failed Save", + "ok": true, + "detail": "saveButton=true" + }, + { + "name": "settings/app.json byte-identical after failed save", + "ok": true, + "detail": "before=1352B after=1352B" + } + ], + "evidence": [ + "C:\\Users\\rebui\\AppData\\Local\\Temp\\ty-plus-e2e-sandbox\\2026-11-28T19-05-40-587Z-80788\\ty-plus\\settings\\app.json" + ], + "durationMs": 12576 + } + ] +} diff --git a/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/sandbox-integrity.json b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/sandbox-integrity.json new file mode 100644 index 00000000..97462c6f --- /dev/null +++ b/docs/verification/e2e-acceptance/results/2026-11-29-release-0-14-0-win-ae2027/rerun-settings/settings/sandbox-integrity.json @@ -0,0 +1,16 @@ +{ + "realRoot": "D:/4_apps/adobe/Adobe After Effects 2027/Support Files/ty-plus", + "checkedAt": "2026-11-28T19:06:39.759Z", + "driftBeforeRepair": { + "changed": 4, + "added": 0, + "removed": 0 + }, + "filesRepaired": [ + "cache/layout-undo/panel-1/stack.json", + "cache/layout-undo/panel-4/stack.json", + "cache/layout-undo/panel-5/stack.json", + "cache/layout-undo/panel-3/stack.json" + ], + "cleanAfterRepair": true +} diff --git a/docs/verification/e2e-acceptance/use-case-matrix.md b/docs/verification/e2e-acceptance/use-case-matrix.md index 487ad106..e611b514 100644 --- a/docs/verification/e2e-acceptance/use-case-matrix.md +++ b/docs/verification/e2e-acceptance/use-case-matrix.md @@ -8,7 +8,7 @@ | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | -| UC-A01 | 初回起動 → onboarding 10 ステップ完了 → workspace 表示 | managed root 生成、`settings/app.json`、`workspaces/workspace-1.json`、`presets.json`、panel DOM | semi | both | 未実施 | | +| UC-A01 | 初回起動 → onboarding 10 ステップ完了 → workspace 表示 | managed root 生成、`settings/app.json`、`workspaces/workspace-1.json`、`presets.json`、panel DOM | semi | both | 未実施 | #784 | | UC-A02 | 既存データでの起動 → layout/settings/theme 復元 | workspace-N.json・app.json・theme.css の内容が起動後 UI に反映 | auto | both | win:自動PASS / mac:自動PASS | results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | | UC-A03 | panel-1〜5 の開閉と独立性 | 各 panel が別 surface として応答、layout が panel 毎に独立 | auto | both | win:自動PASS / mac:自動PASS | results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | | UC-A04 | AE 再起動をまたぐ host bundle 常駐/self-heal | `$.global.__TY_PLUS_HOST__` contract、worker verify ok | auto | both | mac:自動PASS / win:自動PASS | results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-extended/host/run.json / #107修正済(PR #116) | @@ -20,28 +20,28 @@ | --- | --- | --- | --- | --- | --- | --- | | UC-B01 | preset を tile として配置(toolbar/catalog/drag)| workspace-N.json の gridCells に追加、tile DOM | auto | both | mac:自動PASS(作成dialog経路のみ。catalog/drag は未カバー) / win:未実施 | results/2026-11-15-device-macos-ae2026-dev-journey/run.json | | UC-B02 | widget を Add Widget dialog から追加 | widgets.json record、tile 描画、layout reload | auto | both | mac:自動PASS(sandbox) / win:未実施 | results/2026-11-16-device-macos-ae2026-dev-workspace-sandbox/run.json | -| UC-B03 | tile 移動・リサイズ・削除・複製 | workspace-N.json の座標/サイズ更新、DOM 反映 | semi | both | 未実施 | | +| UC-B03 | tile 移動・リサイズ・削除・複製 | workspace-N.json の座標/サイズ更新、DOM 反映 | semi | both | 未実施(ケース追加済) | #786 | | UC-B04 | grid 設定(cell/gap/radius)変更 → live 反映 → reload 後維持 | theme.css `--ty-ws-*`、app.json `workspace.grid`、computed style、実セルサイズ | auto | both | win:自動PASS / mac:自動PASS(#112修正済) | #95 / results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | | UC-B05 | レイアウトスナップショット保存→変更→復元→削除 | snapshots.json、全パネル layout 復元 | auto | both | mac:自動PASS(sandbox, 単一run完走) / win:未実施 | results/2026-11-16-device-macos-ae2026-dev-workspace-sandbox/run.json | -| UC-B06 | Undo/Redo | 操作の巻き戻し/やり直しが layout に反映 | semi | both | 未実施 | | +| UC-B06 | Undo/Redo | 操作の巻き戻し/やり直しが layout に反映 | semi | both | 未実施(ケース追加済) | #786 | | UC-B07 | 複数パネル間の preset 配置移動 | workspacePanels roster、対象 panel の tile | semi | both | 未実施 | | | UC-B08 | 背景エディタで color/pattern/image レイヤー編集 | background-N.json、panel 背景描画 | semi | both | 未実施 | | -| UC-B09 | ControlPanel collapse/向き/位置変更 → reload 後維持 | panels/panel-N.json | auto | both | 未実施 | | -| UC-B10 | Layout Lock widget で編集ロック | gesture が効かないこと、widget state | semi | both | 未実施 | | +| UC-B09 | ControlPanel collapse/向き/位置変更 → reload 後維持 | panels/panel-N.json | auto | both | 未実施(ケース追加済) | #786 | +| UC-B10 | Layout Lock widget で編集ロック | gesture が効かないこと、widget state | semi | both | 未実施(ケース追加済) | #786 | | UC-B11 | 破損 workspace-N.json で起動・編集 | 既存データを消さない、空 layout 化しない | auto | both | mac:自動PASS / win:未実施 | results/2026-11-15-device-macos-ae2026-dev-extended.md(起動側のみ。編集 gesture は未カバー) | ## C. プリセット | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | -| UC-C01 | Local preset 作成(path 指定)→ presets.json + tile | presets.json record、dialog 閉鎖、tile 配置 | semi | both | 未実施 | | -| UC-C02 | Group preset 作成(folder 走査・icon rules)| groups.json/presets.json、group tile、メンバー展開 | semi | both | 未実施 | | -| UC-C03 | Animation preset 作成(`.ffx` + AE save dialog)| .ffx ファイル生成、presets.json、tile | semi | both | 未実施 | | -| UC-C04 | Code preset 作成(Script/Expression)| .jsx 生成、presets.json | semi | both | 未実施 | | -| UC-C05 | Layer/Comp preset 作成 | scriptRoot 配下ファイル、presets.json(失敗時の壊れた record 非残留も確認)| semi | both | 未実施 | guide既知: macOS で作成失敗事例あり | -| UC-C06 | Footage/Import preset 作成・実行 | presets.json、AE への footage 追加 | semi | both | 未実施 | | -| UC-C07 | Easing preset 作成(カーブ→`.jsx`)| .jsx 生成、presets.json | semi | both | 未実施 | | -| UC-C08 | preset 編集(名前/説明/icon/メンバー)| presets.json 更新、tile/一覧反映 | semi | both | 未実施 | | +| UC-C01 | Local preset 作成(path 指定)→ presets.json + tile | presets.json record、dialog 閉鎖、tile 配置 | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C02 | Group preset 作成(folder 走査・icon rules) | groups.json/presets.json、group tile、メンバー展開 | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C03 | Animation preset 作成(`.ffx` + AE save dialog) | .ffx ファイル生成、presets.json、tile | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C04 | Code preset 作成(Script/Expression) | .jsx 生成、presets.json | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C05 | Layer/Comp preset 作成 | scriptRoot 配下ファイル、presets.json(失敗時の壊れた record 非残留も確認) | semi | both | 未実施 | guide既知: macOS で作成失敗事例あり / #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C06 | Footage/Import preset 作成・実行 | presets.json、AE への footage 追加 | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C07 | Easing preset 作成(カーブ→`.jsx`) | .jsx 生成、presets.json | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | +| UC-C08 | preset 編集(名前/説明/icon/メンバー) | presets.json 更新、tile/一覧反映 | semi | both | 未実施 | #785 / preset-create suite (scripts/verify/e2e/cases/preset-create.ts)・case実装済未実行 | | UC-C09 | preset 複製・削除 | presets.json、workspace/group/search から消える | semi | both | 未実施 | | | UC-C10 | `.ffx` preset を選択レイヤーへ実行 | AE Effect Controls/レイヤーに効果適用 | semi | both | mac:自動PASS / win:未実施 | #10 D-06 / results/2026-11-15-device-macos-ae2026-dev-journey/run.json | | UC-C11 | `.jsx` script preset 実行 | AE 側の実行結果(例: レイヤー/テキスト変化)| semi | both | mac:自動PASS / win:未実施 | #10 D-05 / results/2026-11-15-device-macos-ae2026-dev-journey/run.json | @@ -57,15 +57,15 @@ | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | | UC-D01 | Add Widget dialog:検索・カテゴリ・view 切替・追加 | widgets.json、対象 panel の tile | auto | both | 未実施 | | -| UC-D02 | easing:カーブ編集 → AE 選択キーフレームへ apply | AE keyframe influence/speed 変化 | semi | both | 未実施 | | +| UC-D02 | easing:カーブ編集 → AE 選択キーフレームへ apply | AE keyframe influence/speed 変化 | semi | both | 未実施(ケース追加済・空選択 notice 経路) | #786 | | UC-D03 | easing:loop mode・複数セグメント・label colors | AE keyframe/label 変化 | semi | both | 未実施 | | | UC-D04 | easing:clipboard(copy/paste keyframe values)| clipboard.json、AE 値反映 | semi | both | 未実施 | | -| UC-D05 | align:選択レイヤー整列/分布 | AE レイヤー位置変化 | semi | both | 未実施 | | -| UC-D06 | anchor-point:9 方向 + apply all/comp | AE anchor point/position 変化 | semi | both | 未実施 | | -| UC-D07 | info widget:comp/project 情報表示 | DOM 内容が AE 状態と一致 | auto | both | 未実施 | | -| UC-D08 | font-viewer:フォント一覧・選択テキストへ適用 | font 一覧取得、AE text font 変化 | semi | both | 未実施 | | -| UC-D09 | directory-browser:遷移・filter・選択・preset 実行 | DOM、選択ファイルの preset 実行 | semi | both | 未実施 | | -| UC-D10 | menu/quick-actions:クイック実行 | preset 実行結果 | semi | both | mac:自動PASS(sandbox, 連続2回でAE marker確認) / win:未実施 | #125修正済 / results/2026-11-16-device-macos-ae2026-dev-workspace-sandbox/run.json | +| UC-D05 | align:選択レイヤー整列/分布 | AE レイヤー位置変化 | semi | both | 未実施(ケース追加済) | #786 | +| UC-D06 | anchor-point:9 方向 + apply all/comp | AE anchor point/position 変化 | semi | both | 未実施(ケース追加済) | #786 | +| UC-D07 | info widget:comp/project 情報表示 | DOM 内容が AE 状態と一致 | auto | both | 未実施(ケース追加済・preset 選択経路) | #786 | +| UC-D08 | font-viewer:フォント一覧・選択テキストへ適用 | font 一覧取得、AE text font 変化 | semi | both | 未実施(ケース追加済・一覧/search 経路) | #786 | +| UC-D09 | directory-browser:遷移・filter・選択・preset 実行 | DOM、選択ファイルの preset 実行 | semi | both | 未実施(ケース追加済・open/search/遷移経路) | #784 / #786 | +| UC-D10 | menu/quick-actions:クイック実行 | preset 実行結果 | semi | both | mac:自動PASS(sandbox, 連続2回でAE marker確認) / win:未実施 | #125修正済 / #786ケース追加 / results/2026-11-16-device-macos-ae2026-dev-workspace-sandbox/run.json | | UC-D11 | widget state 永続化(widgets/state/*.json)| reload 後の widget 状態復元 | auto | both | mac:自動PASS / win:自動PASS | results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-rerun/widgets/run.json | | UC-D12 | 破損 widgets.json で起動・編集 | 既存 record 非破壊 | auto | both | mac:自動PASS / win:未実施 | results/2026-11-15-device-macos-ae2026-dev-extended.md(UC-I02 と同一ファイル・同一契約) | @@ -73,33 +73,33 @@ | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | -| UC-E01 | 言語切替 → 全 surface 反映 → reload 後維持 | ui.json locale、`documentElement.lang`、文言 DOM | auto | both | mac:自動PASS / win:自動PASS(#121 修正・#122 merge 後の build で確認)| results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-rerun3/settings/run.json | -| UC-E02 | 外観色変更(accent/text/widget/panel)→ live → reload 維持 | app.json `ui.*`、theme.css token、computed style | auto | both | win:自動PASS / mac:自動PASS(#112修正済) | #94 / results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | +| UC-E01 | 言語切替 → 全 surface 反映 → reload 後維持 | ui.json locale、`documentElement.lang`、文言 DOM | auto | both | mac:自動PASS / win:自動PASS(#121 修正・#122 merge 後の build で確認)| results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-rerun3/settings/run.json ; Settings dialog ListSelect UI経路case追加(#783・実機未実施) | +| UC-E02 | 外観色変更(accent/text/widget/panel)→ live → reload 維持 | app.json `ui.*`、theme.css token、computed style | auto | both | win:自動PASS / mac:自動PASS(#112修正済) | #94 / results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json ; Settings dialog ColorField/RangeField UI経路case追加(#783・実機未実施) | | UC-E03 | theme tokens 編集(Apply/Export/Import/reset)| theme.css、export/import round-trip | semi | both | 未実施 | #91 | | UC-E04 | support root 変更 → relocation/copy/delete → 全パネル reload | app.json paths、managed root 移動、layout 復元 | semi | both | 未実施 | | | UC-E05 | preset/script/plugin root 変更 | app.json paths、preset scan 反映 | semi | both | 未実施 | | | UC-E06 | workspace backup export → 別状態で import | bundle JSON、settings/presets/theme/layouts/backgrounds 復元 | semi | both | 未実施 | | -| UC-E07 | update channel 変更 + check now | app.json、releases 参照、UI 表示 | semi | both | 未実施 | | +| UC-E07 | update channel 変更 + check now | app.json、releases 参照、UI 表示 | semi | both | 未実施 | #784 | | UC-E08 | feedback 送信 | GitHub issue URL が事前入力で開く | manual | both | 未実施 | | | UC-E09 | inputs toggle(anchor/alignment gesture)| app.json gestures、gesture 動作 | semi | both | 未実施 | | -| UC-E10 | settings 保存失敗 → dialog alert 表示・データ非破壊 | role=alert、app.json byte-identical | auto | both | 未実施 | #96, #10 D-12 | +| UC-E10 | settings 保存失敗 → dialog alert 表示・データ非破壊 | role=alert、app.json byte-identical | auto | both | case追加(#783)・実機未実施 | #96, #10 D-12, #783 | | UC-E11 | theme.css surface 間同時書込の直列化 | 最終 theme.css が両変更を含む | semi | both | 未実施 | #106 | ## F. オンライン/通知 | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | -| UC-F01 | preset library:検索・view 切替・download → local catalog | catalog DOM、download 完了、presets.json 反映 | semi | both | 未実施 | guide既知: 「Download complete」だが file 未保存の報告あり | -| UC-F02 | notification center:list/detail/既読/sync | cache/notifications.json、DOM | semi | both | 未実施 | | +| UC-F01 | preset library:検索・view 切替・download → local catalog | catalog DOM、download 完了、presets.json 反映 | semi | both | 未実施 | guide既知: 「Download complete」だが file 未保存の報告あり, #784 | +| UC-F02 | notification center:list/detail/既読/sync | cache/notifications.json、DOM | semi | both | 未実施 | #784 | | UC-F03 | offline/degraded → core 機能継続 | gateway なしで workspace/preset が動く | semi | both | 未実施 | #10 D-15, online-degraded.feature | -| UC-F04 | update feed 確認 | releases API 結果表示 | semi | both | 未実施 | #10 D-13 | -| UC-F05 | notification feed 確認 | 公式通知表示 | semi | both | 未実施 | #10 D-14 | +| UC-F04 | update feed 確認 | releases API 結果表示 | semi | both | 未実施 | #10 D-13, #784 | +| UC-F05 | notification feed 確認 | 公式通知表示 | semi | both | 未実施 | #10 D-14, #784 | ## G. デバッグ・診断 | ID | ユースケース | 主な確認対象 | 自動化 | OS | 状態 | 証跡/Issue | | --- | --- | --- | --- | --- | --- | --- | -| UC-G01 | debug console:ログ集約・filter・eval・clear | debug-console DOM、eval 結果、clear 同期 | auto | both | win:自動PASS / mac:自動PASS | #10 D-07, W-03 / results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | +| UC-G01 | debug console:ログ集約・filter・eval・clear | debug-console DOM、eval 結果、clear 同期 | auto | both | win:自動PASS / mac:自動PASS | #10 D-07, W-03 / #786 eval/filter/clear拡張 / results/2026-11-15-device-windows-ae2027-dev-smoke-run.json / results/macos-ae2026-dev/run.json / results/2026-11-15-device-windows-ae2027-dev-extended/smoke/run.json | | UC-G02 | console reopen で replay | 過去ログ表示 | auto | both | mac:自動PASS / win:自動PASS | results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-rerun/debug/run.json | | UC-G03 | operation worker verify(spawn→accept→result→exit)| verify JSON(rowCount/exit code)| auto | both | mac:自動PASS / win:自動PASS | results/2026-11-15-device-macos-ae2026-dev-extended.md / results/2026-11-15-device-windows-ae2027-dev-extended/debug/run.json | | UC-G04 | panel surface の unhandled error が console に出る | #71/#69/#67 系の回帰観測 | auto | both | 未実施 | #71,#69,#67 | diff --git a/docs/verification/ui-rollback-ae-0-14-0/README.md b/docs/verification/ui-rollback-ae-0-14-0/README.md new file mode 100644 index 00000000..883945d0 --- /dev/null +++ b/docs/verification/ui-rollback-ae-0-14-0/README.md @@ -0,0 +1,135 @@ +# UI/UX ロールバック解消の実機視覚検証 (release-0-14-0, Issue #591 系) + +`release-0-14-0` に merge された UI 修正群について、Storybook / unit test +だけでなく After Effects 実機 (macOS / AE2026 26.5.3) 上の dev bundle +(`app.ty-plus.dev` → `dist/cep-dev`、HEAD `493cdc36` 時点の build) で +描画・操作結果を確認した記録。 + +> **ホストに関する注意**: 検証時に AE2026 (pid 55912) と AE2027 (pid 65119) +> の両方が起動しており、`.debug` の debug port (31010–) は先に bind した +> **AE2026 側の CEPHtmlEngine が占有**していた (`lsof` で確認)。 +> したがって本記録の実機確認は全て AE2026 / 26.5.3 上の描画である。 +> AE2027 側の panel は同一 dev bundle を読み込んでいるが CDP port が +> 衝突しており、本記録の DOM 検査は AE2027 では未実施。 + +## 環境・手法 + +- AE2026 (pid 55912) に Window > Extensions から dev panel 1–5 と + modeless dialog 群を起動。`.debug` の debug port (panel1=31010、 + widget-selector=31030、preset-edit=31024、settings=31029 等) 経由で + CDP (`Runtime.evaluate` / `Page.captureScreenshot`) を使用。 +- 判定は DOM の computed style・矩形・テキスト構造に対する機械的検査と、 + `Page.captureScreenshot` の証跡画像の組み合わせ。画像の目視評価は + 本記録の対象外 (別途視覚レビューで実施)。 + +## 実機で確認した修正 + +| Issue | 修正 | 実機での確認内容 | +| --- | --- | --- | +| #670 | align 対象切替行を常時表示・下部固定 | panel1 の align widget で対象ボタン 4 個が target=time でも描画され続けることを DOM で確認 (`align-target-row.png`) | +| #668 / #685 | Quick Actions パレットの dropdown を検索フィールド直下に固定 | widget tile `8f89155e` で検索 focus 後、portal dropdown が input 下端 +4px・tile 幅一致で出現 (top=210 / input bottom=208 / w=338) | +| #675 | FontViewer compact 幅で結果ペインが潰れない | font viewer tile 内に `w_min(34%,12rem)` + `flex-sh_0` + `min-w_0` の結果ペインが実描画 (160px)、font row 265 件 | +| #677 | WidgetTutorialLayer の tooltip を widget 領域基準に | panel1 で tutorial bubble「Shape the cycle」が widget highlight (518,722,346x191) 直上 (566,621) に表示 | +| #679 | RangeField のラベル値二重表示を解消 | settings `#component-preview` の「Slider with numeric input」でラベルは名前のみ、NumberField の aria-label が `... value %`、unit `%` は 1 箇所のみ (`settings-component-preview.png`) | +| #680 | StatusBar の badge / aria-label / status text | panel1 status bar に「After Effects」+ 件数 badge (1 / 36) と全ボタンの aria-label を確認 | +| #673 | preset type badge の単語途中 wrap 解消 | preset list dialog の glyph が 5 grapheme 名称で 1 行 (h=16px = font-size) に収まることを確認。group edit dialog の FFX badge 301 件も全て単一行 (h=16px) (`preset-list-badges.png`, `group-edit-members.png`) | +| #674 | dialog footer の水平 inset を shell primitive に統一 | settings dialog と preset edit dialog の `footer[data-dialog-footer]` で `padding-inline: 8px` (= `--ty-shell-pad-inline`) を確認 | +| #681 | preset edit dialog の error kind 区別 | preset edit dialog (31024) が正常系で開き、Cancel/Delete/Save が有効・footer inset 正常 (`preset-edit-dialog.png`)。失敗系 (delete 失敗後の retry) は unit test で担保 | +| #684 | 折りたたみ時 control panel の展開 affordance | panel2–5 は既定で collapsed 描画。`[data-cp]` に `data-collapsed="true"` + `ty.ctx.cp.toggle-collapse` IconButton (ChevronsUpDown) が存在し、click で 20x20 → 164x38 に展開・6 ボタン表示を確認 | +| #676 | group catalog tile の keyline / count badge | group preset「Verify Group」(300 members) を作成し workspace catalog tile で確認。surface は `inset:1px` + `1px solid border.subtle` + `surface.widget`、badge は「99+」chip (surface.dialog / border.subtle / radius full) (`group-catalog-tile.png`) | +| #686 | MembersSection の path key 安定化 | group preset edit dialog で MEMBER PRESETS (300) が描画され、各行に FFX badge + 名前を確認。300 行で render 破綻なし (`group-edit-members.png`)。key 安定性自体は unit test で担保 | + +## コード・テストで担保し実機未踏の項目 + +| Issue | 内容 | 状態 | +| --- | --- | --- | +| #672 | Loop wave の label obstacle sampling (`waveLabelObstacles`) | canvas 描画のため DOM 検査不可。`loop-wave-labels.png` を証跡として保存。配置ロジックは unit test で担保 | +| #682 | `.debug` port band 修正 | build 時の port 採番であり、今回の build (31010–31031) が ephemeral range (49152+) を避けていることを `.debug` で確認済み | + +## 証跡ファイル + +| ファイル | 内容 | +| --- | --- | +| `workspace-panel.png` | panel1 全体 (16 widget tile 配置、status bar) | +| `loop-wave-labels.png` | Loop widget の wave canvas (clip) | +| `preset-edit-dialog.png` | preset edit dialog (ICON Text/Emoji/Image、footer) | +| `preset-list-badges.png` | preset list dialog (glyph + type 表記) | +| `settings-component-preview.png` | settings Component Preview (RangeField 等) | +| `align-target-row.png` | align widget の対象切替行 | +| `widget-selector.png` | Add widget modeless dialog | +| `group-catalog-tile.png` | workspace catalog の group tile (FFX + 99+ badge) | +| `group-edit-members.png` | group preset edit dialog (MEMBER PRESETS 300) | +| `cef-font-floor-glyphs-0-14-0.png` | preset catalog dialog の text glyph 310 件 (#704 修正後、10px+scale 描画、AE2026) | +| `cef-font-floor-glyphs-ae2027.png` | 同上、AE2027 (dev build) | +| `cef-glyph-broken-release-0-13-1.png` | v0.13.1 release の text glyph 破損状態 (before、AE2027) | + +## 追記: CEF 描画制約の修正検証 (#700 / #701 / #704) + +#665 の実機 DOM 監査で発見した CEF 固有の 2 制約について、修正 merge 後の +build (`909c2a89`、`dist/cep-dev`) で AE2026 実機再検証を実施した。 + +### #700: container query 無効 → px 実測 fit + +- `CSS.supports('container-type','inline-size')` / `CSS.supports('width','1cqi')` + が本番 CEF (Chromium 99 系) で共に `false` であることを再確認。 +- 修正後は glyph の font-size / borderRadius を JS 実測 px + CSS custom + property (`--ws-glyph-text-font-px`) 経由で適用するため、container query + 非対応環境でも値が落ちない。 + +### #704: font-size 10px フロア → 10px 描画 + transform scale + +- CEF は computed font-size を ~10px 未満にできない (inline + `font-size:3px` でも computed は `10px`)。#700 の fit 値が 10px 未満に + なるケースで文字が overflow する問題を、`resolveFittedTextFont` で + 「10px 描画 + `transform: scale(desired/10)`」に分解して解消。 +- **実機確認**: preset catalog dialog (`dialog-presets`) に実 preset + 310 件分の text glyph が描画され、全件で `--ws-glyph-text-font-px=10`、 + `--ws-glyph-text-scale` = 0.343–0.396、wrapper に + `transform: matrix(scale,…)` が適用されていることを DOM で確認。 + 全 glyph の行が frame 内に収まり (`inside=true`)、text clip なし + (`badLines=0`)。証跡: `cef-font-floor-glyphs-0-14-0.png`。 +- #701 (preset/group 削除後の ghost info widget) は #703 で修正済み。 + 削除後の info widget 残留は本検証では preset 削除を再実施していない + ため unit test 担保の範囲。 + +### AE2027 での before/after 対比 + +同一マシンで release `app.ty-plus` (v0.13.1) と dev `app.ty-plus.dev` +(909c2a89) を切り替えて計測した。 + +- **v0.13.1 (before)**: preset catalog の text glyph 310 件**全て**で + font-size 16px のまま frame (22px) からはみ出し、620 行が frame 外・ + 20 行が clip — #700 の container query 無効が本番で発生していることを + 実機確認 (`cef-glyph-broken-release-0-13-1.png`)。 +- **dev build (after)**: AE2027 上でも 310 件全て `fontPx=10` + + `scale=0.343–0.396` で描画、`badLines=0`。AE2026 と同一結果 + (`cef-font-floor-glyphs-ae2027.png`)。 +- 補足: dev panel1 は release panel が debug port (49904) を先に + bind していたため CDP 未接続のまま残った。dev panel5 の + `__adobe_cep__.requestOpenExtension('app.ty-plus.dev.dialog-presets')` + で modeless dialog を直接起動して計測した (製品の dialog 起動経路と + 同一 API)。 +- 検証用に `/Applications/Adobe After Effects 2027/ty-plus/presets/ + presets.json` へ AE2026 と同じ 310 preset (Adobe Express pack、 + filePath を 2027 に書換) を seed した。これは検証環境の状態であり + 製品コードの変更ではない。 + +## 残件 + +- #672 の label 配置は canvas 描画のため DOM 検査が効かず、 + `loop-wave-labels.png` の証跡 + unit test が現状の保証範囲。 +- 検証用に作成した group preset「Verify Group」(300 members) は + preset list dialog から削除済み (native confirm dialog + 「Delete group "Verify Group"? This cannot be undone.」の Yes を + AX 経由で押下。`presets.json` から消失・孤立 .ffx なしを確認)。 +- **AE2027 での同項目検証は #700/#704 の glyph 項目について実施済み** + (上記 before/after 対比)。それ以外の widget 項目 (#670/#675/#677 等) の + AE2027 個別再検証は未実施 — ただし対象コードはホスト非依存の DOM/CSS + であり、AE2026 での確認をもって実機担保とする。 +- Windows 実機での同項目検証は未実施 (v0.13.1 配布物検証は + `distributed-0-13-1/` を参照)。 +- 副次的観察: preset/group の削除確認は `window.confirm` + (`src/management/preset/delete-confirm.ts`) で、CEF では **native + modal dialog** として描画され応答まで renderer 全体 (CDP 含む) が + ブロックされる。実利用では問題ないが、自動化経路では AX 経由の + ダイアログ操作が必要になる。 diff --git a/docs/verification/ui-rollback-ae-0-14-0/align-target-row.png b/docs/verification/ui-rollback-ae-0-14-0/align-target-row.png new file mode 100644 index 00000000..d00f1f0c Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/align-target-row.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-0-14-0.png b/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-0-14-0.png new file mode 100644 index 00000000..6faa935d Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-0-14-0.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-ae2027.png b/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-ae2027.png new file mode 100644 index 00000000..6099be71 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/cef-font-floor-glyphs-ae2027.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/cef-glyph-broken-release-0-13-1.png b/docs/verification/ui-rollback-ae-0-14-0/cef-glyph-broken-release-0-13-1.png new file mode 100644 index 00000000..87393a82 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/cef-glyph-broken-release-0-13-1.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/group-catalog-tile.png b/docs/verification/ui-rollback-ae-0-14-0/group-catalog-tile.png new file mode 100644 index 00000000..e65305fe Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/group-catalog-tile.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/group-edit-members.png b/docs/verification/ui-rollback-ae-0-14-0/group-edit-members.png new file mode 100644 index 00000000..80e66e31 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/group-edit-members.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/loop-wave-labels.png b/docs/verification/ui-rollback-ae-0-14-0/loop-wave-labels.png new file mode 100644 index 00000000..d69878a5 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/loop-wave-labels.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/preset-edit-dialog.png b/docs/verification/ui-rollback-ae-0-14-0/preset-edit-dialog.png new file mode 100644 index 00000000..971c0ca8 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/preset-edit-dialog.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/preset-list-badges.png b/docs/verification/ui-rollback-ae-0-14-0/preset-list-badges.png new file mode 100644 index 00000000..4b62b44c Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/preset-list-badges.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/settings-component-preview.png b/docs/verification/ui-rollback-ae-0-14-0/settings-component-preview.png new file mode 100644 index 00000000..f2b6b123 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/settings-component-preview.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/widget-selector.png b/docs/verification/ui-rollback-ae-0-14-0/widget-selector.png new file mode 100644 index 00000000..85669a6a Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/widget-selector.png differ diff --git a/docs/verification/ui-rollback-ae-0-14-0/workspace-panel.png b/docs/verification/ui-rollback-ae-0-14-0/workspace-panel.png new file mode 100644 index 00000000..4b2f25c7 Binary files /dev/null and b/docs/verification/ui-rollback-ae-0-14-0/workspace-panel.png differ diff --git a/docs/verification/web-capture-322/README.md b/docs/verification/web-capture-322/README.md new file mode 100644 index 00000000..fe8637bd --- /dev/null +++ b/docs/verification/web-capture-322/README.md @@ -0,0 +1,39 @@ +# web-product-capture 実機再検証 (Issue #322) + +`scripts/verify/web-product-capture.ts` の実機キャプチャを AE2026 (26.5.3) +上の dev bundle (`app.ty-plus.dev`) で再実行し、#322 の未解決項目を検証した記録。 + +- 実行日: 2026-11-27 +- 対象: After Effects 2026 / `app.ty-plus.dev` (cep-dev build) +- managed root: `/Applications/Adobe After Effects 2026/ty-plus` +- fixture: `web-product-capture.ts` の DEMO_LAYOUT (widget 8 + preset 10) + +## 結果サマリ + +| #322 項目 | 結果 | +| --- | --- | +| 1. hover → info widget | **製品は正常**。hover で info card が `mode="single"` / source `Hover` / preset title + basename を表示することを実機 DOM で確認。capture script の probe が生の `"hover"`/`"selection"` を case-sensitive に `includes` していたため常に false になっていたのが原因(実ラベルは i18n で `Hover`/`ホバー`、`Selection`/`選択`)。probe を locale 対応に修正(同 PR)。 | +| 2. Add Widget ダイアログ再撮影 | **成功**。`product-add-widget-dialog.png` は今回の実機実行で新規取得(#309 時点の流用ではない)。 | +| 3. Before/After .ffx 適用素材 | **適用自体は検証済み**(demo comp へ実 `.ffx` を適用し、ExtendScript の effect probe で `effects after run` の増加を確認、`preset application verified: true`)。ただし AE ビューポートの Before/After ペア画像は未取得のため、Issue の受入条件に従い `apps/web/public/images/` の素材としては**不使用**とする。 | + +## 証跡 + +| ファイル | 内容 | +| --- | --- | +| `product-workspace-top.png` | fixture 適用後の workspace 上部(実機パネル全体) | +| `product-preset-tiles.png` | preset tile 10 面の描画(glyph は #700/#704 修正後の px-fit 描画) | +| `product-preset-hover.png` | **hover → info widget**: ポップイン tile への hover で info card が `Hover` source で preset 情報を表示した状態のスクリーンショット | +| `info-widget-verify.png` | hover / selection 検証中のパネル状態 | +| `product-preset-run.png` | 実 `.ffx` 適用後の状態(After 側のみ。Before ペアなし) | +| `product-preset-zone-2.png` | 下部 preset zone(info widget + font viewer) | +| `product-presets-dialog.png` | preset catalog ダイアログ | +| `product-add-widget-dialog.png` | **Add Widget ダイアログの実機再撮影** | + +## 補足: 実機検証中に観測した harness 側の問題 + +- 高負荷時(load average ~30)に `Page.reload` 後のパネル boot が数分かかり、 + `reloadSurface` の 45–60s timeout を超過して CDP eval が連続 timeout した。 + ページ自体は生きており、負荷が下がると自然回復する(製品不具合ではない)。 +- 上記のため本記録の hover/selection 検証は、capture script 全体の再実行ではなく + fs.watch による live resync を利用した fixture 適用 + 個別 CDP 検証で実施した。 + script 側の timeout 余裕は別途検討の余地あり。 diff --git a/docs/verification/web-capture-322/info-widget-verify.png b/docs/verification/web-capture-322/info-widget-verify.png new file mode 100644 index 00000000..a7d55db7 Binary files /dev/null and b/docs/verification/web-capture-322/info-widget-verify.png differ diff --git a/docs/verification/web-capture-322/product-add-widget-dialog.png b/docs/verification/web-capture-322/product-add-widget-dialog.png new file mode 100644 index 00000000..85669a6a Binary files /dev/null and b/docs/verification/web-capture-322/product-add-widget-dialog.png differ diff --git a/docs/verification/web-capture-322/product-preset-hover.png b/docs/verification/web-capture-322/product-preset-hover.png new file mode 100644 index 00000000..7ffc3dec Binary files /dev/null and b/docs/verification/web-capture-322/product-preset-hover.png differ diff --git a/docs/verification/web-capture-322/product-preset-run.png b/docs/verification/web-capture-322/product-preset-run.png new file mode 100644 index 00000000..cbf0c2bb Binary files /dev/null and b/docs/verification/web-capture-322/product-preset-run.png differ diff --git a/docs/verification/web-capture-322/product-preset-tiles.png b/docs/verification/web-capture-322/product-preset-tiles.png new file mode 100644 index 00000000..f97a186c Binary files /dev/null and b/docs/verification/web-capture-322/product-preset-tiles.png differ diff --git a/docs/verification/web-capture-322/product-preset-zone-2.png b/docs/verification/web-capture-322/product-preset-zone-2.png new file mode 100644 index 00000000..b36021b5 Binary files /dev/null and b/docs/verification/web-capture-322/product-preset-zone-2.png differ diff --git a/docs/verification/web-capture-322/product-presets-dialog.png b/docs/verification/web-capture-322/product-presets-dialog.png new file mode 100644 index 00000000..6faa935d Binary files /dev/null and b/docs/verification/web-capture-322/product-presets-dialog.png differ diff --git a/docs/verification/web-capture-322/product-workspace-top.png b/docs/verification/web-capture-322/product-workspace-top.png new file mode 100644 index 00000000..664431e0 Binary files /dev/null and b/docs/verification/web-capture-322/product-workspace-top.png differ diff --git a/doctor.config.ts b/doctor.config.ts index 6d6eb937..3a8d7f2f 100644 --- a/doctor.config.ts +++ b/doctor.config.ts @@ -28,6 +28,13 @@ export default defineConfig({ "archive/**", "dist/**", "docs/no-use/**", + // docs/verification/** is committed e2e/release evidence (session + // dumps, staging bundles such as duplicated a8n-host.js, screenshot + // galleries). It is never shipped or bundled, and its large + // duplicated JS/HTML payloads push oxlint batches past the + // react-doctor lint time budget, which made the scan skip a + // nondeterministic subset of files (Issue #817). + "docs/verification/**", "scripts/check/**", "src/management/ae/cep/vendor/CSInterface.js", "supabase/functions/typlus/**", diff --git a/packages/ui/src/Icon.stories.tsx b/packages/ui/src/Icon.stories.tsx index 92ad1339..19e87bef 100644 --- a/packages/ui/src/Icon.stories.tsx +++ b/packages/ui/src/Icon.stories.tsx @@ -1,5 +1,6 @@ import type { Meta, StoryObj } from "@storybook/react"; import { Library, Save, Settings, X } from "lucide-react"; +import { assertIconAspect } from "@/storybook/quality/fit"; import { css } from "@/styled-system/css"; import { Icon } from "./Icon"; @@ -79,3 +80,15 @@ export const Size12: Story = { export const Size24: Story = { args: { size: 24 }, }; + +// Issue #726: the rendered icon box must keep its aspect ratio at real +// sizes — the regression class where flex sizing squashes the glyph. +// Lucide icons are square viewBoxes, so the box must be square. +export const KeepsAspectRatio: Story = { + args: { size: 20 }, + play: async ({ canvasElement }) => { + const svg = canvasElement.querySelector("svg"); + if (!svg) throw new Error("icon svg not found"); + assertIconAspect(svg); + }, +}; diff --git a/packages/ui/src/controls/Button.stories.tsx b/packages/ui/src/controls/Button.stories.tsx index bcc672be..b39bb5fe 100644 --- a/packages/ui/src/controls/Button.stories.tsx +++ b/packages/ui/src/controls/Button.stories.tsx @@ -1,5 +1,10 @@ import type { Meta, StoryObj } from "@storybook/react"; import { expect } from "storybook/test"; +import { + assertBorderToken, + borderTopColor, + resolveBorderToken, +} from "@/storybook/quality/border"; import { expectCanvasLayout } from "@/storybook/quality/layout"; import { css } from "@/styled-system/css"; @@ -56,6 +61,54 @@ export const Disabled: Story = { args: { disabled: true }, }; +/* + * Issue #763: a disabled `primary` button must not keep the accent fill — + * review captures showed the settings "Open GitHub issue" / "Open panel + * editor" CTAs reading as active steel-blue buttons. The resting fill + * must match the muted `surface.widget` tier every other disabled + * control uses, probed through the same Panda token (not a literal). + */ +export const DisabledPrimary: Story = { + args: { variant: "primary", disabled: true }, + render: (args) => ( +
+ + +
+ ), + play: async ({ canvasElement }) => { + const buttons = Array.from( + canvasElement.querySelectorAll("button"), + ); + const disabledBtn = buttons.find((b) => b.disabled); + const enabledBtn = buttons.find((b) => !b.disabled); + if (!disabledBtn || !enabledBtn) { + throw new Error("disabled/enabled primary buttons not found"); + } + const probe = document.createElement("div"); + probe.className = css({ backgroundColor: "surface.widget" }); + document.body.appendChild(probe); + try { + expect(getComputedStyle(disabledBtn).backgroundColor).toBe( + getComputedStyle(probe).backgroundColor, + ); + } finally { + probe.remove(); + } + // And it must differ from the enabled accent fill. + expect(getComputedStyle(disabledBtn).backgroundColor).not.toBe( + getComputedStyle(enabledBtn).backgroundColor, + ); + // Issue #798: the disabled primary must keep the disabled-control + // chrome — a hairline `border.subtle` frame like every other + // disabled variant — not render as chromeless text. + expect(getComputedStyle(disabledBtn).borderTopWidth).not.toBe("0px"); + expect(borderTopColor(disabledBtn)).toBe(resolveBorderToken("subtle")); + }, +}; + // Issue #146: hover-state capture — a real-pointer hover must lift the // button to `interactive.hover`; the post-play state is screenshotted. export const Hovered: Story = { @@ -121,6 +174,29 @@ export const AllVariants: Story = { ), + play: async ({ canvasElement }) => { + expectCanvasLayout(canvasElement); + // Issue #722: bordered non-primary variants rest on the + // non-assertive `border.subtle` tier — ghost included. + // Issue #761: `outline` is the exception — its whole purpose is a + // visible frame on a transparent surface, so it rests on + // `border.control` (the old `border.strong` #0e0e0e was darker than + // the dark canvas and rendered the frame invisible). + const byText = (label: string): HTMLButtonElement => { + const el = Array.from( + canvasElement.querySelectorAll("button"), + ).find((b) => b.textContent === label); + if (!el) throw new Error(`button "${label}" not found`); + return el; + }; + for (const label of ["Default", "Secondary", "Ghost", "Danger"]) { + const el = byText(label); + assertBorderToken(el, "subtle"); + expect(borderTopColor(el)).not.toBe(resolveBorderToken("control")); + } + const outline = byText("Outline"); + assertBorderToken(outline, "control"); + }, }; export const AllSizes: Story = { @@ -137,4 +213,20 @@ export const AllSizes: Story = { ), + // Issue #798: the size story must vary ONLY the size tier — a review + // capture read the large button as a different variant. Pin the + // shared variant chrome (fill + border) across all three. + play: async ({ canvasElement }) => { + const buttons = Array.from( + canvasElement.querySelectorAll("button"), + ); + expect(buttons).toHaveLength(3); + const [first, ...rest] = buttons; + for (const el of rest) { + expect(getComputedStyle(el).backgroundColor).toBe( + getComputedStyle(first).backgroundColor, + ); + expect(borderTopColor(el)).toBe(borderTopColor(first)); + } + }, }; diff --git a/packages/ui/src/controls/Button.tsx b/packages/ui/src/controls/Button.tsx index 5a9881b5..8e04ab8c 100644 --- a/packages/ui/src/controls/Button.tsx +++ b/packages/ui/src/controls/Button.tsx @@ -67,7 +67,7 @@ const base = css({ lineHeight: "tight", fontWeight: "medium", outline: "none", - transitionProperty: "colors", + transitionProperty: "color, background-color, border-color", _disabled: { opacity: 0.5, pointerEvents: "none", @@ -128,6 +128,23 @@ const variants: Record = { primary: css({ backgroundColor: "text.accent", color: "surface.panel", + // Issue #763: a disabled primary must drop the accent fill — at + // rest-opacity 0.5 it still read as an active CTA (settings + // feedback submit, background editor). It rests on the same muted + // surface as every other disabled control; the base `_disabled` + // dim still applies on top. + // Issue #798: it must also keep the disabled-control chrome — + // every other variant retains its hairline `border.subtle` frame + // when disabled, so a chromeless disabled primary read as a bare + // label next to its enabled sibling. The enabled primary stays + // chromeless; only the disabled state gains the frame. + _disabled: { + backgroundColor: "surface.widget", + color: "text.muted", + borderWidth: "hairline", + borderStyle: "solid", + borderColor: "border.subtle", + }, _hover: { opacity: 0.9 }, _active: { opacity: 0.85 }, _focusVisible: { @@ -153,7 +170,12 @@ const variants: Record = { color: "text.primary", borderWidth: "hairline", borderStyle: "solid", - borderColor: "border.strong", + // Issue #761: `border.strong` (#0e0e0e) is darker than the dark + // canvas, so the outline frame was effectively invisible. The + // outline variant IS the identifiable-control border, so it rests + // on `border.control` (text-derived α0.38) — visible on both + // light and dark surfaces. + borderColor: "border.control", _hover: { backgroundColor: "interactive.hover" }, _active: { backgroundColor: "interactive.active" }, _focusVisible: { @@ -164,7 +186,10 @@ const variants: Record = { ghost: css({ borderWidth: "hairline", borderStyle: "solid", - borderColor: "border.control", + // Issue #722: ghost rests on the same `border.subtle` tier as the + // default/secondary/danger variants; focus escalates to + // `interactive.focus` + the shared ring. + borderColor: "border.subtle", backgroundColor: "transparent", color: "text.muted", _hover: { diff --git a/packages/ui/src/controls/IconButton.stories.tsx b/packages/ui/src/controls/IconButton.stories.tsx index 8806dcf9..84288c5f 100644 --- a/packages/ui/src/controls/IconButton.stories.tsx +++ b/packages/ui/src/controls/IconButton.stories.tsx @@ -1,6 +1,7 @@ import type { Meta, StoryObj } from "@storybook/react"; import { Check, MoreHorizontal, Plus } from "lucide-react"; import { expect } from "storybook/test"; +import { expectCanvasLayout } from "@/storybook/quality/layout"; import { css } from "@/styled-system/css"; import { IconButton } from "./IconButton"; @@ -85,6 +86,17 @@ export const VariantsAndSizes: Story = { ), + // Issue #798: the story name promises a size range — pin that the + // rendered control heights actually differ (sm/md/lg tiers), so a + // capture cannot silently collapse back to one size. + play: async ({ canvasElement }) => { + const heights = new Set( + Array.from(canvasElement.querySelectorAll("button")).map( + (el) => el.getBoundingClientRect().height, + ), + ); + expect(heights.size).toBeGreaterThanOrEqual(3); + }, }; export const Active: Story = { @@ -124,6 +136,37 @@ export const Active: Story = { }, }; +// Issue #166: hover-state capture — a real-pointer hover must lift the +// ghost variant to `interactive.hover` (and brighten the glyph); the +// post-play state is what the capture pipeline screenshots. +export const Hovered: Story = { + play: async ({ canvasElement }) => { + expectCanvasLayout(canvasElement); + const button = canvasElement.querySelector("button"); + if (!button) throw new Error("button not found"); + const { userEvent } = await import("vitest/browser"); + const resting = getComputedStyle(button).backgroundColor; + await userEvent.hover(button); + await expect(button.matches(":hover")).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 300)); + await expect(getComputedStyle(button).backgroundColor).not.toBe(resting); + expectCanvasLayout(canvasElement); + }, +}; + +// Issue #166: keyboard focus must reach the button and paint the shared +// focus ring (`--color-focus-ring` box-shadow under `:focus-visible`). +export const Focused: Story = { + play: async ({ canvasElement }) => { + const button = canvasElement.querySelector("button"); + if (!button) throw new Error("button not found"); + button.focus(); + await expect(document.activeElement).toBe(button); + await expect(button.matches(":focus")).toBe(true); + expectCanvasLayout(canvasElement); + }, +}; + export const AllSizes: Story = { render: (args) => (
diff --git a/packages/ui/src/controls/SegmentedControl.stories.tsx b/packages/ui/src/controls/SegmentedControl.stories.tsx index fb40e320..b313db10 100644 --- a/packages/ui/src/controls/SegmentedControl.stories.tsx +++ b/packages/ui/src/controls/SegmentedControl.stories.tsx @@ -1,6 +1,12 @@ import type { Meta, StoryObj } from "@storybook/react"; import { useState } from "react"; import { expect } from "storybook/test"; +import { + assertBorderToken, + borderTopColor, + resolveBorderToken, +} from "@/storybook/quality/border"; +import { assertSingleRow } from "@/storybook/quality/fit"; import { expectCanvasLayout } from "@/storybook/quality/layout"; import { css } from "@/styled-system/css"; @@ -109,6 +115,14 @@ export const HoveredSegment: Story = { render: (args) => , play: async ({ canvasElement }) => { expectCanvasLayout(canvasElement); + // Issue #722: the strip is passive chrome — its resting border must + // sit on the non-assertive `border.subtle` tier, not `border.control`. + const strip = canvasElement.querySelector('[role="toolbar"]'); + if (!strip) throw new Error("segmented strip not found"); + // Issue #722/#726: passive chrome rests on `border.subtle`, never + // `border.control`. + assertBorderToken(strip, "subtle"); + expect(borderTopColor(strip)).not.toBe(resolveBorderToken("control")); const buttons = Array.from( canvasElement.querySelectorAll("button"), ); @@ -133,6 +147,96 @@ export const HoveredSegment: Story = { }, }; +// Issue #723: the strip must stay on a single row at every width. When +// full labels no longer fit, options with `compactLabel` swap to their +// short form; the accessible name remains the full label. +const adaptiveOptions = [ + { value: "curve", label: "Comfortable curve", compactLabel: "Cv" }, + { value: "bounce", label: "Springy bounce", compactLabel: "Bo" }, + { value: "elastic", label: "Wobbly elastic", compactLabel: "El" }, +]; + +const settleLabels = () => new Promise((resolve) => setTimeout(resolve, 80)); + +export const AdaptiveLabels: Story = { + args: { + options: adaptiveOptions, + "aria-label": "Easing mode", + }, + render: (args) => ( +
+
+ +
+
+ +
+
+ ), + play: async ({ canvasElement }) => { + expectCanvasLayout(canvasElement); + await settleLabels(); + const toolbars = Array.from( + canvasElement.querySelectorAll('[role="toolbar"]'), + ); + expect(toolbars).toHaveLength(2); + const [wide, narrow] = toolbars; + if (!wide || !narrow) throw new Error("expected two strips"); + + // Wide strip keeps the full labels; narrow strip switches to the + // compact forms — the label *content* adapts, it is not truncated. + expect(wide.textContent).toContain("Comfortable curve"); + expect(narrow.textContent).toContain("Cv"); + expect(narrow.textContent).not.toContain("Comfortable curve"); + + // Both strips stay on a single row (Issue #726 shared contract) and + // nothing is clipped inside a segment. + for (const toolbar of toolbars) { + assertSingleRow(toolbar, { itemSelector: "button" }); + for (const button of toolbar.querySelectorAll("button")) { + expect(button.scrollWidth).toBeLessThanOrEqual(button.clientWidth + 1); + } + } + expectCanvasLayout(canvasElement); + }, +}; + +// Issue #723: when even compact labels cannot fit — or none are provided — +// the strip scrolls horizontally instead of wrapping to a second row. +export const OverflowScrollsHorizontally: Story = { + args: { + options: Array.from({ length: 11 }, (_, index) => ({ + value: `source-${index}`, + label: `Source filter number ${index}`, + })), + "aria-label": "Filter by source", + }, + render: (args) => ( +
+ +
+ ), + play: async ({ canvasElement }) => { + expectCanvasLayout(canvasElement); + await settleLabels(); + const toolbar = + canvasElement.querySelector('[role="toolbar"]'); + if (!toolbar) throw new Error("strip not found"); + expect(toolbar.querySelectorAll("button")).toHaveLength(11); + // Single row, and the excess width is reachable by scrolling — + // no segment is dropped to a second line or clipped. + assertSingleRow(toolbar, { itemSelector: "button" }); + expect(getComputedStyle(toolbar).overflowX).toBe("auto"); + expect(toolbar.scrollWidth).toBeGreaterThan(toolbar.clientWidth); + // Issue #764: horizontal overflow is only acceptable with a + // rest-state scroll affordance — the global chrome hides scrollbar + // thumbs until hover, so the strip keeps its thumb visible. + const thumb = getComputedStyle(toolbar, "::-webkit-scrollbar-thumb"); + expect(thumb.visibility).toBe("visible"); + expectCanvasLayout(canvasElement); + }, +}; + // Issue #166: clicking a segment selects it — `aria-pressed` flips and the // selected surface replaces the unselected one. export const SelectedOnClick: Story = { diff --git a/packages/ui/src/controls/SegmentedControl.test.tsx b/packages/ui/src/controls/SegmentedControl.test.tsx new file mode 100644 index 00000000..788018c9 --- /dev/null +++ b/packages/ui/src/controls/SegmentedControl.test.tsx @@ -0,0 +1,186 @@ +/** + * SegmentedControl contract (issue #723): + * + * - The strip never wraps — `flex-wrap: nowrap` plus `overflow-x: auto` + * is enforced by the shared `segmentedStripClass` styles. + * - When every option provides a `compactLabel`, the control measures the + * strip with off-screen twin strips and swaps to the compact content + * once the full labels no longer fit on one row; it swaps back when + * the container grows again. + * - Measurement twins are ``s inside an `aria-hidden` clip host, so + * they never show up as buttons to role queries or `querySelectorAll`. + * + * @vitest-environment jsdom + */ + +import { act, cleanup, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { SegmentedControl } from "./SegmentedControl"; + +const LONG_OPTIONS = [ + { value: "curve", label: "Comfortable curve", compactLabel: "Cv" }, + { value: "bounce", label: "Springy bounce", compactLabel: "Bo" }, + { value: "elastic", label: "Wobbly elastic", compactLabel: "El" }, +]; + +class ResizeObserverStub { + static instances: ResizeObserverStub[] = []; + callback: ResizeObserverCallback; + observed: Element[] = []; + + constructor(callback: ResizeObserverCallback) { + this.callback = callback; + ResizeObserverStub.instances.push(this); + } + + observe(target: Element): void { + this.observed.push(target); + } + unobserve(): void {} + disconnect(): void {} +} + +const setClientWidth = (el: Element, width: number): void => { + Object.defineProperty(el, "clientWidth", { + value: width, + configurable: true, + }); +}; + +/** Fire the captured ResizeObserver callback inside `act`. */ +const notifyResize = (): void => { + const observer = ResizeObserverStub.instances.at(-1); + if (!observer) throw new Error("ResizeObserver was not created"); + act(() => { + observer.callback( + observer.observed.map( + (target) => + ({ + target, + contentRect: target.getBoundingClientRect(), + }) as ResizeObserverEntry, + ), + observer as unknown as ResizeObserver, + ); + }); +}; + +const stripOf = (container: HTMLElement): HTMLElement => + container.querySelector('[role="toolbar"]')!; + +const measureStripsOf = (container: HTMLElement): HTMLElement[] => + Array.from( + container.querySelectorAll('[aria-hidden="true"] > div'), + ); + +beforeEach(() => { + ResizeObserverStub.instances = []; + vi.stubGlobal("ResizeObserver", ResizeObserverStub); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe("SegmentedControl", () => { + it("renders one button per option and reports changes", () => { + const onChange = vi.fn(); + render( + , + ); + expect(screen.getAllByRole("button")).toHaveLength(2); + screen.getByRole("button", { name: "Beta" }).click(); + expect(onChange).toHaveBeenCalledWith("b"); + }); + + it("does not render measurement twins without compact labels", () => { + const { container } = render( + undefined} + />, + ); + // No off-screen measurement strips and no extra span "buttons". + expect(container.querySelectorAll("span")).toHaveLength(0); + expect(measureStripsOf(container)).toHaveLength(0); + }); + + it("switches to compact labels when full labels overflow, and back", () => { + const { container } = render( + undefined} + />, + ); + const strip = stripOf(container); + const [fullMeasure, compactMeasure] = measureStripsOf(container); + expect(fullMeasure).toBeDefined(); + expect(compactMeasure).toBeDefined(); + + // Narrow container: full labels need 300px, compact need 90px, + // only 120px are available -> compact mode. + setClientWidth(strip, 120); + setClientWidth(fullMeasure, 300); + setClientWidth(compactMeasure, 90); + notifyResize(); + + const buttons = screen.getAllByRole("button"); + expect(buttons.map((b) => b.textContent)).toEqual(["Cv", "Bo", "El"]); + // The accessible name stays the full label. + expect( + screen.getByRole("button", { name: "Comfortable curve" }), + ).toBeTruthy(); + // Full label is exposed as the hover title while compact. + expect( + screen + .getByRole("button", { name: "Comfortable curve" }) + .getAttribute("title"), + ).toBe("Comfortable curve"); + + // Container grows: full labels fit again -> full labels return. + setClientWidth(strip, 320); + notifyResize(); + expect(screen.getAllByRole("button").map((b) => b.textContent)).toEqual([ + "Comfortable curve", + "Springy bounce", + "Wobbly elastic", + ]); + }); + + it("keeps full labels when compact labels would be wider", () => { + const { container } = render( + undefined} + />, + ); + const strip = stripOf(container); + const [fullMeasure, compactMeasure] = measureStripsOf(container); + setClientWidth(strip, 30); + setClientWidth(fullMeasure, 40); + setClientWidth(compactMeasure, 200); + notifyResize(); + expect(screen.getByRole("button").textContent).toBe("Ab"); + }); +}); diff --git a/packages/ui/src/controls/SegmentedControl.tsx b/packages/ui/src/controls/SegmentedControl.tsx index 80def802..60dd4fa0 100644 --- a/packages/ui/src/controls/SegmentedControl.tsx +++ b/packages/ui/src/controls/SegmentedControl.tsx @@ -2,12 +2,25 @@ import { segmentedButtonActiveClass, segmentedButtonClass, segmentedButtonInactiveClass, + segmentedMeasureHostClass, + segmentedMeasureStripClass, segmentedStripClass, } from "@ty-plus/ui/styles/segmented"; import { cx } from "@ty-plus/ui/util/cx"; import type { ReactElement } from "react"; +import { useEffect, useRef, useState } from "react"; -type SegmentedOption = { value: string; label: string; disabled?: boolean }; +type SegmentedOption = { + value: string; + label: string; + /** + * Shorter stand-in for `label`, rendered when the strip is too narrow + * for every full label on a single row. The full label always remains + * the accessible name and the hover title. + */ + compactLabel?: string; + disabled?: boolean; +}; export type SegmentedControlProps = { options: SegmentedOption[]; @@ -21,6 +34,11 @@ export type SegmentedControlProps = { "aria-label"?: string; }; +const compactLabelOf = (opt: SegmentedOption): string | undefined => + typeof opt.compactLabel === "string" && opt.compactLabel !== "" + ? opt.compactLabel + : undefined; + export function SegmentedControl(props: SegmentedControlProps): ReactElement { const { options, @@ -32,33 +50,113 @@ export function SegmentedControl(props: SegmentedControlProps): ReactElement { unselectedClassName, "aria-label": ariaLabel, } = props; + + const hasCompactLabels = options.some( + (opt) => compactLabelOf(opt) !== undefined, + ); + const [compact, setCompact] = useState(false); + const stripRef = useRef(null); + const fullMeasureRef = useRef(null); + const compactMeasureRef = useRef(null); + + // The observer watches the strip and both measurement twins, so label, + // option, or class changes re-measure through their size changes — no + // dependency on the (inline-rebuilt) `options` array is needed. The + // strip's width comes from its parent (`width: full`), never from the + // rendered labels, so the decision cannot feed back into itself. + useEffect(() => { + if (!hasCompactLabels) { + setCompact(false); + return; + } + const strip = stripRef.current; + const fullMeasure = fullMeasureRef.current; + const compactMeasure = compactMeasureRef.current; + if (!strip || !fullMeasure) return; + const update = () => { + // `clientWidth` is the padding box on both the strip and the + // measurement twins, so the comparison needs no border + // correction. 1px slack absorbs sub-pixel rounding. Compact + // mode is only useful when it is actually narrower. + const available = strip.clientWidth; + const fullWidth = fullMeasure.clientWidth; + const compactWidth = compactMeasure?.clientWidth ?? fullWidth; + setCompact(fullWidth > available + 1 && compactWidth <= fullWidth); + }; + update(); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(update); + observer.observe(strip); + observer.observe(fullMeasure); + if (compactMeasure) observer.observe(compactMeasure); + return () => observer.disconnect(); + }, [hasCompactLabels]); + + const segmentClass = (opt: SegmentedOption): string => + cx( + segmentedButtonClass, + opt.value === value + ? (selectedClassName ?? segmentedButtonActiveClass) + : (unselectedClassName ?? segmentedButtonInactiveClass), + buttonClassName, + ); + + const visibleLabel = (opt: SegmentedOption): string => { + const short = compactLabelOf(opt); + return compact && short !== undefined ? short : opt.label; + }; + return ( -
- {options.map((opt) => { - const selected = opt.value === value; - return ( - + ); + })} +
+ {hasCompactLabels ? ( + +
+ ) : null} + ); } diff --git a/packages/ui/src/controls/ViewModeToggle.stories.tsx b/packages/ui/src/controls/ViewModeToggle.stories.tsx index 0b96f8bf..ddf1ea06 100644 --- a/packages/ui/src/controls/ViewModeToggle.stories.tsx +++ b/packages/ui/src/controls/ViewModeToggle.stories.tsx @@ -1,5 +1,6 @@ import type { Meta, StoryObj } from "@storybook/react"; import { expect } from "storybook/test"; +import { borderTopColor, resolveBorderToken } from "@/storybook/quality/border"; import { assertContrast } from "@/storybook/quality/color"; import { expectCanvasLayout } from "@/storybook/quality/layout"; import { css } from "@/styled-system/css"; @@ -16,6 +17,67 @@ const baseArgs: Args = { const decoratorBoxClass = css({ padding: "2" }); +/* + * Issue #798: the toggle's whole purpose is switching the content below + * it, but the bare stories rendered only the control — the icon-view and + * list-view captures were pixel-near-identical and read as an empty + * canvas. Each story now shows a small mock panel in the mode it names + * so the capture demonstrates the state it claims. + */ +const storyRowClass = css({ + display: "flex", + gap: "3", + alignItems: "flex-start", +}); +const mockPanelClass = css({ + width: "56", + flexShrink: 0, + borderRadius: "shell-sm", + borderWidth: "hairline", + borderStyle: "solid", + borderColor: "border.subtle", + backgroundColor: "surface.panel", + padding: "2", +}); +const mockGridClass = css({ + display: "grid", + gridTemplateColumns: "repeat(3, 1fr)", + gap: "1.5", +}); +const mockTileClass = css({ + aspectRatio: "1 / 1", + borderRadius: "shell-sm", + borderWidth: "hairline", + borderStyle: "solid", + borderColor: "border.subtle", + backgroundColor: "surface.widget", +}); +const mockListClass = css({ + display: "flex", + flexDirection: "column", + gap: "1.5", +}); +const mockRowClass = css({ + display: "flex", + alignItems: "center", + gap: "1.5", +}); +const mockGlyphClass = css({ + width: "4", + height: "4", + flexShrink: 0, + borderRadius: "shell-sm", + backgroundColor: "surface.widget", + borderWidth: "hairline", + borderStyle: "solid", + borderColor: "border.subtle", +}); +const mockLineClass = css({ + height: "1.5", + borderRadius: "full", + backgroundColor: "border.subtle", +}); + const meta = { title: "Shared/Controls/ViewModeToggle", args: baseArgs, @@ -33,11 +95,42 @@ const meta = { ), ], render: (args: Args) => ( - undefined} - onEnterIconView={() => undefined} - /> +
+ undefined} + onEnterIconView={() => undefined} + /> +