playcanvas-agent-bridge-cli 0.4.2 → 0.5.1
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 +54 -11
- package/README.zh-CN.md +50 -9
- package/dist/builder/manager.js +459 -0
- package/dist/cli.js +37 -0
- package/dist/config.js +1 -1
- package/dist/daemon/server.js +47 -0
- package/dist/workspace/manager.js +654 -67
- package/extension/isolated.js +57 -0
- package/extension/main.js +374 -0
- package/extension/manifest.json +1 -1
- package/extension/popup.js +58 -19
- package/extension/service-worker.js +63 -0
- package/package.json +3 -1
- package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +16 -6
- package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +18 -7
- package/skills/cursor/playcanvas-agent-bridge-cli.mdc +8 -3
- package/skills/windsurf/playcanvas-agent-bridge-cli.md +7 -2
package/README.md
CHANGED
|
@@ -20,9 +20,8 @@ npm install -g github:Q-My99/playcanvas-agent-bridge-cli
|
|
|
20
20
|
pcbridge install-skill --agent all
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
The commands documented below
|
|
24
|
-
the
|
|
25
|
-
use the GitHub install when testing these unreleased changes.
|
|
23
|
+
The commands documented below track repository version `0.5.1`. npm installs the latest stable
|
|
24
|
+
release; use the GitHub install when testing changes that have not been released yet.
|
|
26
25
|
|
|
27
26
|
One-shot with npx:
|
|
28
27
|
|
|
@@ -105,10 +104,10 @@ When a ready Editor connects, pcbridge creates `<projectId>-<projectName>/` auto
|
|
|
105
104
|
|
|
106
105
|
```text
|
|
107
106
|
1552681-pcbridge-test/
|
|
108
|
-
├── pcbridge.project.json
|
|
109
|
-
├── assets/ # PlayCanvas folder mirror with bidirectional
|
|
110
|
-
├── tmp/ #
|
|
111
|
-
└── .pcbridge/ # internal
|
|
107
|
+
├── pcbridge.project.json # project metadata plus the agent-readable asset catalog
|
|
108
|
+
├── assets/ # PlayCanvas folder mirror with bidirectional file-content sync
|
|
109
|
+
├── tmp/ # builds, cache, conflicts, captures, and quarantined remote deletions
|
|
110
|
+
└── .pcbridge/ # internal sync state; do not edit
|
|
112
111
|
```
|
|
113
112
|
|
|
114
113
|
Inspect or refresh the workspace with:
|
|
@@ -120,10 +119,53 @@ pcbridge workspace sync --target editor:<sceneId>
|
|
|
120
119
|
pcbridge workspace pull --target editor:<sceneId> --asset <assetId>
|
|
121
120
|
```
|
|
122
121
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
122
|
+
Scripts, images, models, audio, and other asset files synchronize in both directions. The initial
|
|
123
|
+
mirror downloads project files. Later refreshes read the complete Asset metadata snapshot but reuse
|
|
124
|
+
cached local size/mtime/MD5 values and transfer file content only when it is missing or changed.
|
|
125
|
+
A local-only edit uploads, a remote-only edit downloads, and concurrent edits preserve both text or
|
|
126
|
+
binary copies under `tmp/conflicts/`. Create, move, rename, and delete assets through structured
|
|
127
|
+
pcbridge commands; `workspace pull` remains available for an explicit single-file refresh.
|
|
128
|
+
|
|
129
|
+
`pcbridge.project.json` schema v2 stores every asset id, type, PlayCanvas folder, project-relative
|
|
130
|
+
`assets/...` file path, download presence, and the remote/local/base MD5 values. Agents may read
|
|
131
|
+
this catalog directly; the `assets` object is managed by pcbridge. An existing schema-v1 hidden
|
|
132
|
+
asset index is migrated automatically and retained as `.pcbridge/asset-index.v1.json` for rollback.
|
|
133
|
+
An empty snapshot received while indexed assets exist is ignored, and a non-empty shrinking
|
|
134
|
+
snapshot must repeat before files are moved to `tmp/trash/remote/`.
|
|
135
|
+
|
|
136
|
+
## Template builds and S3 uploads
|
|
137
|
+
|
|
138
|
+
Selecting a PlayCanvas Template Asset adds a **pcbridge Tiny Builder** section to the Attributes
|
|
139
|
+
panel. **Build and upload to S3** collects recursive Asset references, attached scripts, and child
|
|
140
|
+
Templates in the page. The daemon validates the workspace MD5 cache, downloads only missing or
|
|
141
|
+
remote-updated files, and uploads objects concurrently without creating a ZIP. Generated
|
|
142
|
+
`tinyapp.json` and `gamescript.js` files live under `tmp/builds/`; variants and additional font maps
|
|
143
|
+
are cached under `tmp/cache/assets/`.
|
|
144
|
+
|
|
145
|
+
Create `.env` in the directory where the daemon starts for workspace defaults, or in a project
|
|
146
|
+
directory for per-project values. Project values override workspace values field by field. Do not
|
|
147
|
+
commit credential-bearing `.env` files:
|
|
148
|
+
|
|
149
|
+
```dotenv
|
|
150
|
+
PCBRIDGE_S3_ENDPOINT=https://s3.example.com
|
|
151
|
+
PCBRIDGE_S3_REGION=us-east-1
|
|
152
|
+
PCBRIDGE_S3_BUCKET=my-bucket
|
|
153
|
+
PCBRIDGE_S3_ACCESS_KEY_ID=your-access-key
|
|
154
|
+
PCBRIDGE_S3_SECRET_ACCESS_KEY=your-secret-key
|
|
155
|
+
# PCBRIDGE_S3_SESSION_TOKEN=
|
|
156
|
+
PCBRIDGE_S3_PUBLIC_BASE_URL=https://cdn.example.com
|
|
157
|
+
PCBRIDGE_S3_PREFIX=assets
|
|
158
|
+
PCBRIDGE_S3_FORCE_PATH_STYLE=false
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The implementation uses the standard AWS S3 client and supports Amazon S3, Alibaba OSS, Tencent
|
|
162
|
+
COS, Cloudflare R2, and other compatible providers. Set `PCBRIDGE_S3_FORCE_PATH_STYLE` when the
|
|
163
|
+
provider requires path-style addressing. Builds can also be started and inspected from the CLI:
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pcbridge builder start --target editor:<sceneId> --asset <templateAssetId> --suffix '-${time}'
|
|
167
|
+
pcbridge builder status --job <jobId>
|
|
168
|
+
```
|
|
127
169
|
|
|
128
170
|
Script, JSON, upload, and capture paths are restricted to the selected project workspace by default.
|
|
129
171
|
Use `--allow-external-path` only for an intentional external file.
|
|
@@ -148,6 +190,7 @@ The CLI exposes layered help so agents can load only the command surface they ne
|
|
|
148
190
|
pcbridge help
|
|
149
191
|
pcbridge help core
|
|
150
192
|
pcbridge help workspace
|
|
193
|
+
pcbridge help builder
|
|
151
194
|
pcbridge help frontend
|
|
152
195
|
pcbridge help target
|
|
153
196
|
pcbridge help entity
|
package/README.zh-CN.md
CHANGED
|
@@ -13,8 +13,8 @@ npm install -g playcanvas-agent-bridge-cli
|
|
|
13
13
|
pcbridge install-skill --agent all
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
下文命令跟随仓库版 `0.5.1`。npm 安装的是最新稳定版本;测试尚未发布的改动时请使用
|
|
17
|
+
GitHub 安装。
|
|
18
18
|
|
|
19
19
|
如果要测试尚未发布的改动,也可以直接从这个 GitHub 仓库安装:
|
|
20
20
|
|
|
@@ -104,10 +104,10 @@ pcbridge daemon start
|
|
|
104
104
|
|
|
105
105
|
```text
|
|
106
106
|
1552681-pcbridge-test/
|
|
107
|
-
├── pcbridge.project.json
|
|
108
|
-
├── assets/ # 与 PlayCanvas
|
|
109
|
-
├── tmp/ #
|
|
110
|
-
└── .pcbridge/ #
|
|
107
|
+
├── pcbridge.project.json # 项目信息和供 agent 读取的资源目录
|
|
108
|
+
├── assets/ # 与 PlayCanvas 文件夹结构对应,所有文件内容自动双向同步
|
|
109
|
+
├── tmp/ # 构建产物、缓存、冲突、截图和远端删除隔离副本
|
|
110
|
+
└── .pcbridge/ # 内部同步状态,请勿手动修改
|
|
111
111
|
```
|
|
112
112
|
|
|
113
113
|
查看或手动刷新工作区:
|
|
@@ -119,9 +119,49 @@ pcbridge workspace sync --target editor:<sceneId>
|
|
|
119
119
|
pcbridge workspace pull --target editor:<sceneId> --asset <assetId>
|
|
120
120
|
```
|
|
121
121
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
122
|
+
脚本、图片、模型、音频等文件内容都保持双向同步。首次建立镜像会下载项目文件;之后每轮
|
|
123
|
+
刷新只读取完整 Asset 元数据,并用 PlayCanvas MD5 与本地缓存的 size/mtime/MD5 判断变化,
|
|
124
|
+
不会重复全量传输文件内容。本地单边修改会上传,远端单边修改会下载;同时修改时不会覆盖
|
|
125
|
+
任一版本,文本和二进制冲突副本都写入 `tmp/conflicts/`。资源的新建、移动、重命名和删除
|
|
126
|
+
仍应使用 pcbridge 结构化命令;`workspace pull` 可用于显式重新拉取单个文件。
|
|
127
|
+
|
|
128
|
+
schema v2 的 `pcbridge.project.json` 会记录每个 asset 的 id、类型、PlayCanvas 文件夹、相对
|
|
129
|
+
项目根目录的 `assets/...` 文件路径、是否已下载,以及远端、本地和同步基线 MD5。agent 可以
|
|
130
|
+
直接读取这些信息,但其中的 `assets` 对象由 pcbridge 管理。已有 schema v1 隐藏索引会自动
|
|
131
|
+
迁移,并保留为 `.pcbridge/asset-index.v1.json` 以便回退。已有资源时收到的空快照会被忽略;
|
|
132
|
+
非空但缩小的快照必须连续出现两次,文件才会被移动到 `tmp/trash/remote/`。
|
|
133
|
+
|
|
134
|
+
## Template 构建与 S3 上传
|
|
135
|
+
|
|
136
|
+
选中 PlayCanvas Template Asset 后,Attributes 面板会出现 **pcbridge Tiny Builder**。点击
|
|
137
|
+
**构建并上传到 S3** 后,网页只负责收集 Template、递归 Asset 引用、挂载脚本和子 Template;
|
|
138
|
+
daemon 会核对工作区 MD5,缺失或远端更新的文件才会下载到工作区,然后直接并发上传对象,
|
|
139
|
+
不再生成 ZIP。生成的 `tinyapp.json` 和 `gamescript.js` 保存在 `tmp/builds/`,变体和字体附加
|
|
140
|
+
贴图缓存于 `tmp/cache/assets/`。
|
|
141
|
+
|
|
142
|
+
在 daemon 启动目录创建 `.env` 作为工作区默认配置,也可以在单个项目目录创建 `.env`;
|
|
143
|
+
项目配置按字段覆盖工作区配置。不要提交含密钥的 `.env`:
|
|
144
|
+
|
|
145
|
+
```dotenv
|
|
146
|
+
PCBRIDGE_S3_ENDPOINT=https://s3.example.com
|
|
147
|
+
PCBRIDGE_S3_REGION=us-east-1
|
|
148
|
+
PCBRIDGE_S3_BUCKET=my-bucket
|
|
149
|
+
PCBRIDGE_S3_ACCESS_KEY_ID=your-access-key
|
|
150
|
+
PCBRIDGE_S3_SECRET_ACCESS_KEY=your-secret-key
|
|
151
|
+
# PCBRIDGE_S3_SESSION_TOKEN=
|
|
152
|
+
PCBRIDGE_S3_PUBLIC_BASE_URL=https://cdn.example.com
|
|
153
|
+
PCBRIDGE_S3_PREFIX=assets
|
|
154
|
+
PCBRIDGE_S3_FORCE_PATH_STYLE=false
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
以上配置使用 AWS S3 标准客户端,适用于 Amazon S3、阿里云 OSS、腾讯云 COS、Cloudflare
|
|
158
|
+
R2 等兼容服务;自定义服务是否需要 path-style URL 由
|
|
159
|
+
`PCBRIDGE_S3_FORCE_PATH_STYLE` 决定。也可以从 CLI 发起和查看任务:
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
pcbridge builder start --target editor:<sceneId> --asset <templateAssetId> --suffix '-${time}'
|
|
163
|
+
pcbridge builder status --job <jobId>
|
|
164
|
+
```
|
|
125
165
|
|
|
126
166
|
CLI 的脚本、JSON、上传文件和截图路径默认必须位于对应项目工作区内。只有明确需要使用
|
|
127
167
|
外部文件时才使用 `--allow-external-path`。
|
|
@@ -146,6 +186,7 @@ CLI 提供分层 help,方便 agent 只加载当前需要的命令面:
|
|
|
146
186
|
pcbridge help
|
|
147
187
|
pcbridge help core
|
|
148
188
|
pcbridge help workspace
|
|
189
|
+
pcbridge help builder
|
|
149
190
|
pcbridge help frontend
|
|
150
191
|
pcbridge help target
|
|
151
192
|
pcbridge help entity
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { createReadStream, existsSync } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, extname, join } from "node:path";
|
|
5
|
+
import { PutObjectCommand, S3Client, } from "@aws-sdk/client-s3";
|
|
6
|
+
import { parse as parseEnv } from "dotenv";
|
|
7
|
+
const OMITTED_ASSET_FIELDS = new Set([
|
|
8
|
+
"uniqueId",
|
|
9
|
+
"createdAt",
|
|
10
|
+
"modifiedAt",
|
|
11
|
+
"scope",
|
|
12
|
+
"user_id",
|
|
13
|
+
"source_asset_id",
|
|
14
|
+
"source",
|
|
15
|
+
"revision",
|
|
16
|
+
"region",
|
|
17
|
+
"task",
|
|
18
|
+
"path",
|
|
19
|
+
"has_thumbnail",
|
|
20
|
+
"thumbnail",
|
|
21
|
+
"thumbnails",
|
|
22
|
+
]);
|
|
23
|
+
const ENV_EXAMPLE = `# Copy to .env and fill in the values. A project .env overrides the workspace .env.\n\
|
|
24
|
+
PCBRIDGE_S3_ENDPOINT=https://s3.example.com\n\
|
|
25
|
+
PCBRIDGE_S3_REGION=us-east-1\n\
|
|
26
|
+
PCBRIDGE_S3_BUCKET=my-bucket\n\
|
|
27
|
+
PCBRIDGE_S3_ACCESS_KEY_ID=\n\
|
|
28
|
+
PCBRIDGE_S3_SECRET_ACCESS_KEY=\n\
|
|
29
|
+
# PCBRIDGE_S3_SESSION_TOKEN=\n\
|
|
30
|
+
PCBRIDGE_S3_PUBLIC_BASE_URL=https://cdn.example.com\n\
|
|
31
|
+
PCBRIDGE_S3_PREFIX=assets\n\
|
|
32
|
+
PCBRIDGE_S3_FORCE_PATH_STYLE=false\n`;
|
|
33
|
+
function md5(value) {
|
|
34
|
+
return createHash("md5").update(value).digest("hex");
|
|
35
|
+
}
|
|
36
|
+
function clone(value) {
|
|
37
|
+
return JSON.parse(JSON.stringify(value));
|
|
38
|
+
}
|
|
39
|
+
function envValue(env, ...names) {
|
|
40
|
+
for (const name of names) {
|
|
41
|
+
const value = env[name];
|
|
42
|
+
if (value && value.trim())
|
|
43
|
+
return value.trim();
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
function booleanValue(value, fallback = false) {
|
|
48
|
+
if (!value)
|
|
49
|
+
return fallback;
|
|
50
|
+
return ["1", "true", "yes", "on"].includes(value.toLowerCase());
|
|
51
|
+
}
|
|
52
|
+
function normalizePrefix(value) {
|
|
53
|
+
const parts = String(value || "assets")
|
|
54
|
+
.replaceAll("\\", "/")
|
|
55
|
+
.split("/")
|
|
56
|
+
.map((part) => part.trim())
|
|
57
|
+
.filter(Boolean);
|
|
58
|
+
if (parts.some((part) => part === "." || part === "..")) {
|
|
59
|
+
throw new Error("S3 upload prefix cannot contain . or .. path segments.");
|
|
60
|
+
}
|
|
61
|
+
return parts.join("/");
|
|
62
|
+
}
|
|
63
|
+
function safeSegment(value, fallback) {
|
|
64
|
+
const result = value
|
|
65
|
+
.normalize("NFKC")
|
|
66
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "-")
|
|
67
|
+
.replace(/[. ]+$/g, "")
|
|
68
|
+
.trim()
|
|
69
|
+
.slice(0, 120);
|
|
70
|
+
return result || fallback;
|
|
71
|
+
}
|
|
72
|
+
function timestamp() {
|
|
73
|
+
const date = new Date();
|
|
74
|
+
const part = (value) => String(value).padStart(2, "0");
|
|
75
|
+
return `${date.getFullYear()}_${part(date.getMonth() + 1)}_${part(date.getDate())}-` +
|
|
76
|
+
`${part(date.getHours())}_${part(date.getMinutes())}_${part(date.getSeconds())}`;
|
|
77
|
+
}
|
|
78
|
+
function contentType(path) {
|
|
79
|
+
const types = {
|
|
80
|
+
".bin": "application/octet-stream",
|
|
81
|
+
".css": "text/css",
|
|
82
|
+
".gif": "image/gif",
|
|
83
|
+
".glb": "model/gltf-binary",
|
|
84
|
+
".gltf": "model/gltf+json",
|
|
85
|
+
".jpeg": "image/jpeg",
|
|
86
|
+
".jpg": "image/jpeg",
|
|
87
|
+
".js": "text/javascript; charset=utf-8",
|
|
88
|
+
".json": "application/json; charset=utf-8",
|
|
89
|
+
".mp3": "audio/mpeg",
|
|
90
|
+
".mp4": "video/mp4",
|
|
91
|
+
".ogg": "audio/ogg",
|
|
92
|
+
".png": "image/png",
|
|
93
|
+
".wasm": "application/wasm",
|
|
94
|
+
".webm": "video/webm",
|
|
95
|
+
".webp": "image/webp",
|
|
96
|
+
};
|
|
97
|
+
return types[extname(path).toLowerCase()] || "application/octet-stream";
|
|
98
|
+
}
|
|
99
|
+
function publicObjectUrl(base, key) {
|
|
100
|
+
const encoded = key.split("/").map(encodeURIComponent).join("/");
|
|
101
|
+
return `${base.replace(/\/$/, "")}/${encoded}`;
|
|
102
|
+
}
|
|
103
|
+
function sanitizeAsset(asset) {
|
|
104
|
+
const result = clone(asset);
|
|
105
|
+
for (const field of OMITTED_ASSET_FIELDS)
|
|
106
|
+
delete result[field];
|
|
107
|
+
if (result.type === "material") {
|
|
108
|
+
result.data ||= {};
|
|
109
|
+
if (!result.data.shader)
|
|
110
|
+
result.data.shader = "blinn";
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
async function readEnvFile(path) {
|
|
115
|
+
if (!existsSync(path))
|
|
116
|
+
return {};
|
|
117
|
+
return parseEnv(await readFile(path, "utf8"));
|
|
118
|
+
}
|
|
119
|
+
async function loadS3Settings(rootDir, projectDirectory) {
|
|
120
|
+
const workspacePath = join(rootDir, ".env");
|
|
121
|
+
const projectPath = join(projectDirectory, ".env");
|
|
122
|
+
if (!existsSync(workspacePath) && !existsSync(projectPath)) {
|
|
123
|
+
await writeFile(join(rootDir, ".env.example"), ENV_EXAMPLE, { flag: "wx" }).catch(() => undefined);
|
|
124
|
+
}
|
|
125
|
+
const processValues = Object.fromEntries(Object.entries(process.env).filter((entry) => typeof entry[1] === "string"));
|
|
126
|
+
const workspaceValues = await readEnvFile(workspacePath);
|
|
127
|
+
const projectValues = await readEnvFile(projectPath);
|
|
128
|
+
const env = { ...processValues, ...workspaceValues, ...projectValues };
|
|
129
|
+
const source = existsSync(projectPath)
|
|
130
|
+
? "project"
|
|
131
|
+
: existsSync(workspacePath) ? "workspace" : "environment";
|
|
132
|
+
const endpoint = envValue(env, "PCBRIDGE_S3_ENDPOINT", "S3_ENDPOINT");
|
|
133
|
+
const region = envValue(env, "PCBRIDGE_S3_REGION", "AWS_REGION", "S3_REGION") || "us-east-1";
|
|
134
|
+
const bucket = envValue(env, "PCBRIDGE_S3_BUCKET", "S3_BUCKET");
|
|
135
|
+
const accessKeyId = envValue(env, "PCBRIDGE_S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID");
|
|
136
|
+
const secretAccessKey = envValue(env, "PCBRIDGE_S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY");
|
|
137
|
+
const sessionToken = envValue(env, "PCBRIDGE_S3_SESSION_TOKEN", "AWS_SESSION_TOKEN", "S3_SESSION_TOKEN");
|
|
138
|
+
if (!bucket)
|
|
139
|
+
throw new Error("Missing PCBRIDGE_S3_BUCKET in the project or workspace .env file.");
|
|
140
|
+
if (!accessKeyId || !secretAccessKey) {
|
|
141
|
+
throw new Error("Missing PCBRIDGE_S3_ACCESS_KEY_ID or PCBRIDGE_S3_SECRET_ACCESS_KEY in the project or workspace .env file.");
|
|
142
|
+
}
|
|
143
|
+
const configuredBase = envValue(env, "PCBRIDGE_S3_PUBLIC_BASE_URL", "S3_PUBLIC_BASE_URL");
|
|
144
|
+
let publicBaseUrl = configuredBase;
|
|
145
|
+
if (!publicBaseUrl && endpoint)
|
|
146
|
+
publicBaseUrl = `${endpoint.replace(/\/$/, "")}/${bucket}`;
|
|
147
|
+
if (!publicBaseUrl)
|
|
148
|
+
publicBaseUrl = `https://${bucket}.s3.${region}.amazonaws.com`;
|
|
149
|
+
return {
|
|
150
|
+
client: new S3Client({
|
|
151
|
+
region,
|
|
152
|
+
endpoint,
|
|
153
|
+
forcePathStyle: booleanValue(envValue(env, "PCBRIDGE_S3_FORCE_PATH_STYLE", "S3_FORCE_PATH_STYLE"), false),
|
|
154
|
+
credentials: { accessKeyId, secretAccessKey, sessionToken },
|
|
155
|
+
}),
|
|
156
|
+
bucket,
|
|
157
|
+
defaultPrefix: normalizePrefix(envValue(env, "PCBRIDGE_S3_PREFIX", "S3_PREFIX")),
|
|
158
|
+
publicBaseUrl,
|
|
159
|
+
source,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function descriptorFrom(value) {
|
|
163
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
164
|
+
throw new Error("PlayCanvas returned an invalid Template dependency descriptor.");
|
|
165
|
+
}
|
|
166
|
+
const candidate = value;
|
|
167
|
+
if (!candidate.template || !Array.isArray(candidate.assets)) {
|
|
168
|
+
throw new Error("PlayCanvas returned an incomplete Template dependency descriptor.");
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
template: candidate.template,
|
|
172
|
+
assets: candidate.assets,
|
|
173
|
+
scripts: Array.isArray(candidate.scripts) ? candidate.scripts : [],
|
|
174
|
+
childTemplateIds: Array.isArray(candidate.childTemplateIds) ? candidate.childTemplateIds.map(String) : [],
|
|
175
|
+
projectUrl: typeof candidate.projectUrl === "string" ? candidate.projectUrl : null,
|
|
176
|
+
sceneUrl: typeof candidate.sceneUrl === "string" ? candidate.sceneUrl : null,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export class BuilderManager {
|
|
180
|
+
rootDir;
|
|
181
|
+
#requestTarget;
|
|
182
|
+
#workspace;
|
|
183
|
+
#jobs = new Map();
|
|
184
|
+
constructor(options) {
|
|
185
|
+
this.rootDir = options.rootDir;
|
|
186
|
+
this.#requestTarget = options.requestTarget;
|
|
187
|
+
this.#workspace = options.workspace;
|
|
188
|
+
}
|
|
189
|
+
start(info, templateAssetId, options = {}) {
|
|
190
|
+
const now = new Date().toISOString();
|
|
191
|
+
const job = {
|
|
192
|
+
id: `build_${randomUUID()}`,
|
|
193
|
+
target: info.id,
|
|
194
|
+
templateAssetId,
|
|
195
|
+
state: "queued",
|
|
196
|
+
message: "Queued",
|
|
197
|
+
completedFiles: 0,
|
|
198
|
+
totalFiles: 0,
|
|
199
|
+
createdAt: now,
|
|
200
|
+
updatedAt: now,
|
|
201
|
+
outputPath: null,
|
|
202
|
+
publicUrl: null,
|
|
203
|
+
configSource: null,
|
|
204
|
+
error: null,
|
|
205
|
+
info,
|
|
206
|
+
options,
|
|
207
|
+
};
|
|
208
|
+
this.#jobs.set(job.id, job);
|
|
209
|
+
while (this.#jobs.size > 100)
|
|
210
|
+
this.#jobs.delete(this.#jobs.keys().next().value);
|
|
211
|
+
void this.#run(job);
|
|
212
|
+
return this.#publicJob(job);
|
|
213
|
+
}
|
|
214
|
+
get(jobId) {
|
|
215
|
+
const job = this.#jobs.get(jobId);
|
|
216
|
+
return job ? this.#publicJob(job) : null;
|
|
217
|
+
}
|
|
218
|
+
#update(job, values) {
|
|
219
|
+
Object.assign(job, values, { updatedAt: new Date().toISOString() });
|
|
220
|
+
}
|
|
221
|
+
#publicJob(job) {
|
|
222
|
+
const { info: _info, options: _options, ...status } = job;
|
|
223
|
+
return status;
|
|
224
|
+
}
|
|
225
|
+
async #descriptor(info, assetId) {
|
|
226
|
+
const response = await this.#requestTarget(info.id, "bridge:collectTemplateDependencies", { assetId }, 60000);
|
|
227
|
+
if (!response.ok)
|
|
228
|
+
throw new Error(response.error.message);
|
|
229
|
+
return descriptorFrom(response.data);
|
|
230
|
+
}
|
|
231
|
+
async #cacheRemoteFile(info, projectDirectory, assetId, filename, url, expectedHash) {
|
|
232
|
+
const path = join(projectDirectory, "tmp", "cache", "assets", safeSegment(assetId, "asset"), safeSegment(filename, "file.bin"));
|
|
233
|
+
if (existsSync(path)) {
|
|
234
|
+
const content = await readFile(path);
|
|
235
|
+
const hash = md5(content);
|
|
236
|
+
if (!expectedHash || hash === expectedHash)
|
|
237
|
+
return { path, hash };
|
|
238
|
+
}
|
|
239
|
+
const response = await this.#requestTarget(info.id, "bridge:readAssetResource", { assetId, url }, 120000);
|
|
240
|
+
if (!response.ok)
|
|
241
|
+
throw new Error(response.error.message);
|
|
242
|
+
const data = response.data;
|
|
243
|
+
const base64 = typeof data.base64 === "string" ? data.base64 : "";
|
|
244
|
+
if (!base64)
|
|
245
|
+
throw new Error(`Asset ${assetId} resource ${filename} returned no data.`);
|
|
246
|
+
const content = Buffer.from(base64, "base64");
|
|
247
|
+
const hash = md5(content);
|
|
248
|
+
if (expectedHash && hash !== expectedHash) {
|
|
249
|
+
throw new Error(`Asset ${assetId} resource ${filename} did not match its PlayCanvas MD5.`);
|
|
250
|
+
}
|
|
251
|
+
await mkdir(dirname(path), { recursive: true });
|
|
252
|
+
await writeFile(path, content);
|
|
253
|
+
return { path, hash };
|
|
254
|
+
}
|
|
255
|
+
async #run(job) {
|
|
256
|
+
let activeClient = null;
|
|
257
|
+
try {
|
|
258
|
+
this.#update(job, { state: "collecting", message: "Collecting Template dependencies" });
|
|
259
|
+
const descriptors = new Map();
|
|
260
|
+
const visit = async (assetId, stack) => {
|
|
261
|
+
if (descriptors.has(assetId))
|
|
262
|
+
return;
|
|
263
|
+
if (stack.has(assetId))
|
|
264
|
+
throw new Error(`Template dependency cycle detected at asset ${assetId}.`);
|
|
265
|
+
const nextStack = new Set(stack).add(assetId);
|
|
266
|
+
const descriptor = await this.#descriptor(job.info, assetId);
|
|
267
|
+
descriptors.set(assetId, descriptor);
|
|
268
|
+
for (const childId of descriptor.childTemplateIds)
|
|
269
|
+
await visit(childId, nextStack);
|
|
270
|
+
};
|
|
271
|
+
await visit(job.templateAssetId, new Set());
|
|
272
|
+
this.#update(job, { state: "syncing", message: "Synchronizing dependency files" });
|
|
273
|
+
const allAssetIds = new Set();
|
|
274
|
+
for (const descriptor of descriptors.values()) {
|
|
275
|
+
for (const asset of descriptor.assets)
|
|
276
|
+
allAssetIds.add(String(asset.id));
|
|
277
|
+
}
|
|
278
|
+
const prepared = await this.#workspace.prepareAssetFiles(job.info, [...allAssetIds]);
|
|
279
|
+
const preparedById = new Map(prepared.assets.map((asset) => [asset.id, asset]));
|
|
280
|
+
const settings = await loadS3Settings(this.rootDir, prepared.projectDirectory);
|
|
281
|
+
activeClient = settings.client;
|
|
282
|
+
job.configSource = settings.source;
|
|
283
|
+
const prefix = normalizePrefix(job.options.prefix || settings.defaultPrefix);
|
|
284
|
+
const uploads = new Map();
|
|
285
|
+
const built = new Map();
|
|
286
|
+
const buildTemplate = async (assetId) => {
|
|
287
|
+
const existing = built.get(assetId);
|
|
288
|
+
if (existing)
|
|
289
|
+
return existing;
|
|
290
|
+
const descriptor = descriptors.get(assetId);
|
|
291
|
+
if (!descriptor)
|
|
292
|
+
throw new Error(`Missing descriptor for Template ${assetId}.`);
|
|
293
|
+
for (const childId of descriptor.childTemplateIds)
|
|
294
|
+
await buildTemplate(childId);
|
|
295
|
+
const suffix = String(job.options.suffix || "").replaceAll("${time}", timestamp());
|
|
296
|
+
const buildName = safeSegment(`${descriptor.template.name}${suffix}`, `template-${assetId}`);
|
|
297
|
+
const buildRoot = join(prepared.tmpDirectory, "builds", buildName);
|
|
298
|
+
await mkdir(buildRoot, { recursive: true });
|
|
299
|
+
const rootData = {
|
|
300
|
+
projectUrl: descriptor.projectUrl,
|
|
301
|
+
sceneUrl: descriptor.sceneUrl,
|
|
302
|
+
template: clone(descriptor.template.data || {}),
|
|
303
|
+
assets: {},
|
|
304
|
+
};
|
|
305
|
+
const templateData = rootData.template;
|
|
306
|
+
const entities = templateData.entities && typeof templateData.entities === "object"
|
|
307
|
+
? templateData.entities
|
|
308
|
+
: {};
|
|
309
|
+
for (const entity of Object.values(entities)) {
|
|
310
|
+
const attributes = entity.components?.script;
|
|
311
|
+
const scripts = attributes?.scripts;
|
|
312
|
+
const handler = scripts?.sdsTinyRootHandler;
|
|
313
|
+
const values = handler?.attributes;
|
|
314
|
+
const childId = values && Number.isInteger(values.testTemplate)
|
|
315
|
+
? String(values.testTemplate)
|
|
316
|
+
: null;
|
|
317
|
+
if (!childId || !built.has(childId))
|
|
318
|
+
continue;
|
|
319
|
+
delete values.testTemplate;
|
|
320
|
+
values.type = "TinyApp";
|
|
321
|
+
values.tinyAppUrl = built.get(childId).publicUrl;
|
|
322
|
+
}
|
|
323
|
+
const assetOutput = rootData.assets;
|
|
324
|
+
const scriptIds = new Set(descriptor.scripts.map((script) => script.assetId));
|
|
325
|
+
for (const asset of descriptor.assets) {
|
|
326
|
+
const id = String(asset.id);
|
|
327
|
+
if (scriptIds.has(id) || asset.type === "script")
|
|
328
|
+
continue;
|
|
329
|
+
const output = sanitizeAsset(asset);
|
|
330
|
+
const originalFileUrl = asset.file?.url;
|
|
331
|
+
const originalFilename = asset.file?.filename;
|
|
332
|
+
const local = preparedById.get(id);
|
|
333
|
+
if (output.file && local?.path && local.filename) {
|
|
334
|
+
const relativeUrl = `${buildName}/${id}/${safeSegment(local.filename, `asset-${id}`)}`;
|
|
335
|
+
const key = `${prefix}/${relativeUrl}`;
|
|
336
|
+
output.file.url = relativeUrl;
|
|
337
|
+
uploads.set(key, {
|
|
338
|
+
key,
|
|
339
|
+
path: local.path,
|
|
340
|
+
contentType: contentType(local.path),
|
|
341
|
+
hash: local.hash || md5(await readFile(local.path)),
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
for (const variant of Object.values(output.file?.variants || {})) {
|
|
345
|
+
if (!variant.url || !variant.filename)
|
|
346
|
+
continue;
|
|
347
|
+
const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, variant.filename, variant.url, variant.hash);
|
|
348
|
+
const relativeUrl = `${buildName}/${id}/${safeSegment(variant.filename, "variant.bin")}`;
|
|
349
|
+
const key = `${prefix}/${relativeUrl}`;
|
|
350
|
+
variant.url = relativeUrl;
|
|
351
|
+
uploads.set(key, {
|
|
352
|
+
key,
|
|
353
|
+
path: cached.path,
|
|
354
|
+
contentType: contentType(cached.path),
|
|
355
|
+
hash: cached.hash,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
|
|
359
|
+
asset.data.info.maps)
|
|
360
|
+
? asset.data.info.maps
|
|
361
|
+
: [];
|
|
362
|
+
if (originalFileUrl && originalFilename && fontMaps.length > 1) {
|
|
363
|
+
for (let index = 1; index < fontMaps.length; index += 1) {
|
|
364
|
+
const filename = originalFilename.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
365
|
+
const url = originalFileUrl.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
366
|
+
const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, filename, url);
|
|
367
|
+
const key = `${prefix}/${buildName}/${id}/${safeSegment(filename, `font-map-${index}`)}`;
|
|
368
|
+
uploads.set(key, {
|
|
369
|
+
key,
|
|
370
|
+
path: cached.path,
|
|
371
|
+
contentType: contentType(cached.path),
|
|
372
|
+
hash: cached.hash,
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
assetOutput[id] = output;
|
|
377
|
+
}
|
|
378
|
+
let scriptText = "";
|
|
379
|
+
for (const script of descriptor.scripts) {
|
|
380
|
+
const local = preparedById.get(script.assetId);
|
|
381
|
+
if (!local?.path)
|
|
382
|
+
continue;
|
|
383
|
+
scriptText += `\n//-----script:${script.name}-----\n`;
|
|
384
|
+
scriptText += await readFile(local.path, "utf8");
|
|
385
|
+
scriptText += "\n";
|
|
386
|
+
}
|
|
387
|
+
if (scriptText.trim()) {
|
|
388
|
+
const scriptPath = join(buildRoot, "gamescript.js");
|
|
389
|
+
await writeFile(scriptPath, scriptText);
|
|
390
|
+
const relativeUrl = `${buildName}/gamescript.js`;
|
|
391
|
+
const key = `${prefix}/${relativeUrl}`;
|
|
392
|
+
rootData.scriptUrl = relativeUrl;
|
|
393
|
+
uploads.set(key, {
|
|
394
|
+
key,
|
|
395
|
+
path: scriptPath,
|
|
396
|
+
contentType: contentType(scriptPath),
|
|
397
|
+
hash: md5(scriptText),
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
const rootPath = join(buildRoot, "tinyapp.json");
|
|
401
|
+
const rootContent = `${JSON.stringify(rootData)}\n`;
|
|
402
|
+
await writeFile(rootPath, rootContent);
|
|
403
|
+
const key = `${prefix}/${buildName}/tinyapp.json`;
|
|
404
|
+
const result = { key, publicUrl: publicObjectUrl(settings.publicBaseUrl, key), buildName };
|
|
405
|
+
uploads.set(key, {
|
|
406
|
+
key,
|
|
407
|
+
path: rootPath,
|
|
408
|
+
contentType: contentType(rootPath),
|
|
409
|
+
hash: md5(rootContent),
|
|
410
|
+
});
|
|
411
|
+
built.set(assetId, result);
|
|
412
|
+
return result;
|
|
413
|
+
};
|
|
414
|
+
this.#update(job, { state: "preparing", message: "Preparing upload manifest" });
|
|
415
|
+
const root = await buildTemplate(job.templateAssetId);
|
|
416
|
+
job.totalFiles = uploads.size;
|
|
417
|
+
const uploadFiles = [...uploads.values()];
|
|
418
|
+
this.#update(job, { state: "uploading", message: `Uploading 0/${uploadFiles.length} files` });
|
|
419
|
+
const concurrency = Math.min(4, Math.max(1, uploadFiles.length));
|
|
420
|
+
let cursor = 0;
|
|
421
|
+
const worker = async () => {
|
|
422
|
+
while (cursor < uploadFiles.length) {
|
|
423
|
+
const file = uploadFiles[cursor++];
|
|
424
|
+
const info = await stat(file.path);
|
|
425
|
+
const input = {
|
|
426
|
+
Bucket: settings.bucket,
|
|
427
|
+
Key: file.key,
|
|
428
|
+
Body: createReadStream(file.path),
|
|
429
|
+
ContentLength: info.size,
|
|
430
|
+
ContentType: file.contentType,
|
|
431
|
+
Metadata: { "pcbridge-md5": file.hash },
|
|
432
|
+
};
|
|
433
|
+
await settings.client.send(new PutObjectCommand(input));
|
|
434
|
+
job.completedFiles += 1;
|
|
435
|
+
this.#update(job, {
|
|
436
|
+
message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
await Promise.all(Array.from({ length: concurrency }, () => worker()));
|
|
441
|
+
this.#update(job, {
|
|
442
|
+
state: "completed",
|
|
443
|
+
message: `Uploaded ${uploadFiles.length} files`,
|
|
444
|
+
outputPath: join(prepared.tmpDirectory, "builds", root.buildName, "tinyapp.json"),
|
|
445
|
+
publicUrl: root.publicUrl,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
catch (error) {
|
|
449
|
+
this.#update(job, {
|
|
450
|
+
state: "error",
|
|
451
|
+
message: "Build failed",
|
|
452
|
+
error: error instanceof Error ? error.message : String(error),
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
finally {
|
|
456
|
+
activeClient?.destroy();
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|