playcanvas-agent-bridge-cli 0.4.2 → 0.5.0

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 CHANGED
@@ -20,7 +20,7 @@ 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 include repository version `0.4.2`. Until that version is published,
23
+ The commands documented below include repository version `0.5.0`. Until that version is published,
24
24
  the npm `latest` release (`0.3.0` as of 2026-08-04) does not contain every command described here;
25
25
  use the GitHub install when testing these unreleased changes.
26
26
 
@@ -105,10 +105,10 @@ When a ready Editor connects, pcbridge creates `<projectId>-<projectName>/` auto
105
105
 
106
106
  ```text
107
107
  1552681-pcbridge-test/
108
- ├── pcbridge.project.json
109
- ├── assets/ # PlayCanvas folder mirror with bidirectional script sync
110
- ├── tmp/ # task scripts, manifests, captures, and conflict copies
111
- └── .pcbridge/ # internal asset index; do not edit
108
+ ├── pcbridge.project.json # project metadata plus the agent-readable asset catalog
109
+ ├── assets/ # PlayCanvas folder mirror with bidirectional file-content sync
110
+ ├── tmp/ # builds, cache, conflicts, captures, and quarantined remote deletions
111
+ └── .pcbridge/ # internal sync state; do not edit
112
112
  ```
113
113
 
114
114
  Inspect or refresh the workspace with:
@@ -120,10 +120,53 @@ pcbridge workspace sync --target editor:<sceneId>
120
120
  pcbridge workspace pull --target editor:<sceneId> --asset <assetId>
121
121
  ```
122
122
 
123
- Script contents synchronize in both directions. Create, move, rename, and delete assets through
124
- structured pcbridge commands. Images, models, audio, and other file assets are indexed and downloaded
125
- lazily with `workspace pull`. Concurrent local and remote script edits are preserved under
126
- `tmp/conflicts/` instead of being overwritten.
123
+ Scripts, images, models, audio, and other asset files synchronize in both directions. The initial
124
+ mirror downloads project files. Later refreshes read the complete Asset metadata snapshot but reuse
125
+ cached local size/mtime/MD5 values and transfer file content only when it is missing or changed.
126
+ A local-only edit uploads, a remote-only edit downloads, and concurrent edits preserve both text or
127
+ binary copies under `tmp/conflicts/`. Create, move, rename, and delete assets through structured
128
+ pcbridge commands; `workspace pull` remains available for an explicit single-file refresh.
129
+
130
+ `pcbridge.project.json` schema v2 stores every asset id, type, PlayCanvas folder, project-relative
131
+ `assets/...` file path, download presence, and the remote/local/base MD5 values. Agents may read
132
+ this catalog directly; the `assets` object is managed by pcbridge. An existing schema-v1 hidden
133
+ asset index is migrated automatically and retained as `.pcbridge/asset-index.v1.json` for rollback.
134
+ An empty snapshot received while indexed assets exist is ignored, and a non-empty shrinking
135
+ snapshot must repeat before files are moved to `tmp/trash/remote/`.
136
+
137
+ ## Template builds and S3 uploads
138
+
139
+ Selecting a PlayCanvas Template Asset adds a **pcbridge Tiny Builder** section to the Attributes
140
+ panel. **Build and upload to S3** collects recursive Asset references, attached scripts, and child
141
+ Templates in the page. The daemon validates the workspace MD5 cache, downloads only missing or
142
+ remote-updated files, and uploads objects concurrently without creating a ZIP. Generated
143
+ `tinyapp.json` and `gamescript.js` files live under `tmp/builds/`; variants and additional font maps
144
+ are cached under `tmp/cache/assets/`.
145
+
146
+ Create `.env` in the directory where the daemon starts for workspace defaults, or in a project
147
+ directory for per-project values. Project values override workspace values field by field. Do not
148
+ commit credential-bearing `.env` files:
149
+
150
+ ```dotenv
151
+ PCBRIDGE_S3_ENDPOINT=https://s3.example.com
152
+ PCBRIDGE_S3_REGION=us-east-1
153
+ PCBRIDGE_S3_BUCKET=my-bucket
154
+ PCBRIDGE_S3_ACCESS_KEY_ID=your-access-key
155
+ PCBRIDGE_S3_SECRET_ACCESS_KEY=your-secret-key
156
+ # PCBRIDGE_S3_SESSION_TOKEN=
157
+ PCBRIDGE_S3_PUBLIC_BASE_URL=https://cdn.example.com
158
+ PCBRIDGE_S3_PREFIX=assets
159
+ PCBRIDGE_S3_FORCE_PATH_STYLE=false
160
+ ```
161
+
162
+ The implementation uses the standard AWS S3 client and supports Amazon S3, Alibaba OSS, Tencent
163
+ COS, Cloudflare R2, and other compatible providers. Set `PCBRIDGE_S3_FORCE_PATH_STYLE` when the
164
+ provider requires path-style addressing. Builds can also be started and inspected from the CLI:
165
+
166
+ ```bash
167
+ pcbridge builder start --target editor:<sceneId> --asset <templateAssetId> --suffix '-${time}'
168
+ pcbridge builder status --job <jobId>
169
+ ```
127
170
 
128
171
  Script, JSON, upload, and capture paths are restricted to the selected project workspace by default.
129
172
  Use `--allow-external-path` only for an intentional external file.
@@ -148,6 +191,7 @@ The CLI exposes layered help so agents can load only the command surface they ne
148
191
  pcbridge help
149
192
  pcbridge help core
150
193
  pcbridge help workspace
194
+ pcbridge help builder
151
195
  pcbridge help frontend
152
196
  pcbridge help target
153
197
  pcbridge help entity
package/README.zh-CN.md CHANGED
@@ -13,7 +13,7 @@ npm install -g playcanvas-agent-bridge-cli
13
13
  pcbridge install-skill --agent all
14
14
  ```
15
15
 
16
- 下文命令包含仓库版 `0.4.2` 的尚未发布改动。在该版本发布前,npm 的 `latest`(截至
16
+ 下文命令包含仓库版 `0.5.0` 的尚未发布改动。在该版本发布前,npm 的 `latest`(截至
17
17
  2026-08-04 为 `0.3.0`)不包含这里列出的全部命令;测试本轮新能力时请使用 GitHub 安装。
18
18
 
19
19
  如果要测试尚未发布的改动,也可以直接从这个 GitHub 仓库安装:
@@ -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
- 脚本内容保持双向同步。资源的新建、移动、重命名和删除仍应使用 pcbridge 结构化命令;
123
- 图片、模型和音频等文件只建立索引,需要时用 `workspace pull` 懒下载。检测到本地与远端
124
- 同时修改时不会覆盖任一版本,冲突副本写入 `tmp/conflicts/`。
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,456 @@
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 key = `${prefix}/${buildName}/${id}/${safeSegment(local.filename, `asset-${id}`)}`;
335
+ output.file.url = publicObjectUrl(settings.publicBaseUrl, key);
336
+ uploads.set(key, {
337
+ key,
338
+ path: local.path,
339
+ contentType: contentType(local.path),
340
+ hash: local.hash || md5(await readFile(local.path)),
341
+ });
342
+ }
343
+ for (const variant of Object.values(output.file?.variants || {})) {
344
+ if (!variant.url || !variant.filename)
345
+ continue;
346
+ const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, variant.filename, variant.url, variant.hash);
347
+ const key = `${prefix}/${buildName}/${id}/${safeSegment(variant.filename, "variant.bin")}`;
348
+ variant.url = publicObjectUrl(settings.publicBaseUrl, key);
349
+ uploads.set(key, {
350
+ key,
351
+ path: cached.path,
352
+ contentType: contentType(cached.path),
353
+ hash: cached.hash,
354
+ });
355
+ }
356
+ const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
357
+ asset.data.info.maps)
358
+ ? asset.data.info.maps
359
+ : [];
360
+ if (originalFileUrl && originalFilename && fontMaps.length > 1) {
361
+ for (let index = 1; index < fontMaps.length; index += 1) {
362
+ const filename = originalFilename.replace(/(\.[^.]*)$/, `${index}$1`);
363
+ const url = originalFileUrl.replace(/(\.[^.]*)$/, `${index}$1`);
364
+ const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, filename, url);
365
+ const key = `${prefix}/${buildName}/${id}/${safeSegment(filename, `font-map-${index}`)}`;
366
+ uploads.set(key, {
367
+ key,
368
+ path: cached.path,
369
+ contentType: contentType(cached.path),
370
+ hash: cached.hash,
371
+ });
372
+ }
373
+ }
374
+ assetOutput[id] = output;
375
+ }
376
+ let scriptText = "";
377
+ for (const script of descriptor.scripts) {
378
+ const local = preparedById.get(script.assetId);
379
+ if (!local?.path)
380
+ continue;
381
+ scriptText += `\n//-----script:${script.name}-----\n`;
382
+ scriptText += await readFile(local.path, "utf8");
383
+ scriptText += "\n";
384
+ }
385
+ if (scriptText.trim()) {
386
+ const scriptPath = join(buildRoot, "gamescript.js");
387
+ await writeFile(scriptPath, scriptText);
388
+ const key = `${prefix}/${buildName}/gamescript.js`;
389
+ rootData.scriptUrl = publicObjectUrl(settings.publicBaseUrl, key);
390
+ uploads.set(key, {
391
+ key,
392
+ path: scriptPath,
393
+ contentType: contentType(scriptPath),
394
+ hash: md5(scriptText),
395
+ });
396
+ }
397
+ const rootPath = join(buildRoot, "tinyapp.json");
398
+ const rootContent = `${JSON.stringify(rootData)}\n`;
399
+ await writeFile(rootPath, rootContent);
400
+ const key = `${prefix}/${buildName}/tinyapp.json`;
401
+ const result = { key, publicUrl: publicObjectUrl(settings.publicBaseUrl, key), buildName };
402
+ uploads.set(key, {
403
+ key,
404
+ path: rootPath,
405
+ contentType: contentType(rootPath),
406
+ hash: md5(rootContent),
407
+ });
408
+ built.set(assetId, result);
409
+ return result;
410
+ };
411
+ this.#update(job, { state: "preparing", message: "Preparing upload manifest" });
412
+ const root = await buildTemplate(job.templateAssetId);
413
+ job.totalFiles = uploads.size;
414
+ const uploadFiles = [...uploads.values()];
415
+ this.#update(job, { state: "uploading", message: `Uploading 0/${uploadFiles.length} files` });
416
+ const concurrency = Math.min(4, Math.max(1, uploadFiles.length));
417
+ let cursor = 0;
418
+ const worker = async () => {
419
+ while (cursor < uploadFiles.length) {
420
+ const file = uploadFiles[cursor++];
421
+ const info = await stat(file.path);
422
+ const input = {
423
+ Bucket: settings.bucket,
424
+ Key: file.key,
425
+ Body: createReadStream(file.path),
426
+ ContentLength: info.size,
427
+ ContentType: file.contentType,
428
+ Metadata: { "pcbridge-md5": file.hash },
429
+ };
430
+ await settings.client.send(new PutObjectCommand(input));
431
+ job.completedFiles += 1;
432
+ this.#update(job, {
433
+ message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
434
+ });
435
+ }
436
+ };
437
+ await Promise.all(Array.from({ length: concurrency }, () => worker()));
438
+ this.#update(job, {
439
+ state: "completed",
440
+ message: `Uploaded ${uploadFiles.length} files`,
441
+ outputPath: join(prepared.tmpDirectory, "builds", root.buildName, "tinyapp.json"),
442
+ publicUrl: root.publicUrl,
443
+ });
444
+ }
445
+ catch (error) {
446
+ this.#update(job, {
447
+ state: "error",
448
+ message: "Build failed",
449
+ error: error instanceof Error ? error.message : String(error),
450
+ });
451
+ }
452
+ finally {
453
+ activeClient?.destroy();
454
+ }
455
+ }
456
+ }