@openfairygui/backend 0.4.0 → 0.5.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/docs.cjs +4776 -845
- package/dist/docs.d.cts +14 -1
- package/dist/docs.d.mts +14 -1
- package/dist/docs.mjs +4776 -845
- package/dist/index.cjs +137 -10
- package/dist/index.d.cts +100 -5
- package/dist/index.d.mts +100 -5
- package/dist/index.mjs +137 -11
- package/dist/node.cjs +135 -9
- package/dist/node.d.cts +67 -4
- package/dist/node.d.mts +67 -4
- package/dist/node.mjs +135 -9
- package/docs/workflow.md +10 -0
- package/package.json +3 -3
- package/src/contracts.ts +1 -1
- package/src/diagnostics.ts +8 -0
- package/src/generated/contracts.ts +8588 -1733
- package/src/generated/docs.ts +3 -3
- package/src/index.ts +10 -0
- package/src/runtime/capabilities.ts +5 -1
- package/src/runtime/contracts.ts +54 -0
- package/src/runtime.ts +14 -0
- package/src/services/read-service.ts +80 -8
package/src/generated/docs.ts
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
export const INSTALLED_DOCS = {
|
|
3
3
|
"version": {
|
|
4
4
|
"packageName": "@openfairygui/backend",
|
|
5
|
-
"packageVersion": "0.
|
|
5
|
+
"packageVersion": "0.5.0-alpha.2",
|
|
6
6
|
"nodeEngine": ">=22",
|
|
7
|
-
"documentationDigest": "
|
|
7
|
+
"documentationDigest": "c0a367162dbfa3cf5e481e9cf30f44dfe4106d162cae182c3f649ef882d643fc"
|
|
8
8
|
},
|
|
9
|
-
"workflow": "# Installed OpenFairyGUI workflow\n\nThis is a minimal offline companion, not the full website. Read `ofgui docs ls --json` for the installed package version, contract version, capability schema version and digest. Use the project's installed `ofgui`/`ofgui-mcp`, not a global executable or an online latest-version lookup. A mismatched installation must be reconciled by the host before editing.\n\n## Discover the current contract\n\n- `ofgui docs find \"selector\" --json` searches this installed corpus.\n- `ofgui docs cat contracts --json` lists Core operations and Backend/MCP mappings.\n- `ofgui docs schema setDisplayNodeProps --json` reads one self-contained operation schema.\n- `ofgui docs schema cli/validate --json` reads the installed CLI output schema; `cli/docs cat` is a valid exact document ID for the nested command.\n- `ofgui docs cat methods/queryEntity --json` reads precise input/output wire schemas.\n- `ofgui docs diagnostic stale_write --json` reads recovery guidance.\n- MCP `resources/read` at `openfairygui://docs/index` provides the same index and content URIs. MCP is local stdio, not an assumed HTTP port.\n\nThe generated schemas describe JSON wire structure and input budgets, not semantic validity. Native SDK byte fields remain Uint8Array; MCP transports declared byte fields as integer arrays. Arbitrary extension data is not converted. Host objects/functions are omitted from MCP wire schemas; use SDK declarations for host injection, not guessed JSON fields.\n\nAll CLI JSON uses `{schemaVersion:1,command,success:true,result}` or `{schemaVersion:1,command,success:false,error:{code,message},result?}`. Documentation version/index/body fields are inside `result`; read `result.text` for document content. Invalid/incomplete validate and doctor responses retain their full report under `result`. Help/version are text; other JSON-mode stdout contains exactly one document and human logs use stderr. Exit codes: 0 success, 1 workflow failure, 2 arguments, 3 incomplete validation. CLI owns envelopes, not new workflow semantics.\n\n## Edit safely\n\n1. Read capabilities. Existing projects use openSession (with host authorization and a lifetime lock); openProjectSession accepts a host-supplied authoritative UAM, not a shortcut around lossy file-session guards.\n2. Read getProjectOutline to discover exact identities, then queryEntity for the relevant current properties and actual revision. Capabilities list the supported read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:\"project\"} without a selector; package queries use {kind:\"package\",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection.\n3. Read the operation and method schemas. Plan the smallest authorized batch using current identifiers and expectedRevision.\n4. preflightTransaction executes on an isolated snapshot and discards it. Inspect projectedRevision, impact.entities (exact identities and changed fields, including reference normalization), impact.files (ProjectWriter model diff, not a disk write plan) and persistence.nextAction. The diff starts at the current revision, not the last save. It contains no source bytes. Summary overflow or serialization failure returns transaction_preview_failed without a partial result. No revision is reserved; writeVerified is always false. It does not save files or guarantee later apply/save/publish.\n5. Only when authorized, applyTransaction with the planned batch and expectedRevision. On stale_write, refresh and replan; never blindly substitute a newer revision.\n6. validateSession checks the new authoritative state. A successful response can contain an invalid or incomplete validation report; require status valid and complete true before treating validation as passed.\n7. When authorized, saveSession checks revision independently and writes the original project only. Keep path policy, UAM fidelity and rollback guards. Close the session only after handling unsaved changes. Read saved output again when disk round-trip is part of acceptance.\n\nupdateProjectSettings and updatePackageSettings replace complete settings snapshots. Copy the corresponding query's entity.properties.settings, change only requested fields, retain other nested settings and optional fields, and submit the complete settings with the queried revision. Package updates also require the original packageId selector. Settings queries share the same response budgets as other entity kinds.\n\nupdateController and updateTransition replace complete snapshots, not partial patches. Copy the queried entity.properties, change only the requested fields, preserve page IDs/remarks/actions, item order/targets, settings and references, and submit the original selector with the queried revision. A stale_write requires refreshing and replanning the full snapshot for all these replacement operations. Querying does not validate references or grant permission to edit them.\n\n## Diagnose without repair\n\n`ofgui doctor --json` checks installed CLI/documentation versions, the Node Backend capability snapshot, in-memory Sharp PNG/JPEG encoding and pixel decoding, and temporary-directory access flags. `ofgui doctor <project-directory-or-fairy-file> --json` additionally runs existing Node project validation, including source reads and available image decoding. Optional `--output-dir <directory>` checks an explicit destination or its nearest existing ancestor, without creating it. Directory checks return the absolute requested `path`, link-resolved `inspectedPath` and `exists` (null when unknown); files, dangling links and access errors fail. The temporary directory must exist. It opens no Backend session, creates no lock, installs nothing, writes no probe files and changes no configuration.\n\nExit 0 means the requested checks completed; exit 1 means a detected error; exit 2 means invalid arguments; exit 3 means native image capability is unavailable/failed or project validation is incomplete. Inspect result.checks, result.errors and result.project. Without a project, its source bytes are not checked. Access flags do not prove effective ACL permissions, available space, later writes/rename/rollback or continued access. The capability manifest remains a declaration; a successful doctor does not prove publish/restore or runtime rendering. Plugins and configured output destinations are not executed or checked automatically; only explicit --output-dir is inspected. This product doctor does not inspect Git, pnpm, repository builds or fixture submodules; maintainers use pnpm repo:doctor for those.\n\nRead diagnostic guides for ownership and recovery boundaries. Every formal Core/Backend diagnostic code is covered; shared codes list all `owners`, while response `owner` identifies the actual source. Missing bytes/decoders, rejected paths and expired sessions require host action; do not invent repair/hydration tools, widen roots, discard unsaved work, or turn incomplete validation into success. Invalid/unsupported operations require schema-based replanning, live locks cannot be removed, and write failures require preserving dirty state and inspecting actual files.\n\n## Publish and recover trusted local artifacts\n\nPublishing and restoration are external Node-hosted workflows, not Backend session methods or general MCP editing tools. The host must authorize input and output directories independently. They require the native image capability; do not rename binary extensions to imitate a different target profile.\n\n- `ofgui publish <project> --output <release-directory> --project-type layabox --json` publishes the current saved project. `--output` overrides runtime artifact destinations; configured code generation still uses its own destinations and project plugins run as trusted local code.\n- The JSON document is `{schemaVersion:1,command:\"publish\",success:true,result:{files:[{path,size}]}}`. Paths are final absolute paths and sizes are bytes. The Node SDK `publishNode()` returns the same `result`. The manifest records actual successful filesystem/atlas writes, including code written through the supplied publish filesystem; it excludes pre-existing untouched files, deletions and arbitrary plugin I/O outside that filesystem. It is not an inventory of everything in the output directory. Explicit runtime output is staged and rolled back on failure; separately configured code outputs and arbitrary plugin effects are not covered by that directory transaction.\n- `ofgui restore <trusted-release-directory> --output <separate-project-directory> --project-type layabox --json` returns `{schemaVersion:1,command:\"restore\",success:true,result:{projectPath,packages:[{id,name}],warnings:[]}}`. Warnings are not a validation pass. Reread the returned projectPath and run `ofgui validate <projectPath> --json`; require valid and complete validation.\n- Both artifact commands exit 0 on workflow success, 1 on workflow failure, and 2 on command syntax errors. Errors are `{schemaVersion:1,command,success:false,error:{code,message}}`, with `publish_failed`, `restore_failed` or `invalid_arguments`. In JSON mode stdout contains only this document; human/plugin output goes to stderr. Help remains human-readable. Errors do not include a claimed successful file manifest.\n- Restore requires a separate directory, not a `.fairy` file. Do not force overwrite by default. `--force` replaces an existing nonempty target only after complete staged recovery; parse/image failures retain the previous target. Only trusted local artifacts are supported, not arbitrary third-party imports.\n- Read `ofgui docs cat restore-limits --json` or MCP resource `openfairygui://docs/restore-limits` for the installed version's full recovery boundary. Accept readable, structurally valid supported semantics and decoded assets, not original project IDs, workspace state, unpublished resources, original filenames/extensions, controller editor selection/export flags, float32 text precision or byte-identical XML.\n",
|
|
9
|
+
"workflow": "# Installed OpenFairyGUI workflow\n\nThis is a minimal offline companion, not the full website. Read `ofgui docs ls --json` for the installed package version, contract version, capability schema version and digest. Use the project's installed `ofgui`/`ofgui-mcp`, not a global executable or an online latest-version lookup. A mismatched installation must be reconciled by the host before editing.\n\n## Discover the current contract\n\n- `ofgui docs find \"selector\" --json` searches this installed corpus.\n- `ofgui docs cat contracts --json` lists Core operations and Backend/MCP mappings.\n- `ofgui docs schema setDisplayNodeProps --json` reads one self-contained operation schema.\n- `ofgui docs schema cli/validate --json` reads the installed CLI output schema; `cli/docs cat` is a valid exact document ID for the nested command.\n- `ofgui docs cat methods/queryEntity --json` reads precise input/output wire schemas.\n- `ofgui docs diagnostic stale_write --json` reads recovery guidance.\n- MCP `resources/read` at `openfairygui://docs/index` provides the same index and content URIs. MCP is local stdio, not an assumed HTTP port.\n\nThe generated schemas describe JSON wire structure and input budgets, not semantic validity. Native SDK byte fields remain Uint8Array; MCP transports declared byte fields as integer arrays. Arbitrary extension data is not converted. Host objects/functions are omitted from MCP wire schemas; use SDK declarations for host injection, not guessed JSON fields.\n\nAll CLI JSON uses `{schemaVersion:1,command,success:true,result}` or `{schemaVersion:1,command,success:false,error:{code,message},result?}`. Documentation version/index/body fields are inside `result`; read `result.text` for document content. Invalid/incomplete validate and doctor responses retain their full report under `result`. Help/version are text; other JSON-mode stdout contains exactly one document and human logs use stderr. Exit codes: 0 success, 1 workflow failure, 2 arguments, 3 incomplete validation. CLI owns envelopes, not new workflow semantics.\n\n## Edit safely\n\n1. Read capabilities. Existing projects use openSession (with host authorization and a lifetime lock); openProjectSession accepts a host-supplied authoritative UAM, not a shortcut around lossy file-session guards.\n2. Read getProjectOutline to discover exact identities, then queryEntity for the relevant current properties and actual revision. Capabilities list the supported read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:\"project\"} without a selector; package queries use {kind:\"package\",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection.\n3. Read the operation and method schemas. Plan the smallest authorized batch using current identifiers and expectedRevision.\n4. preflightTransaction executes on an isolated snapshot and discards it. Inspect projectedRevision, impact.entities (exact identities and changed fields, including reference normalization), impact.files (ProjectWriter model diff, not a disk write plan) and persistence.nextAction. The diff starts at the current revision, not the last save. It contains no source bytes. Summary overflow or serialization failure returns transaction_preview_failed without a partial result. No revision is reserved; writeVerified is always false. It does not save files or guarantee later apply/save/publish.\n5. Only when authorized, applyTransaction with the planned batch and expectedRevision. On stale_write, refresh and replan; never blindly substitute a newer revision.\n6. validateSession checks the new authoritative state. A successful response can contain an invalid or incomplete validation report; require status valid and complete true before treating validation as passed.\n7. When authorized, saveSession checks revision independently and writes the original project only. Keep path policy, UAM fidelity and rollback guards. Close the session only after handling unsaved changes. Read saved output again when disk round-trip is part of acceptance.\n\nupdateProjectSettings and updatePackageSettings replace complete settings snapshots. Copy the corresponding query's entity.properties.settings, change only requested fields, retain other nested settings and optional fields, and submit the complete settings with the queried revision. Package updates also require the original packageId selector. Settings queries share the same response budgets as other entity kinds.\n\nupdateController and updateTransition replace complete snapshots, not partial patches. Copy the queried entity.properties, change only the requested fields, preserve page IDs/remarks/actions, item order/targets, settings and references, and submit the original selector with the queried revision. A stale_write requires refreshing and replanning the full snapshot for all these replacement operations. Querying does not validate references or grant permission to edit them.\n\n## Consume the committed session state\n\nFor complete public UAM consumption, use readSessionState({sessionId, expectedRevision?}); use queryEntity for targeted properties. The detached model excludes only asset resources' primary sourceBytes, retaining sourcePath and JSON extensions. It includes revision, dirty, lastSavedRevision, readComplete, readDiagnostics and uamFidelity. Only this read-model output schema accepts unnamed object fields; transaction input contracts remain unchanged.\n\nRead each asset with readResourceBytes({sessionId, expectedRevision: state.revision, selector:{packageId,resourceId}}). Bytes are detached Uint8Array values in the SDK and integer arrays in MCP, limited to the primary file already held in memory. There is no disk hydration or auxiliary-file discovery. Components are unsupported; unavailable bytes produce session_read_failed with reason bytes_unavailable.\n\nOn stale_read, discard the incomplete model/bytes collection and restart from readSessionState. Reads do not wait for uncommitted transactions, retain historical versions, or reserve revisions. Saving can update sourcePath and dirty without increasing the edit revision; the same revision does not identify permanently identical complete UAM. Completeness/fidelity flags preserve existing meaning and do not guarantee bytes, rendering or saving. Preserve failed reads as failures; never save or repair merely to obtain a read.\n\nCapabilities advertise a 4 MiB compact JSON data limit (depth 64, 500000 nodes) for the model and 1 MiB per primary resource. Both new MCP tools additionally limit the complete JSON CallToolResult, including compact text and structuredContent, to 16 MiB; excess returns mcp_response_budget_exceeded. Native model/buffer overflow returns session_read_failed with reason response_budget_exceeded, without truncation. Read the installed methods/readSessionState and methods/readResourceBytes schemas for precise inputs, results and errors.\n\n## Diagnose without repair\n\n`ofgui doctor --json` checks installed CLI/documentation versions, the Node Backend capability snapshot, in-memory Sharp PNG/JPEG encoding and pixel decoding, and temporary-directory access flags. `ofgui doctor <project-directory-or-fairy-file> --json` additionally runs existing Node project validation, including source reads and available image decoding. Optional `--output-dir <directory>` checks an explicit destination or its nearest existing ancestor, without creating it. Directory checks return the absolute requested `path`, link-resolved `inspectedPath` and `exists` (null when unknown); files, dangling links and access errors fail. The temporary directory must exist. It opens no Backend session, creates no lock, installs nothing, writes no probe files and changes no configuration.\n\nExit 0 means the requested checks completed; exit 1 means a detected error; exit 2 means invalid arguments; exit 3 means native image capability is unavailable/failed or project validation is incomplete. Inspect result.checks, result.errors and result.project. Without a project, its source bytes are not checked. Access flags do not prove effective ACL permissions, available space, later writes/rename/rollback or continued access. The capability manifest remains a declaration; a successful doctor does not prove publish/restore or runtime rendering. Plugins and configured output destinations are not executed or checked automatically; only explicit --output-dir is inspected. This product doctor does not inspect Git, pnpm, repository builds or fixture submodules; maintainers use pnpm repo:doctor for those.\n\nRead diagnostic guides for ownership and recovery boundaries. Every formal Core/Backend diagnostic code is covered; shared codes list all `owners`, while response `owner` identifies the actual source. Missing bytes/decoders, rejected paths and expired sessions require host action; do not invent repair/hydration tools, widen roots, discard unsaved work, or turn incomplete validation into success. Invalid/unsupported operations require schema-based replanning, live locks cannot be removed, and write failures require preserving dirty state and inspecting actual files.\n\n## Publish and recover trusted local artifacts\n\nPublishing and restoration are external Node-hosted workflows, not Backend session methods or general MCP editing tools. The host must authorize input and output directories independently. They require the native image capability; do not rename binary extensions to imitate a different target profile.\n\n- `ofgui publish <project> --output <release-directory> --project-type layabox --json` publishes the current saved project. `--output` overrides runtime artifact destinations; configured code generation still uses its own destinations and project plugins run as trusted local code.\n- The JSON document is `{schemaVersion:1,command:\"publish\",success:true,result:{files:[{path,size}]}}`. Paths are final absolute paths and sizes are bytes. The Node SDK `publishNode()` returns the same `result`. The manifest records actual successful filesystem/atlas writes, including code written through the supplied publish filesystem; it excludes pre-existing untouched files, deletions and arbitrary plugin I/O outside that filesystem. It is not an inventory of everything in the output directory. Explicit runtime output is staged and rolled back on failure; separately configured code outputs and arbitrary plugin effects are not covered by that directory transaction.\n- `ofgui restore <trusted-release-directory> --output <separate-project-directory> --project-type layabox --json` returns `{schemaVersion:1,command:\"restore\",success:true,result:{projectPath,packages:[{id,name}],warnings:[]}}`. Warnings are not a validation pass. Reread the returned projectPath and run `ofgui validate <projectPath> --json`; require valid and complete validation.\n- Both artifact commands exit 0 on workflow success, 1 on workflow failure, and 2 on command syntax errors. Errors are `{schemaVersion:1,command,success:false,error:{code,message}}`, with `publish_failed`, `restore_failed` or `invalid_arguments`. In JSON mode stdout contains only this document; human/plugin output goes to stderr. Help remains human-readable. Errors do not include a claimed successful file manifest.\n- Restore requires a separate directory, not a `.fairy` file. Do not force overwrite by default. `--force` replaces an existing nonempty target only after complete staged recovery; parse/image failures retain the previous target. Only trusted local artifacts are supported, not arbitrary third-party imports.\n- Read `ofgui docs cat restore-limits --json` or MCP resource `openfairygui://docs/restore-limits` for the installed version's full recovery boundary. Accept readable, structurally valid supported semantics and decoded assets, not original project IDs, workspace state, unpublished resources, original filenames/extensions, controller editor selection/export flags, float32 text precision or byte-identical XML.\n",
|
|
10
10
|
"restoreLimits": "# 受限发布产物恢复边界\n\n`restore` 只是一条受限的本地故障恢复路径,不是 FairyGUI 的常规创作入口、第三方发布物导入器或源码还原承诺。本文档记录其安全使用范围,以及当前仓库已经验证过、无法仅凭发布产物稳定恢复的内容。\n\n## 使用范围与安全边界\n\n| 项目 | 当前口径 |\n|---|---|\n| 输入 | 仅处理可信的本地发布目录;不把未知来源 `.fui` / `_fui.bytes` 视为安全输入 |\n| 输出 | 必须是独立工程目录,不接受 `.fairy` 单文件目标 |\n| 路径约束 | 拒绝资源路径、包名、分支名、文件名中的路径逃逸;发布目录内资源若解析到输入目录外也会失败 |\n| 覆盖行为 | 先在相邻暂存目录完成工程和资源写入,再替换目标;`--force` 不会在二进制解析或资源重建前删除旧输出 |\n| 不代表 | 不是恶意文件检测器,也不保证第三方产物能够安全或完整恢复 |\n\n这里的“不可还原”指:\n\n| 项目 | 含义 |\n|---|---|\n| 输入范围 | 仅使用发布目录中的 `.fui` / `_fui.bytes`、图集 PNG、以及同目录 loose 资源 |\n| 判定标准 | 不能稳定、通用、无外部辅助地恢复回原工程语义或原始 XML 文本 |\n| 不包含 | 仍可通过补协议、补 writer 规则、补测试继续收敛的普通实现问题 |\n\n## 总结\n\n| 结论 | 说明 |\n|---|---|\n| 受限恢复目标 | 在可信输入下生成一个可重读、可打开、结构自洽的 FairyGUI 工程 |\n| 不保证目标 | 还原成与原工程逐字节一致的源码工程 |\n| 主要原因 | 发布产物会丢失一部分编辑器阶段信息,或把原始值降精度到运行时格式 |\n\n## 当前已确认的不可还原项\n\n### 1. 发布包中根本不存在的资源或动作\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 组件资源 | 原工程存在、但发布包未携带的组件 XML | 发布产物没有资源定义,restore 无法凭空生成真实内容 | `HitTest/component1.xml`、`PullToRefresh/Button1.xml`、`PullToRefresh/Button2.xml`、`TurnPage/Button3.xml` |\n| Transition item | 原工程存在、但二进制 transition block 未携带的 item | 二进制里没有对应时间轴项,无法可靠反推 | `Transition/BOSS.xml` 中 `target=\"n3\"` 的 6 个 item |\n\n说明:这类内容如果强行补出,只能生成占位内容,不能声称是“还原原工程”。\n\n### 2. 原始资源文件名与扩展名\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 普通图片资源 | 原工程使用的真实文件扩展名与双后缀命名 | 发布包只保留运行时资源名,不稳定保留工程文件名 | `change.jpg -> change.png`、`Paper.jpg -> Paper.png`、`i3.png.png -> i3.png` |\n| 部分 loose 资源 | 若发布名与工程名完全脱钩,且缺少稳定映射线索 | 发布目录只提供发布后文件名,原工程命名信息已经丢失 | 仍可能出现少量发布名残留 |\n\n说明:当前实现已经尽量把“资源 id 命名”还原回工程名,但对原始扩展名并不能做通用、可靠的反推。\n\n### 3. Transition path 的原始文本精度\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 路径字符串 | 编辑器 XML 中 path 的原始小数位数与文本格式 | 发布二进制只保存 float32 数值;写回时只能输出数值等价的字符串 | `Transition/PathDemo.xml` 的 `path` |\n\n说明:这类路径通常还能恢复到相同几何轨迹,但不能保证与原 XML 的字符串完全一致。\n\n### 4. 被降级为运行时默认值的编辑器信息\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| Transition easing | 原工程中的特定 ease 名称 | 当前样本对应二进制读出的就是默认 easing,无法证明原工程曾写过哪个非默认 ease | `Transition/BOSS.xml`、`TRAP.xml`、`GoodHit.xml` 中部分 `Expo.Out` / `Back.Out` / `Bounce.Out` |\n| 简单 Group 节点 | 仅用于编辑器分组、但没有额外运行时语义的 `GGroup` 节点 | 当前样本中的发布组件数据会直接裁掉这类 group,二进制 child list 里既没有 group 节点,也没有可稳定回推的 group 归属索引 | `Basics/Demo_Clip&Scroll.xml`、`Emoji/Main.xml`、`TurnPage/Book.xml` |\n| Group 高级模式 | 原工程 XML 中的 `group.advanced=\"true\"` | 发布 group block写出的是布局与间距等运行时数据,不单独保留编辑器里的高级模式开关;当前样本中二进制读回的 group 会直接落成 `advanced=false` | `Basics/Demo_Grid.xml`、`Transition/Main.xml`、`Transition/PowerUp.xml` |\n| Controller 当前选中页 | 原工程 XML 中的 `controller.selected` 当前页状态 | 发布 controller block稳定保存的是 `homePageType/homePage` 发布首页信息;当前样本中的二进制常写成 `default`,并不保留编辑器工程里当时的非零当前页 | `TurnPage/Main.xml` 的 `bookPos=\"2\"`、`TurnPage/Page.xml` 的 `style=\"1\"` / `side=\"1\"`、`FrontCover.xml` / `BackCover.xml` 的 `side=\"1\"` |\n| Controller 导出标记 | 原工程 XML 中的 `controller.exported=\"true\"` | 当前样本对应的 controller 发布 block只写 `name/pages/homePageType/homePage/actions`,没有独立写出 `exported` | `TurnPage/BackCover.xml`、`TurnPage/FrontCover.xml`、`TurnPage/Page.xml` |\n| 默认值显式性 | 原工程是否显式写出默认属性 | 发布包只保留语义值,不保留“这个默认值当时是否显式写在 XML 里” | 如 `xy=\"0,0\"`、空文本、默认布尔值等 |\n\n说明:这类信息恢复后通常仍然语义可用,但无法保证与原工程的编辑器写法逐项一致。\n\n### 5. 编辑器工程本地设置\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 工程标识 | 原始 `projectId` | restore 会生成新的工程标识 |\n| 工程设置 | 原始 `.objs` / workspace / 编辑器本地状态 | 发布目录不包含这些本地工程文件 |\n| 初始化设置之外的项目配置 | 原工程的非发布产物配置 | 当前 restore 按初始化默认值生成工程设置,而不是恢复源工程工作区状态 |\n\n说明:当前 restore 的目标是“重建可用工程”,不是恢复编辑器本地工作环境。\n\n### 6. 原工程 XML 的文本级细节\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 属性顺序 | 原标签属性排列顺序 | XML 语义不依赖属性顺序,发布产物也不保留该信息 |\n| 格式风格 | 换行、缩进、是否自闭合、空格风格 | 这是 writer 生成结果,不是发布产物协议内容 |\n| 大小写风格 | 某些颜色值、小数文本风格 | 发布包保留的是数值语义,不是原文本样式 |\n\n说明:当前实现会尽量贴近 FairyGUI 编辑器写法,但不会把这类文本风格视为“可从发布产物逆推出的正式数据”。\n\n## 当前恢复输出范围\n\n| 项目 | 当前口径 |\n|---|---|\n| 工程目标 | 在可信输入下生成可读、可打开、可继续编辑的 FairyGUI 工程 |\n| 资源目标 | 尽量恢复包内素材、组件 XML、字体派生图与 `.jta` / `.fnt` 等正式资源 |\n| 不承诺 | 与原工程一模一样的文件名、文本格式、局部编辑器状态 |\n\n## 何时需要外部辅助信息\n\n若目标不是“重建可用工程”,而是“尽量贴近原工程文本或命名”,则需要额外输入:\n\n| 额外输入 | 作用 |\n|---|---|\n| 原工程目录 | 作为命名、路径、缺失资源、文本样式的真实基准 |\n| 编辑器工作区文件 | 恢复 `.objs`、workspace、本地工程状态 |\n| 发布前清单或映射表 | 回填发布名与工程名之间的脱钩关系 |\n\n## 当前样本下仍然成立的判断\n\n| 判断 | 说明 |\n|---|---|\n| 可以从发布产物重建“可工作的工程” | 是 |\n| 可以从发布产物重建“原工程的源码真迹” | 否 |\n| 还原结果是否应该继续优化 | 可以,但应只优化“发布产物里确实有证据的部分” |\n",
|
|
11
11
|
"skill": "---\nname: openfairygui\ndescription: Navigate an installed OpenFairyGUI SDK, CLI or MCP server for FairyGUI project inspection, precise queries, revision-checked authoring and diagnosis. Use the installed version's offline documentation and generated schemas before constructing operations.\n---\n\n# OpenFairyGUI installed-version navigation\n\nUse this skill for OpenFairyGUI project workflows, not unrelated GUI frameworks.\n\n1. Locate the intended project's installed `ofgui` binary (local `node_modules/.bin/ofgui`, `ofgui.cmd` on Windows) or its configured MCP server. Do not use `npx`, install, upgrade, or fall back to a global executable automatically. If missing, report the missing installation and ask the host to choose it.\n2. Read `ofgui --version` and `ofgui docs ls --json`; compare the CLI and documentation package versions. In MCP, read `openfairygui://docs/index` and the server's version. Report mismatches before authoring; do not use online latest-version docs as the installed contract.\n3. Read `ofgui docs cat workflow` or the index's workflow URI. Use `docs find`, `docs schema <kind>`, `docs cat methods/<method>` and `docs diagnostic <code>` (or the listed MCP URIs) for exact current inputs and recovery boundaries. Never copy or guess operation grammar from this skill.\n4. Follow outline → exact query → plan → preflight → authorized apply → validate → authorized save → reread. Revision changes require refreshing and replanning, not blind retries. Read-only requests do not authorize opening locked file sessions, mutations or repairs.\n5. Use `ofgui doctor [project] --json` for read-only installation/project diagnosis. Missing bytes/decoders and path/session failures may require host action. Preserve unsaved work and report incomplete checks honestly.\n\nThe commands above navigate this installed corpus; they do not grant permission to change projects, install dependencies or widen filesystem access.\n"
|
|
12
12
|
};
|
package/src/index.ts
CHANGED
|
@@ -44,6 +44,16 @@ export {
|
|
|
44
44
|
type BackendJobStatus,
|
|
45
45
|
type BackendMethodName,
|
|
46
46
|
BACKEND_ENTITY_QUERY_LIMITS,
|
|
47
|
+
BACKEND_SESSION_READ_LIMITS,
|
|
48
|
+
type BackendSessionResourceModel,
|
|
49
|
+
type BackendSessionProjectModel,
|
|
50
|
+
type BackendSessionPackageModel,
|
|
51
|
+
type BackendSessionStateSnapshot,
|
|
52
|
+
type BackendResourceBytesSnapshot,
|
|
53
|
+
type ReadSessionStateInput,
|
|
54
|
+
type ReadResourceBytesInput,
|
|
55
|
+
type SessionReadError,
|
|
56
|
+
type SessionStaleReadError,
|
|
47
57
|
BACKEND_TRANSACTION_PREVIEW_LIMITS,
|
|
48
58
|
type BackendEntityTarget,
|
|
49
59
|
type BackendEntitySnapshot,
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
import { createRuntimePathPolicy } from '../path-policy.js';
|
|
11
11
|
import { createArtifactCapabilities } from '../services/artifact-service.js';
|
|
12
12
|
import type { BackendArtifactBridgeCapability, BackendCapabilities, BackendMethodName } from './contracts.js';
|
|
13
|
-
import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_TRANSACTION_PREVIEW_LIMITS } from './contracts.js';
|
|
13
|
+
import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_SESSION_READ_LIMITS, BACKEND_TRANSACTION_PREVIEW_LIMITS } from './contracts.js';
|
|
14
14
|
|
|
15
15
|
export const BACKEND_METHODS = [
|
|
16
16
|
'getCapabilities',
|
|
@@ -19,6 +19,8 @@ export const BACKEND_METHODS = [
|
|
|
19
19
|
'getSession',
|
|
20
20
|
'getProjectOutline',
|
|
21
21
|
'queryEntity',
|
|
22
|
+
'readSessionState',
|
|
23
|
+
'readResourceBytes',
|
|
22
24
|
'validateSession',
|
|
23
25
|
'preflightTransaction',
|
|
24
26
|
'applyTransaction',
|
|
@@ -54,6 +56,8 @@ export function createCapabilities(atomicSave = false): BackendCapabilities {
|
|
|
54
56
|
sessionSnapshot: true,
|
|
55
57
|
projectOutline: true,
|
|
56
58
|
entityQuery: { kinds: ['project', 'package', 'resource', 'component', 'displayNode', 'controller', 'transition'], projection: 'properties', sourceBytes: false, limits: BACKEND_ENTITY_QUERY_LIMITS },
|
|
59
|
+
sessionState: { sourceBytes: false, limits: BACKEND_SESSION_READ_LIMITS.model },
|
|
60
|
+
resourceBytes: { expectedRevisionRequired: true, hydration: false, maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes },
|
|
57
61
|
projectValidation: true,
|
|
58
62
|
},
|
|
59
63
|
authoring: {
|
package/src/runtime/contracts.ts
CHANGED
|
@@ -14,6 +14,7 @@ import type {
|
|
|
14
14
|
UamGenericAssetResource,
|
|
15
15
|
UamComponentResource,
|
|
16
16
|
UamProject,
|
|
17
|
+
UamPackage,
|
|
17
18
|
UamPackageSettings,
|
|
18
19
|
UamPackageSelector,
|
|
19
20
|
UamResource,
|
|
@@ -34,6 +35,55 @@ import type { BackendRuntime } from '../runtime.js';
|
|
|
34
35
|
export type BackendMethodName = keyof BackendRuntime;
|
|
35
36
|
|
|
36
37
|
export const BACKEND_ENTITY_QUERY_LIMITS = { maxBytes: 262144, maxDepth: 32, maxNodes: 100000 } as const;
|
|
38
|
+
export const BACKEND_SESSION_READ_LIMITS = {
|
|
39
|
+
model: { maxBytes: 4194304, maxDepth: 64, maxNodes: 500000 },
|
|
40
|
+
resourceBytes: 1048576,
|
|
41
|
+
} as const;
|
|
42
|
+
|
|
43
|
+
/** The public UAM model, excluding only each asset resource's primary sourceBytes. */
|
|
44
|
+
export type BackendSessionResourceModel = UamComponentResource | Omit<UamImageResource, 'sourceBytes'>
|
|
45
|
+
| Omit<UamMovieClipResource, 'sourceBytes'> | Omit<UamGenericAssetResource, 'sourceBytes'>;
|
|
46
|
+
export interface BackendSessionPackageModel extends Omit<UamPackage, 'resources'> {
|
|
47
|
+
resources: BackendSessionResourceModel[];
|
|
48
|
+
}
|
|
49
|
+
export interface BackendSessionProjectModel extends Omit<UamProject, 'packages'> {
|
|
50
|
+
packages: BackendSessionPackageModel[];
|
|
51
|
+
}
|
|
52
|
+
export interface ReadSessionStateInput {
|
|
53
|
+
sessionId: string;
|
|
54
|
+
expectedRevision?: number;
|
|
55
|
+
}
|
|
56
|
+
export interface ReadResourceBytesInput {
|
|
57
|
+
sessionId: string;
|
|
58
|
+
expectedRevision: number;
|
|
59
|
+
selector: UamResourceSelector;
|
|
60
|
+
}
|
|
61
|
+
export interface BackendSessionStateSnapshot extends Pick<BackendSessionSnapshot, 'sessionId' | 'revision' | 'lastSavedRevision' | 'dirty' | 'uamFidelity'> {
|
|
62
|
+
project: BackendSessionProjectModel;
|
|
63
|
+
readDiagnostics: import('@openfairygui/core').ProjectDiagnostic[];
|
|
64
|
+
/** Source-read completeness, not a guarantee of resource bytes or downstream usability. */
|
|
65
|
+
readComplete: boolean;
|
|
66
|
+
}
|
|
67
|
+
export interface BackendResourceBytesSnapshot {
|
|
68
|
+
sessionId: string;
|
|
69
|
+
revision: number;
|
|
70
|
+
selector: UamResourceSelector;
|
|
71
|
+
/** Only primary bytes already held in this session; no filesystem hydration. */
|
|
72
|
+
sourceBytes: Uint8Array;
|
|
73
|
+
}
|
|
74
|
+
export interface SessionReadError {
|
|
75
|
+
code: 'session_read_failed';
|
|
76
|
+
message: string;
|
|
77
|
+
sessionId: string;
|
|
78
|
+
reason: 'invalid_query' | 'not_found' | 'ambiguous' | 'unsupported_resource' | 'bytes_unavailable' | 'response_budget_exceeded' | 'non_json_value';
|
|
79
|
+
}
|
|
80
|
+
export interface SessionStaleReadError {
|
|
81
|
+
code: 'stale_read';
|
|
82
|
+
message: string;
|
|
83
|
+
sessionId: string;
|
|
84
|
+
expectedRevision: number;
|
|
85
|
+
actualRevision: number;
|
|
86
|
+
}
|
|
37
87
|
export const BACKEND_TRANSACTION_PREVIEW_LIMITS = { maxBytes: 262144, maxEntries: 2000 } as const;
|
|
38
88
|
/** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
|
|
39
89
|
export const BACKEND_RESOURCE_QUERY_FIELDS = [
|
|
@@ -178,6 +228,8 @@ export interface BackendCapabilities {
|
|
|
178
228
|
sessionSnapshot: true;
|
|
179
229
|
projectOutline: true;
|
|
180
230
|
entityQuery: { kinds: readonly BackendEntityTarget['kind'][]; projection: 'properties'; sourceBytes: false; limits: typeof BACKEND_ENTITY_QUERY_LIMITS };
|
|
231
|
+
sessionState: { sourceBytes: false; limits: typeof BACKEND_SESSION_READ_LIMITS.model };
|
|
232
|
+
resourceBytes: { expectedRevisionRequired: true; hydration: false; maxBytes: typeof BACKEND_SESSION_READ_LIMITS.resourceBytes };
|
|
181
233
|
projectValidation: true;
|
|
182
234
|
};
|
|
183
235
|
authoring: {
|
|
@@ -565,6 +617,8 @@ export type BackendError =
|
|
|
565
617
|
| SessionNotFoundError
|
|
566
618
|
| TransactionPreviewError
|
|
567
619
|
| EntityQueryError
|
|
620
|
+
| SessionReadError
|
|
621
|
+
| SessionStaleReadError
|
|
568
622
|
| SessionIdConflictError
|
|
569
623
|
| SessionStaleWriteError
|
|
570
624
|
| InProcessLockConflictError
|
package/src/runtime.ts
CHANGED
|
@@ -38,6 +38,12 @@ import type {
|
|
|
38
38
|
QueryEntityInput,
|
|
39
39
|
BackendEntitySnapshot,
|
|
40
40
|
EntityQueryError,
|
|
41
|
+
ReadSessionStateInput,
|
|
42
|
+
ReadResourceBytesInput,
|
|
43
|
+
BackendSessionStateSnapshot,
|
|
44
|
+
BackendResourceBytesSnapshot,
|
|
45
|
+
SessionReadError,
|
|
46
|
+
SessionStaleReadError,
|
|
41
47
|
ValidateSessionInput,
|
|
42
48
|
InProcessLockConflictError,
|
|
43
49
|
ListJobsInput,
|
|
@@ -151,6 +157,14 @@ export class BackendRuntime {
|
|
|
151
157
|
return this.readService.queryEntity(input);
|
|
152
158
|
}
|
|
153
159
|
|
|
160
|
+
public readSessionState(input: ReadSessionStateInput): BackendResult<BackendSessionStateSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
|
|
161
|
+
return this.readService.readSessionState(input);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
|
|
165
|
+
return this.readService.readResourceBytes(input);
|
|
166
|
+
}
|
|
167
|
+
|
|
154
168
|
public validateSession(
|
|
155
169
|
input: ValidateSessionInput,
|
|
156
170
|
): BackendResult<ProjectValidationReport, SessionNotFoundError> {
|
|
@@ -10,36 +10,48 @@ import type {
|
|
|
10
10
|
BackendResourceSnapshot,
|
|
11
11
|
EntityQueryError,
|
|
12
12
|
SessionNotFoundError,
|
|
13
|
+
ReadSessionStateInput,
|
|
14
|
+
ReadResourceBytesInput,
|
|
15
|
+
BackendSessionStateSnapshot,
|
|
16
|
+
BackendResourceBytesSnapshot,
|
|
17
|
+
SessionReadError,
|
|
18
|
+
SessionStaleReadError,
|
|
13
19
|
} from '../runtime.js';
|
|
14
20
|
import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
|
|
15
21
|
import { validateProject } from '@openfairygui/functions';
|
|
16
22
|
import type { ProjectValidationReport } from '@openfairygui/core';
|
|
17
|
-
import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS } from '../runtime/contracts.js';
|
|
23
|
+
import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS, BACKEND_SESSION_READ_LIMITS } from '../runtime/contracts.js';
|
|
18
24
|
|
|
19
25
|
/** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
|
|
20
|
-
function queryResponseProblem(value: unknown):
|
|
26
|
+
function queryResponseProblem(value: unknown, limits: { maxBytes: number; maxNodes: number; maxDepth: number } = BACKEND_ENTITY_QUERY_LIMITS): 'response_budget_exceeded' | 'non_json_value' | undefined {
|
|
21
27
|
const pending = [{ value, depth: 0 }];
|
|
22
28
|
let nodes = 0;
|
|
23
29
|
let stringUnits = 0;
|
|
24
30
|
while (pending.length) {
|
|
25
31
|
const { value, depth } = pending.pop()!;
|
|
26
|
-
if (++nodes >
|
|
27
|
-
if (typeof value === 'string' && (stringUnits += value.length) >
|
|
32
|
+
if (++nodes > limits.maxNodes || depth > limits.maxDepth) return 'response_budget_exceeded';
|
|
33
|
+
if (typeof value === 'string' && (stringUnits += value.length) > limits.maxBytes) return 'response_budget_exceeded';
|
|
28
34
|
if (value === undefined || value === null || typeof value === 'string' || typeof value === 'boolean') continue;
|
|
29
35
|
if (typeof value === 'number') { if (!Number.isFinite(value)) return 'non_json_value'; continue; }
|
|
30
36
|
if (typeof value !== 'object' || (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) return 'non_json_value';
|
|
31
|
-
if (Array.isArray(value) && value.length + pending.length + nodes >
|
|
37
|
+
if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
|
|
32
38
|
const entries = Object.entries(value);
|
|
33
|
-
if (entries.length + pending.length + nodes >
|
|
39
|
+
if (entries.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
|
|
34
40
|
for (const [key, child] of entries) {
|
|
35
|
-
if (!Array.isArray(value) && (stringUnits += key.length) >
|
|
41
|
+
if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return 'response_budget_exceeded';
|
|
36
42
|
pending.push({ value: child, depth: depth + 1 });
|
|
37
43
|
}
|
|
38
44
|
}
|
|
39
|
-
if (new TextEncoder().encode(JSON.stringify(value)).byteLength >
|
|
45
|
+
if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return 'response_budget_exceeded';
|
|
40
46
|
return undefined;
|
|
41
47
|
}
|
|
42
48
|
|
|
49
|
+
function readFailure(startedAt: number, sessionId: string, reason: SessionReadError['reason'], revision?: number) {
|
|
50
|
+
return failure('read', startedAt, {
|
|
51
|
+
code: 'session_read_failed' as const, sessionId, reason, message: `Session read failed: ${reason}.`,
|
|
52
|
+
}, undefined, { sessionId, revision });
|
|
53
|
+
}
|
|
54
|
+
|
|
43
55
|
function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
|
|
44
56
|
const project = session.project;
|
|
45
57
|
// ponytail: full outline is O(project size); add filters or pagination only if payload size becomes a measured problem.
|
|
@@ -180,6 +192,66 @@ export class ReadService {
|
|
|
180
192
|
return respond(entity);
|
|
181
193
|
}
|
|
182
194
|
|
|
195
|
+
private resolveReadSession(input: ReadSessionStateInput, startedAt: number): BackendResult<BackendSessionState, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
|
|
196
|
+
if (!input || typeof input.sessionId !== 'string' || !input.sessionId.length || input.sessionId.length > 256
|
|
197
|
+
|| (input.expectedRevision !== undefined && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0))) {
|
|
198
|
+
return readFailure(startedAt, typeof input?.sessionId === 'string' ? input.sessionId : '', 'invalid_query');
|
|
199
|
+
}
|
|
200
|
+
const session = this.context.sessions.get(input.sessionId);
|
|
201
|
+
if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
|
|
202
|
+
const meta = { sessionId: session.sessionId, revision: session.revision };
|
|
203
|
+
if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) return failure('read', startedAt, {
|
|
204
|
+
code: 'stale_read', sessionId: session.sessionId, expectedRevision: input.expectedRevision, actualRevision: session.revision,
|
|
205
|
+
message: 'The session edit revision changed. Restart the model and resource read.',
|
|
206
|
+
}, undefined, meta);
|
|
207
|
+
return success('read', startedAt, session, meta);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
public readSessionState(input: ReadSessionStateInput): BackendResult<BackendSessionStateSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
|
|
211
|
+
const startedAt = Date.now();
|
|
212
|
+
const resolved = this.resolveReadSession(input, startedAt);
|
|
213
|
+
if (!resolved.ok) return resolved;
|
|
214
|
+
const session = resolved.data;
|
|
215
|
+
const meta = { sessionId: session.sessionId, revision: session.revision };
|
|
216
|
+
// Capture synchronously: pending transactions have not committed; save bookkeeping may change without an edit revision.
|
|
217
|
+
const data: BackendSessionStateSnapshot = {
|
|
218
|
+
...meta, dirty: session.dirty, lastSavedRevision: session.lastSavedRevision,
|
|
219
|
+
uamFidelity: session.uamFidelity, readComplete: session.readComplete, readDiagnostics: session.readDiagnostics,
|
|
220
|
+
project: { ...session.project, packages: session.project.packages.map((pkg) => ({
|
|
221
|
+
...pkg, resources: pkg.resources.map((resource) => {
|
|
222
|
+
if (resource.kind === 'component') return resource;
|
|
223
|
+
const { sourceBytes: _sourceBytes, ...model } = resource;
|
|
224
|
+
return model;
|
|
225
|
+
}),
|
|
226
|
+
})) },
|
|
227
|
+
};
|
|
228
|
+
const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
|
|
229
|
+
return problem ? readFailure(startedAt, session.sessionId, problem, session.revision)
|
|
230
|
+
: success('read', startedAt, structuredClone(data), meta);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
|
|
234
|
+
const startedAt = Date.now();
|
|
235
|
+
const resolved = this.resolveReadSession(input, startedAt);
|
|
236
|
+
if (!resolved.ok) return resolved;
|
|
237
|
+
const session = resolved.data;
|
|
238
|
+
const reject = (reason: SessionReadError['reason']) => readFailure(startedAt, session.sessionId, reason, session.revision);
|
|
239
|
+
const selector = input.selector;
|
|
240
|
+
if (input.expectedRevision === undefined || !selector || typeof selector !== 'object' || Array.isArray(selector)
|
|
241
|
+
|| Object.keys(selector).length !== 2 || ['packageId', 'resourceId'].some((key) => !Object.hasOwn(selector, key))
|
|
242
|
+
|| [selector.packageId, selector.resourceId].some((value) => typeof value !== 'string' || !value.length || value.length > 256)) return reject('invalid_query');
|
|
243
|
+
const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
|
|
244
|
+
if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
|
|
245
|
+
const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
|
|
246
|
+
if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
|
|
247
|
+
const resource = resources[0];
|
|
248
|
+
if (resource.kind === 'component') return reject('unsupported_resource');
|
|
249
|
+
if (!(resource.sourceBytes instanceof Uint8Array)) return reject('bytes_unavailable');
|
|
250
|
+
if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject('response_budget_exceeded');
|
|
251
|
+
const meta = { sessionId: session.sessionId, revision: session.revision };
|
|
252
|
+
return success('read', startedAt, { ...meta, selector: { ...selector }, sourceBytes: new Uint8Array(resource.sourceBytes) }, meta);
|
|
253
|
+
}
|
|
254
|
+
|
|
183
255
|
public validateSession(
|
|
184
256
|
input: { sessionId: string },
|
|
185
257
|
): BackendResult<ProjectValidationReport, SessionNotFoundError> {
|