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.
@@ -1,13 +1,32 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readFile, readdir, rename, rmdir, writeFile, } from "node:fs/promises";
3
+ import { copyFile, lstat, mkdir, readFile, readdir, rename, rmdir, stat, writeFile, } from "node:fs/promises";
4
4
  import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
5
5
  const PROJECT_FILE = "pcbridge.project.json";
6
- const INDEX_FILE = join(".pcbridge", "asset-index.json");
6
+ const LEGACY_INDEX_FILE = join(".pcbridge", "asset-index.json");
7
+ const LEGACY_INDEX_BACKUP_FILE = join(".pcbridge", "asset-index.v1.json");
8
+ const SYNC_STATE_FILE = join(".pcbridge", "sync-state.json");
7
9
  const DEFAULT_REFRESH_INTERVAL_MS = 5000;
8
10
  function hashContent(value) {
11
+ return createHash("md5").update(value).digest("hex");
12
+ }
13
+ function hashLegacyContent(value) {
9
14
  return createHash("sha256").update(value).digest("hex");
10
15
  }
16
+ function toPosixPath(value) {
17
+ return value.replaceAll("\\", "/");
18
+ }
19
+ function manifestLocalPath(value) {
20
+ if (!value)
21
+ return null;
22
+ const parts = value.split("/");
23
+ if (parts[0] !== "assets" || parts.length < 2)
24
+ return null;
25
+ if (parts.some((part) => !part || part === "." || part === ".." || part.includes("\\"))) {
26
+ return null;
27
+ }
28
+ return join(...parts.slice(1));
29
+ }
11
30
  export function safeWorkspaceName(value, fallback) {
12
31
  const safe = value
13
32
  .normalize("NFKC")
@@ -101,10 +120,11 @@ export class WorkspaceManager {
101
120
  }
102
121
  const record = existing || await this.#createRecord(info);
103
122
  record.targetId = info.id;
123
+ record.targetInfo = info;
104
124
  record.connected = true;
105
125
  record.projectName = info.projectName;
106
126
  record.branchName = info.branchName || record.branchName;
107
- await this.#writeManifest(record, info);
127
+ await this.#writeManifest(record);
108
128
  await this.#sync(record, false);
109
129
  }
110
130
  markDisconnected(info) {
@@ -153,10 +173,49 @@ export class WorkspaceManager {
153
173
  throw new Error(`Workspace is bound to branch ${record.branchId}, not ${info.branchId}.`);
154
174
  }
155
175
  record.targetId = info.id;
176
+ record.targetInfo = info;
156
177
  record.connected = true;
157
178
  await this.#sync(record, true);
158
179
  return this.#status(record);
159
180
  }
181
+ async prepareAssetFiles(info, assetIds) {
182
+ if (!info.projectId)
183
+ throw new Error("The selected target has no project metadata.");
184
+ const record = this.#records.get(info.projectId);
185
+ if (!record)
186
+ throw new Error("The selected project workspace has not been initialized.");
187
+ record.targetId = info.id;
188
+ record.targetInfo = info;
189
+ record.connected = true;
190
+ await this.#sync(record, true);
191
+ const assets = [];
192
+ for (const rawId of assetIds) {
193
+ const id = String(rawId);
194
+ const entry = record.index.entries[id];
195
+ if (!entry)
196
+ throw new Error(`Asset ${id} is not present in the workspace catalog.`);
197
+ if (entry.status === "conflict" || entry.status === "error") {
198
+ throw new Error(`Asset ${id} cannot be built while its workspace state is ${entry.status}.`);
199
+ }
200
+ if (entry.localPath && !existsSync(this.#assetPath(record, entry.localPath))) {
201
+ await this.#downloadAsset(record, entry);
202
+ }
203
+ assets.push({
204
+ id,
205
+ name: entry.name,
206
+ type: entry.type,
207
+ filename: entry.filename,
208
+ path: entry.localPath ? this.#assetPath(record, entry.localPath) : null,
209
+ hash: entry.localHash,
210
+ });
211
+ }
212
+ await this.#persist(record);
213
+ return {
214
+ projectDirectory: record.directory,
215
+ tmpDirectory: record.tmpDirectory,
216
+ assets,
217
+ };
218
+ }
160
219
  async pullAsset(info, assetId) {
161
220
  if (!info.projectId)
162
221
  throw new Error("The selected target has no project metadata.");
@@ -171,23 +230,14 @@ export class WorkspaceManager {
171
230
  if (entry.type === "script") {
172
231
  throw new Error("Scripts are synchronized automatically; use workspace sync instead.");
173
232
  }
174
- const response = await this.#requestTarget(info.id, "bridge:readAssetFile", { assetId }, 120000);
175
- if (!response.ok)
176
- throw new Error(response.error.message);
177
- const data = asObject(response.data);
178
- const base64 = typeof data.base64 === "string" ? data.base64 : "";
179
- if (!base64)
180
- throw new Error(`Asset ${assetId} returned no file data.`);
181
- const path = this.#assetPath(record, entry.localPath);
182
- await atomicWrite(path, Buffer.from(base64, "base64"));
183
- entry.downloaded = true;
184
- entry.localHash = hashContent(await readFile(path));
185
- entry.status = "synced";
186
- await this.#writeIndex(record);
233
+ const result = await this.#downloadAsset(record, entry);
234
+ await this.#persist(record);
187
235
  return {
188
236
  assetId,
189
- path,
190
- size: Buffer.byteLength(base64, "base64"),
237
+ path: result.path,
238
+ size: result.size,
239
+ hash: result.hash,
240
+ hashAlgorithm: "md5",
191
241
  };
192
242
  }
193
243
  async #createRecord(info) {
@@ -204,17 +254,20 @@ export class WorkspaceManager {
204
254
  await mkdir(join(tmpDirectory, "scripts"), { recursive: true });
205
255
  await mkdir(join(tmpDirectory, "captures"), { recursive: true });
206
256
  await mkdir(join(tmpDirectory, "conflicts"), { recursive: true });
257
+ await mkdir(join(tmpDirectory, "trash", "remote"), { recursive: true });
207
258
  await mkdir(join(directory, ".pcbridge"), { recursive: true });
208
- const stored = await readJson(join(directory, INDEX_FILE));
209
- const index = stored?.schemaVersion === 1
210
- ? stored
211
- : {
212
- schemaVersion: 1,
213
- projectId: info.projectId || "",
214
- branchId: info.branchId || null,
215
- updatedAt: new Date().toISOString(),
216
- entries: {},
217
- };
259
+ const manifest = await readJson(join(directory, PROJECT_FILE));
260
+ const syncState = await readJson(join(directory, SYNC_STATE_FILE));
261
+ const legacyPrimaryPath = join(directory, LEGACY_INDEX_FILE);
262
+ const legacyBackupPath = join(directory, LEGACY_INDEX_BACKUP_FILE);
263
+ const legacyPrimary = await readJson(legacyPrimaryPath);
264
+ const legacyBackup = legacyPrimary ? null : await readJson(legacyBackupPath);
265
+ const legacy = legacyPrimary?.schemaVersion === 1
266
+ ? legacyPrimary
267
+ : legacyBackup?.schemaVersion === 1 ? legacyBackup : null;
268
+ const index = manifest?.schemaVersion === 2 && manifest.assets
269
+ ? this.#indexFromManifest(manifest, syncState, info)
270
+ : await this.#indexFromLegacy(directory, legacy, info);
218
271
  const record = {
219
272
  projectId: info.projectId || "",
220
273
  projectName: info.projectName || "Project",
@@ -224,10 +277,22 @@ export class WorkspaceManager {
224
277
  assetsDirectory,
225
278
  tmpDirectory,
226
279
  targetId: info.id,
280
+ targetInfo: info,
227
281
  connected: true,
228
282
  state: "initializing",
229
- lastSyncedAt: null,
283
+ lastSyncedAt: typeof syncState?.lastSuccessfulSyncAt === "string"
284
+ ? syncState.lastSuccessfulSyncAt
285
+ : typeof manifest?.workspace?.lastSuccessfulSyncAt === "string"
286
+ ? manifest.workspace.lastSuccessfulSyncAt
287
+ : null,
230
288
  lastError: null,
289
+ lastWarning: null,
290
+ syncStartedAt: null,
291
+ syncPhase: null,
292
+ syncProgress: null,
293
+ pendingShrinkDigest: null,
294
+ pendingShrinkCount: 0,
295
+ legacyIndexPath: legacyPrimary?.schemaVersion === 1 ? legacyPrimaryPath : null,
231
296
  index,
232
297
  syncPromise: null,
233
298
  };
@@ -266,10 +331,125 @@ export class WorkspaceManager {
266
331
  }
267
332
  return path;
268
333
  }
269
- async #writeManifest(record, info) {
334
+ #indexFromManifest(manifest, syncState, info) {
335
+ const entries = {};
336
+ for (const [id, asset] of Object.entries(manifest.assets || {})) {
337
+ const localPath = manifestLocalPath(asset.file?.path);
338
+ const present = Boolean(localPath && asset.file?.present);
339
+ const state = asset.state === "remote-only" ? "indexed" : asset.state;
340
+ entries[id] = {
341
+ id,
342
+ name: asset.name,
343
+ type: asset.type,
344
+ remotePath: asset.folder ? asset.folder.split("/").filter(Boolean) : [],
345
+ localPath,
346
+ filename: asset.file?.filename || null,
347
+ remoteFileSize: asset.file?.size ?? null,
348
+ remoteFileHash: asset.file?.hash.remote || null,
349
+ localHash: present ? asset.file?.hash.local || null : null,
350
+ lastSyncedHash: asset.file?.hash.base || null,
351
+ legacyLastSyncedSha256: syncState?.entries?.[id]?.legacyLastSyncedSha256,
352
+ pendingRemoteHash: syncState?.entries?.[id]?.pendingRemoteHash,
353
+ localFileSize: syncState?.entries?.[id]?.localFileSize,
354
+ localMtimeMs: syncState?.entries?.[id]?.localMtimeMs,
355
+ downloaded: present,
356
+ status: state,
357
+ error: asset.error,
358
+ };
359
+ }
360
+ return {
361
+ schemaVersion: 2,
362
+ projectId: info.projectId || manifest.project?.id || "",
363
+ branchId: info.branchId || manifest.activeBranch?.id || null,
364
+ updatedAt: manifest.workspace?.updatedAt || new Date().toISOString(),
365
+ entries,
366
+ };
367
+ }
368
+ async #indexFromLegacy(directory, legacy, info) {
369
+ const entries = {};
370
+ for (const [id, old] of Object.entries(legacy?.entries || {})) {
371
+ const localPath = old.localPath || null;
372
+ const assetsDirectory = resolve(directory, "assets");
373
+ const candidate = localPath ? resolve(assetsDirectory, localPath) : null;
374
+ const path = candidate && candidate.startsWith(`${assetsDirectory}${sep}`) ? candidate : null;
375
+ const localContent = path && existsSync(path) ? await readFile(path) : null;
376
+ const localHash = localContent ? hashContent(localContent) : null;
377
+ const localSha256 = localContent ? hashLegacyContent(localContent) : null;
378
+ const migratedBase = old.lastSyncedHash && localSha256 === old.lastSyncedHash
379
+ ? old.remoteFileHash || null
380
+ : null;
381
+ entries[id] = {
382
+ id,
383
+ name: old.name,
384
+ type: old.type,
385
+ remotePath: old.remotePath || [],
386
+ localPath,
387
+ filename: old.filename || null,
388
+ remoteFileSize: old.remoteFileSize ?? null,
389
+ remoteFileHash: old.remoteFileHash || null,
390
+ localHash,
391
+ lastSyncedHash: migratedBase,
392
+ legacyLastSyncedSha256: migratedBase ? undefined : old.lastSyncedHash || undefined,
393
+ pendingRemoteHash: old.pendingRemoteHash,
394
+ localFileSize: old.localFileSize,
395
+ localMtimeMs: old.localMtimeMs,
396
+ downloaded: Boolean(localContent),
397
+ status: old.status,
398
+ error: old.error,
399
+ };
400
+ }
401
+ return {
402
+ schemaVersion: 2,
403
+ projectId: info.projectId || legacy?.projectId || "",
404
+ branchId: info.branchId || legacy?.branchId || null,
405
+ updatedAt: legacy?.updatedAt || new Date().toISOString(),
406
+ entries,
407
+ };
408
+ }
409
+ #manifestAssets(record) {
410
+ const assets = {};
411
+ const sorted = Object.values(record.index.entries)
412
+ .sort((left, right) => left.id.localeCompare(right.id, undefined, { numeric: true }));
413
+ for (const entry of sorted) {
414
+ const present = Boolean(entry.localPath && entry.downloaded && existsSync(this.#assetPath(record, entry.localPath)));
415
+ const publicState = entry.status === "indexed" && entry.localPath && !present
416
+ ? "remote-only"
417
+ : entry.status;
418
+ const asset = {
419
+ id: entry.id,
420
+ name: entry.name,
421
+ type: entry.type,
422
+ folder: toPosixPath(entry.remotePath.join("/")),
423
+ file: entry.localPath && entry.filename
424
+ ? {
425
+ filename: entry.filename,
426
+ path: `assets/${toPosixPath(entry.localPath)}`,
427
+ size: entry.remoteFileSize,
428
+ present,
429
+ hash: {
430
+ algorithm: "md5",
431
+ remote: entry.remoteFileHash,
432
+ local: present ? entry.localHash : null,
433
+ base: entry.lastSyncedHash,
434
+ matches: entry.remoteFileHash && present && entry.localHash
435
+ ? entry.remoteFileHash === entry.localHash
436
+ : null,
437
+ },
438
+ }
439
+ : null,
440
+ state: publicState,
441
+ };
442
+ if (entry.error)
443
+ asset.error = entry.error;
444
+ assets[entry.id] = asset;
445
+ }
446
+ return assets;
447
+ }
448
+ async #writeManifest(record) {
270
449
  const path = join(record.directory, PROJECT_FILE);
271
450
  const existing = await readJson(path);
272
- const scenes = existing?.scenes || [];
451
+ const info = record.targetInfo;
452
+ const scenes = Array.isArray(existing?.scenes) ? [...existing.scenes] : [];
273
453
  if (info.sceneId) {
274
454
  const scene = scenes.find((item) => item.id === info.sceneId);
275
455
  if (scene)
@@ -278,21 +458,84 @@ export class WorkspaceManager {
278
458
  scenes.push({ id: info.sceneId, name: info.sceneName || null });
279
459
  }
280
460
  const now = new Date().toISOString();
461
+ const existingSettings = existing?.settings && typeof existing.settings === "object"
462
+ ? existing.settings
463
+ : {};
464
+ const existingSync = existingSettings.sync && typeof existingSettings.sync === "object"
465
+ ? existingSettings.sync
466
+ : {};
467
+ const previousLastSuccessfulSyncAt = existing?.workspace &&
468
+ Object.prototype.hasOwnProperty.call(existing.workspace, "lastSuccessfulSyncAt")
469
+ ? existing.workspace.lastSuccessfulSyncAt
470
+ : record.lastSyncedAt;
281
471
  const manifest = {
282
- schemaVersion: 1,
472
+ ...(existing || {}),
473
+ schemaVersion: 2,
283
474
  project: { id: record.projectId, name: record.projectName },
284
475
  activeBranch: { id: record.branchId, name: record.branchName },
285
476
  scenes,
286
477
  workspace: {
478
+ ...(existing?.workspace || {}),
287
479
  createdAt: existing?.workspace?.createdAt || now,
288
- updatedAt: now,
480
+ updatedAt: existing?.workspace?.updatedAt || now,
481
+ assetCatalogComplete: Boolean(record.lastSyncedAt),
482
+ assetCount: Object.values(record.index.entries)
483
+ .filter((entry) => entry.type !== "folder").length,
484
+ assetHashAlgorithm: "md5",
485
+ lastSuccessfulSyncAt: previousLastSuccessfulSyncAt,
486
+ },
487
+ settings: {
488
+ ...existingSettings,
489
+ sync: {
490
+ conflictPolicy: "safe-newer",
491
+ deletePolicy: "quarantine",
492
+ ...existingSync,
493
+ contentMode: "all",
494
+ },
289
495
  },
496
+ assets: this.#manifestAssets(record),
497
+ };
498
+ if (existing && JSON.stringify(manifest) === JSON.stringify(existing))
499
+ return;
500
+ manifest.workspace = {
501
+ ...manifest.workspace,
502
+ updatedAt: now,
503
+ lastSuccessfulSyncAt: record.lastSyncedAt,
290
504
  };
291
505
  await atomicWrite(path, `${JSON.stringify(manifest, null, 2)}\n`);
292
506
  }
293
- async #writeIndex(record) {
507
+ async #writeSyncState(record) {
294
508
  record.index.updatedAt = new Date().toISOString();
295
- await atomicWrite(join(record.directory, INDEX_FILE), `${JSON.stringify(record.index, null, 2)}\n`);
509
+ const entries = Object.fromEntries(Object.values(record.index.entries)
510
+ .filter((entry) => entry.legacyLastSyncedSha256 ||
511
+ entry.pendingRemoteHash ||
512
+ entry.localFileSize !== undefined ||
513
+ entry.localMtimeMs !== undefined)
514
+ .map((entry) => [entry.id, {
515
+ legacyLastSyncedSha256: entry.legacyLastSyncedSha256,
516
+ pendingRemoteHash: entry.pendingRemoteHash,
517
+ localFileSize: entry.localFileSize,
518
+ localMtimeMs: entry.localMtimeMs,
519
+ }]));
520
+ await atomicWrite(join(record.directory, SYNC_STATE_FILE), `${JSON.stringify({
521
+ schemaVersion: 1,
522
+ projectId: record.projectId,
523
+ branchId: record.branchId,
524
+ updatedAt: record.index.updatedAt,
525
+ lastSuccessfulSyncAt: record.lastSyncedAt,
526
+ entries,
527
+ }, null, 2)}\n`);
528
+ }
529
+ async #persist(record) {
530
+ await this.#writeManifest(record);
531
+ await this.#writeSyncState(record);
532
+ if (record.legacyIndexPath && existsSync(record.legacyIndexPath)) {
533
+ const backup = join(record.directory, LEGACY_INDEX_BACKUP_FILE);
534
+ if (!existsSync(backup))
535
+ await rename(record.legacyIndexPath, backup);
536
+ if (!existsSync(record.legacyIndexPath))
537
+ record.legacyIndexPath = null;
538
+ }
296
539
  }
297
540
  async #sync(record, force) {
298
541
  if (record.syncPromise)
@@ -303,14 +546,29 @@ export class WorkspaceManager {
303
546
  return record.syncPromise;
304
547
  }
305
548
  async #performSync(record, force) {
549
+ const previousState = record.state === "syncing" ? "initializing" : record.state;
306
550
  record.state = "syncing";
307
551
  record.lastError = null;
552
+ record.lastWarning = null;
553
+ record.syncStartedAt = new Date().toISOString();
554
+ record.syncPhase = "snapshot";
308
555
  try {
309
556
  const response = await this.#requestTarget(record.targetId, "bridge:workspaceSnapshot", {}, 60000);
310
557
  if (!response.ok)
311
558
  throw new Error(response.error.message);
312
559
  const data = asObject(response.data);
313
560
  const assets = Array.isArray(data.assets) ? data.assets : [];
561
+ if (!this.#acceptSnapshot(record, assets)) {
562
+ record.state = previousState;
563
+ return;
564
+ }
565
+ record.syncPhase = "reconciling";
566
+ record.syncProgress = {
567
+ completed: 0,
568
+ total: assets.filter((asset) => asset.type !== "folder" && asset.file).length,
569
+ assetId: null,
570
+ action: "comparing",
571
+ };
314
572
  await this.#applySnapshot(record, assets, force);
315
573
  record.lastSyncedAt = new Date().toISOString();
316
574
  const entries = Object.values(record.index.entries);
@@ -318,15 +576,62 @@ export class WorkspaceManager {
318
576
  ? "conflict"
319
577
  : entries.some((entry) => entry.status === "local-change")
320
578
  ? "local-change"
321
- : entries.some((entry) => entry.status === "error")
322
- ? "error"
323
- : "synced";
324
- await this.#writeIndex(record);
579
+ : entries.some((entry) => entry.status === "remote-change")
580
+ ? "remote-change"
581
+ : entries.some((entry) => entry.status === "error")
582
+ ? "error"
583
+ : "synced";
584
+ record.syncPhase = "persisting";
585
+ await this.#persist(record);
325
586
  }
326
587
  catch (error) {
327
588
  record.state = "error";
328
589
  record.lastError = error instanceof Error ? error.message : String(error);
329
590
  }
591
+ finally {
592
+ record.syncStartedAt = null;
593
+ record.syncPhase = null;
594
+ record.syncProgress = null;
595
+ }
596
+ }
597
+ #acceptSnapshot(record, assets) {
598
+ const previousIds = Object.keys(record.index.entries);
599
+ if (!previousIds.length) {
600
+ record.pendingShrinkDigest = null;
601
+ record.pendingShrinkCount = 0;
602
+ return true;
603
+ }
604
+ const incomingIds = new Set(assets.map((asset) => String(asset.id)));
605
+ const missing = previousIds.filter((id) => !incomingIds.has(id));
606
+ if (!missing.length) {
607
+ record.pendingShrinkDigest = null;
608
+ record.pendingShrinkCount = 0;
609
+ return true;
610
+ }
611
+ if (!assets.length) {
612
+ record.pendingShrinkDigest = null;
613
+ record.pendingShrinkCount = 0;
614
+ record.lastWarning =
615
+ `Ignored an empty PlayCanvas asset snapshot while ${previousIds.length} indexed assets ` +
616
+ "are present. Waiting for the Editor asset store to finish loading.";
617
+ return false;
618
+ }
619
+ const digest = hashContent([...incomingIds].sort().join("\n"));
620
+ if (record.pendingShrinkDigest === digest)
621
+ record.pendingShrinkCount += 1;
622
+ else {
623
+ record.pendingShrinkDigest = digest;
624
+ record.pendingShrinkCount = 1;
625
+ }
626
+ if (record.pendingShrinkCount < 2) {
627
+ record.lastWarning =
628
+ `Deferred ${missing.length} possible remote deletion${missing.length === 1 ? "" : "s"}; ` +
629
+ "the same non-empty asset snapshot must be observed twice.";
630
+ return false;
631
+ }
632
+ record.pendingShrinkDigest = null;
633
+ record.pendingShrinkCount = 0;
634
+ return true;
330
635
  }
331
636
  async #applySnapshot(record, assets, force) {
332
637
  const folderAssets = assets
@@ -366,9 +671,12 @@ export class WorkspaceManager {
366
671
  remotePath: folderPaths.get(id) || parent,
367
672
  localPath: null,
368
673
  filename: null,
674
+ remoteFileSize: null,
369
675
  remoteFileHash: null,
370
676
  localHash: null,
371
677
  lastSyncedHash: null,
678
+ localFileSize: undefined,
679
+ localMtimeMs: undefined,
372
680
  downloaded: false,
373
681
  status: "indexed",
374
682
  };
@@ -385,14 +693,23 @@ export class WorkspaceManager {
385
693
  remotePath: parent,
386
694
  localPath,
387
695
  filename: remoteFilename,
696
+ remoteFileSize: asset.file?.size ?? null,
388
697
  remoteFileHash: asset.file?.hash || null,
389
698
  localHash: old?.localHash || null,
390
699
  lastSyncedHash: old?.lastSyncedHash || null,
700
+ legacyLastSyncedSha256: old?.legacyLastSyncedSha256,
701
+ pendingRemoteHash: old?.pendingRemoteHash,
702
+ localFileSize: old?.localFileSize,
703
+ localMtimeMs: old?.localMtimeMs,
391
704
  downloaded: old?.downloaded || false,
392
705
  status: old?.status || "indexed",
393
706
  error: old?.error,
394
707
  };
395
708
  next[id] = entry;
709
+ if (asset.file && record.syncProgress) {
710
+ record.syncProgress.assetId = id;
711
+ record.syncProgress.action = "comparing";
712
+ }
396
713
  if (old?.localPath && localPath && old.localPath !== localPath && existsSync(this.#assetPath(record, old.localPath))) {
397
714
  const oldPath = this.#assetPath(record, old.localPath);
398
715
  const newPath = this.#assetPath(record, localPath);
@@ -403,12 +720,18 @@ export class WorkspaceManager {
403
720
  if (asset.type === "script" && localPath) {
404
721
  await this.#reconcileScript(record, entry, old, force);
405
722
  }
723
+ else if (localPath) {
724
+ await this.#reconcileBinary(record, entry, old);
725
+ }
726
+ if (asset.file && record.syncProgress)
727
+ record.syncProgress.completed += 1;
406
728
  }
729
+ const deletionBatch = new Date().toISOString().replaceAll(":", "-");
407
730
  for (const [id, old] of Object.entries(previous)) {
408
731
  if (next[id] || !old.localPath || !existsSync(this.#assetPath(record, old.localPath)))
409
732
  continue;
410
733
  const source = this.#assetPath(record, old.localPath);
411
- const destination = join(record.tmpDirectory, "conflicts", `remote-deleted-${id}-${safeWorkspaceName(basename(old.localPath), `asset-${id}`)}`);
734
+ const destination = join(record.tmpDirectory, "trash", "remote", deletionBatch, `${id}-${safeWorkspaceName(basename(old.localPath), `asset-${id}`)}`);
412
735
  await mkdir(dirname(destination), { recursive: true });
413
736
  await rename(source, destination);
414
737
  }
@@ -423,29 +746,227 @@ export class WorkspaceManager {
423
746
  await rmdir(this.#assetPath(record, join(...folder))).catch(() => undefined);
424
747
  }
425
748
  record.index = {
426
- schemaVersion: 1,
749
+ schemaVersion: 2,
427
750
  projectId: record.projectId,
428
751
  branchId: record.branchId,
429
752
  updatedAt: new Date().toISOString(),
430
753
  entries: next,
431
754
  };
432
755
  }
756
+ async #localFileSnapshot(record, entry, old) {
757
+ if (!entry.localPath)
758
+ return null;
759
+ const path = this.#assetPath(record, entry.localPath);
760
+ if (!existsSync(path))
761
+ return null;
762
+ const info = await stat(path);
763
+ const cachedHash = old?.localHash &&
764
+ old.localFileSize === info.size &&
765
+ old.localMtimeMs === info.mtimeMs
766
+ ? old.localHash
767
+ : null;
768
+ return {
769
+ hash: cachedHash || hashContent(await readFile(path)),
770
+ size: info.size,
771
+ mtimeMs: info.mtimeMs,
772
+ };
773
+ }
774
+ async #recordLocalFile(record, entry, hash) {
775
+ if (!entry.localPath)
776
+ return;
777
+ const info = await stat(this.#assetPath(record, entry.localPath));
778
+ entry.localHash = hash;
779
+ entry.localFileSize = info.size;
780
+ entry.localMtimeMs = info.mtimeMs;
781
+ entry.downloaded = true;
782
+ }
783
+ async #readRemoteAsset(record, entry) {
784
+ const response = await this.#requestTarget(record.targetId, "bridge:readAssetFile", { assetId: entry.id }, 120000);
785
+ if (!response.ok)
786
+ throw new Error(response.error.message);
787
+ const data = asObject(response.data);
788
+ const base64 = typeof data.base64 === "string" ? data.base64 : "";
789
+ if (!base64)
790
+ throw new Error(`Asset ${entry.id} returned no file data.`);
791
+ const content = Buffer.from(base64, "base64");
792
+ const hash = hashContent(content);
793
+ if (entry.remoteFileHash && entry.remoteFileHash !== hash) {
794
+ throw new Error(`Asset ${entry.id} changed while it was being downloaded: ` +
795
+ `expected ${entry.remoteFileHash}, received ${hash}.`);
796
+ }
797
+ entry.remoteFileHash = hash;
798
+ return { content, hash };
799
+ }
800
+ async #downloadAsset(record, entry) {
801
+ if (!entry.localPath)
802
+ throw new Error(`Asset ${entry.id} has no downloadable file.`);
803
+ if (record.syncProgress) {
804
+ record.syncProgress.assetId = entry.id;
805
+ record.syncProgress.action = "downloading";
806
+ }
807
+ const remote = await this.#readRemoteAsset(record, entry);
808
+ const path = this.#assetPath(record, entry.localPath);
809
+ await atomicWrite(path, remote.content);
810
+ await this.#recordLocalFile(record, entry, remote.hash);
811
+ entry.lastSyncedHash = remote.hash;
812
+ entry.status = "synced";
813
+ delete entry.legacyLastSyncedSha256;
814
+ delete entry.pendingRemoteHash;
815
+ delete entry.error;
816
+ return { path, size: remote.content.byteLength, hash: remote.hash };
817
+ }
818
+ async #uploadBinary(record, entry, content, localHash) {
819
+ if (record.syncProgress) {
820
+ record.syncProgress.assetId = entry.id;
821
+ record.syncProgress.action = "uploading";
822
+ }
823
+ const response = await this.#requestTarget(record.targetId, "bridge:writeAssetFile", {
824
+ assetId: entry.id,
825
+ filename: entry.filename || entry.name,
826
+ base64: content.toString("base64"),
827
+ }, 120000);
828
+ if (!response.ok) {
829
+ entry.status = "local-change";
830
+ entry.error = response.error.message;
831
+ return;
832
+ }
833
+ await this.#recordLocalFile(record, entry, localHash);
834
+ entry.pendingRemoteHash = localHash;
835
+ entry.status = "local-change";
836
+ delete entry.legacyLastSyncedSha256;
837
+ entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
838
+ }
839
+ async #writeBinaryConflict(record, entry, remoteContent, localHash) {
840
+ if (!entry.localPath)
841
+ return;
842
+ if (record.syncProgress) {
843
+ record.syncProgress.assetId = entry.id;
844
+ record.syncProgress.action = "conflict";
845
+ }
846
+ const conflictBase = join(record.tmpDirectory, "conflicts", `${entry.id}-${safeWorkspaceName(entry.filename || entry.name, `asset-${entry.id}`)}`);
847
+ await mkdir(dirname(conflictBase), { recursive: true });
848
+ await copyFile(this.#assetPath(record, entry.localPath), `${conflictBase}.local`);
849
+ await atomicWrite(`${conflictBase}.remote`, remoteContent);
850
+ entry.localHash = localHash;
851
+ entry.downloaded = true;
852
+ entry.status = "conflict";
853
+ entry.error =
854
+ `Local and remote asset files changed since the last sync. See ` +
855
+ `${relative(record.directory, conflictBase)}.*`;
856
+ }
857
+ async #reconcileBinary(record, entry, old) {
858
+ const local = await this.#localFileSnapshot(record, entry, old);
859
+ const baseline = old?.lastSyncedHash || null;
860
+ const advertisedRemoteHash = entry.remoteFileHash;
861
+ if (!local) {
862
+ await this.#downloadAsset(record, entry);
863
+ return;
864
+ }
865
+ entry.localHash = local.hash;
866
+ entry.localFileSize = local.size;
867
+ entry.localMtimeMs = local.mtimeMs;
868
+ entry.downloaded = true;
869
+ if (advertisedRemoteHash && local.hash === advertisedRemoteHash) {
870
+ entry.lastSyncedHash = local.hash;
871
+ entry.status = "synced";
872
+ delete entry.legacyLastSyncedSha256;
873
+ delete entry.pendingRemoteHash;
874
+ delete entry.error;
875
+ return;
876
+ }
877
+ if (old?.pendingRemoteHash &&
878
+ local.hash === old.pendingRemoteHash &&
879
+ advertisedRemoteHash !== old.pendingRemoteHash) {
880
+ entry.pendingRemoteHash = old.pendingRemoteHash;
881
+ entry.status = "local-change";
882
+ entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
883
+ return;
884
+ }
885
+ if (baseline && local.hash === baseline && advertisedRemoteHash !== baseline) {
886
+ await this.#downloadAsset(record, entry);
887
+ return;
888
+ }
889
+ if (baseline && advertisedRemoteHash === baseline && local.hash !== baseline) {
890
+ await this.#uploadBinary(record, entry, await readFile(this.#assetPath(record, entry.localPath)), local.hash);
891
+ return;
892
+ }
893
+ const remote = await this.#readRemoteAsset(record, entry);
894
+ if (remote.hash === local.hash) {
895
+ entry.lastSyncedHash = local.hash;
896
+ entry.status = "synced";
897
+ delete entry.legacyLastSyncedSha256;
898
+ delete entry.pendingRemoteHash;
899
+ delete entry.error;
900
+ return;
901
+ }
902
+ if (baseline && remote.hash === baseline) {
903
+ await this.#uploadBinary(record, entry, await readFile(this.#assetPath(record, entry.localPath)), local.hash);
904
+ return;
905
+ }
906
+ if (baseline && local.hash === baseline) {
907
+ await atomicWrite(this.#assetPath(record, entry.localPath), remote.content);
908
+ await this.#recordLocalFile(record, entry, remote.hash);
909
+ entry.lastSyncedHash = remote.hash;
910
+ entry.status = "synced";
911
+ delete entry.pendingRemoteHash;
912
+ delete entry.error;
913
+ return;
914
+ }
915
+ if (old?.status === "conflict" && old.localHash === local.hash && old.remoteFileHash === remote.hash) {
916
+ entry.status = "conflict";
917
+ entry.error = old.error;
918
+ return;
919
+ }
920
+ await this.#writeBinaryConflict(record, entry, remote.content, local.hash);
921
+ }
433
922
  async #reconcileScript(record, entry, old, force) {
434
923
  if (!entry.localPath)
435
924
  return;
436
925
  const path = this.#assetPath(record, entry.localPath);
437
- const localContent = existsSync(path) ? await readFile(path, "utf8") : null;
438
- const localHash = localContent === null ? null : hashContent(localContent);
926
+ const localBytes = existsSync(path) ? await readFile(path) : null;
927
+ const localContent = localBytes?.toString("utf8") ?? null;
928
+ const localHash = localBytes === null ? null : hashContent(localBytes);
439
929
  const baseline = old?.lastSyncedHash || null;
930
+ const advertisedRemoteHash = entry.remoteFileHash;
931
+ if (localContent !== null && advertisedRemoteHash && localHash === advertisedRemoteHash) {
932
+ entry.localHash = localHash;
933
+ entry.lastSyncedHash = localHash;
934
+ entry.downloaded = true;
935
+ entry.status = "synced";
936
+ delete entry.legacyLastSyncedSha256;
937
+ delete entry.pendingRemoteHash;
938
+ delete entry.error;
939
+ return;
940
+ }
941
+ if (localContent !== null &&
942
+ old?.pendingRemoteHash &&
943
+ localHash === old.pendingRemoteHash &&
944
+ advertisedRemoteHash !== old.pendingRemoteHash) {
945
+ entry.localHash = localHash;
946
+ entry.pendingRemoteHash = old.pendingRemoteHash;
947
+ entry.downloaded = true;
948
+ entry.status = "local-change";
949
+ entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
950
+ return;
951
+ }
440
952
  const localChanged = localHash !== null && localHash !== baseline;
441
- const remoteMetadataChanged = !old || old.remoteFileHash !== entry.remoteFileHash;
442
- if (!force && localContent !== null && !localChanged && !remoteMetadataChanged) {
953
+ const remoteMetadataChanged = !old || old.remoteFileHash !== advertisedRemoteHash;
954
+ if (!force && localContent !== null && baseline && !localChanged && !remoteMetadataChanged) {
443
955
  entry.localHash = localHash;
444
956
  entry.lastSyncedHash = baseline;
445
957
  entry.downloaded = true;
446
958
  entry.status = "synced";
959
+ delete entry.error;
960
+ return;
961
+ }
962
+ if (localContent !== null && baseline && advertisedRemoteHash === baseline && localChanged) {
963
+ await this.#uploadScript(record, entry, localContent, localHash);
447
964
  return;
448
965
  }
966
+ if (record.syncProgress) {
967
+ record.syncProgress.assetId = entry.id;
968
+ record.syncProgress.action = "downloading";
969
+ }
449
970
  const response = await this.#requestTarget(record.targetId, "bridge:readAssetText", { assetId: entry.id }, 30000);
450
971
  if (!response.ok) {
451
972
  entry.status = "error";
@@ -455,51 +976,108 @@ export class WorkspaceManager {
455
976
  const data = asObject(response.data);
456
977
  const remoteContent = typeof data.text === "string" ? data.text : "";
457
978
  const remoteHash = hashContent(remoteContent);
458
- if (localContent === null || localHash === baseline) {
979
+ if (advertisedRemoteHash && advertisedRemoteHash !== remoteHash) {
980
+ entry.localHash = localHash;
981
+ entry.status = "error";
982
+ entry.error =
983
+ `Remote script ${entry.id} changed while it was being read: ` +
984
+ `expected ${advertisedRemoteHash}, received ${remoteHash}.`;
985
+ return;
986
+ }
987
+ entry.remoteFileHash = remoteHash;
988
+ if (localContent === null) {
459
989
  await atomicWrite(path, remoteContent);
460
990
  entry.localHash = remoteHash;
461
991
  entry.lastSyncedHash = remoteHash;
462
992
  entry.downloaded = true;
463
993
  entry.status = "synced";
994
+ delete entry.legacyLastSyncedSha256;
995
+ delete entry.pendingRemoteHash;
464
996
  delete entry.error;
465
997
  return;
466
998
  }
467
- if (!baseline) {
468
- if (localHash === remoteHash) {
469
- entry.localHash = localHash;
470
- entry.lastSyncedHash = localHash;
999
+ if (!localHash)
1000
+ throw new Error(`Could not hash local script ${entry.id}.`);
1001
+ if (localHash === remoteHash) {
1002
+ entry.localHash = localHash;
1003
+ entry.lastSyncedHash = localHash;
1004
+ entry.downloaded = true;
1005
+ entry.status = "synced";
1006
+ delete entry.legacyLastSyncedSha256;
1007
+ delete entry.pendingRemoteHash;
1008
+ delete entry.error;
1009
+ return;
1010
+ }
1011
+ if (baseline) {
1012
+ if (localHash === baseline) {
1013
+ await atomicWrite(path, remoteContent);
1014
+ entry.localHash = remoteHash;
1015
+ entry.lastSyncedHash = remoteHash;
471
1016
  entry.downloaded = true;
472
1017
  entry.status = "synced";
1018
+ delete entry.legacyLastSyncedSha256;
1019
+ delete entry.pendingRemoteHash;
1020
+ delete entry.error;
1021
+ return;
473
1022
  }
474
- else {
475
- await this.#writeConflict(record, entry, localContent, remoteContent);
1023
+ if (remoteHash === baseline) {
1024
+ await this.#uploadScript(record, entry, localContent, localHash);
1025
+ return;
476
1026
  }
1027
+ await this.#writeConflict(record, entry, localContent, remoteContent);
477
1028
  return;
478
1029
  }
479
- if (remoteHash === baseline || remoteHash === localHash) {
480
- if (remoteHash !== localHash) {
481
- const writeResponse = await this.#requestTarget(record.targetId, "bridge:writeScriptText", { assetId: entry.id, text: localContent }, 60000);
482
- if (!writeResponse.ok) {
483
- entry.localHash = localHash;
484
- entry.status = "local-change";
485
- entry.error = writeResponse.error.message;
486
- return;
487
- }
1030
+ const legacyBaseline = old?.legacyLastSyncedSha256;
1031
+ if (legacyBaseline && localBytes) {
1032
+ const localChangedFromLegacy = hashLegacyContent(localBytes) !== legacyBaseline;
1033
+ const remoteChangedFromLegacy = hashLegacyContent(remoteContent) !== legacyBaseline;
1034
+ if (!localChangedFromLegacy) {
1035
+ await atomicWrite(path, remoteContent);
1036
+ entry.localHash = remoteHash;
1037
+ entry.lastSyncedHash = remoteHash;
1038
+ entry.downloaded = true;
1039
+ entry.status = "synced";
1040
+ delete entry.legacyLastSyncedSha256;
1041
+ delete entry.pendingRemoteHash;
1042
+ delete entry.error;
1043
+ return;
1044
+ }
1045
+ if (!remoteChangedFromLegacy) {
1046
+ await this.#uploadScript(record, entry, localContent, localHash);
1047
+ return;
488
1048
  }
1049
+ }
1050
+ await this.#writeConflict(record, entry, localContent, remoteContent);
1051
+ }
1052
+ async #uploadScript(record, entry, localContent, localHash) {
1053
+ if (record.syncProgress) {
1054
+ record.syncProgress.assetId = entry.id;
1055
+ record.syncProgress.action = "uploading";
1056
+ }
1057
+ const writeResponse = await this.#requestTarget(record.targetId, "bridge:writeScriptText", { assetId: entry.id, text: localContent }, 60000);
1058
+ if (!writeResponse.ok) {
489
1059
  entry.localHash = localHash;
490
- entry.lastSyncedHash = localHash;
491
- entry.downloaded = true;
492
- entry.status = "synced";
493
- delete entry.error;
1060
+ entry.status = "local-change";
1061
+ entry.error = writeResponse.error.message;
494
1062
  return;
495
1063
  }
496
- await this.#writeConflict(record, entry, localContent, remoteContent);
1064
+ entry.localHash = localHash;
1065
+ entry.pendingRemoteHash = localHash;
1066
+ entry.downloaded = true;
1067
+ entry.status = "local-change";
1068
+ delete entry.legacyLastSyncedSha256;
1069
+ entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
497
1070
  }
498
1071
  async #writeConflict(record, entry, localContent, remoteContent) {
1072
+ if (record.syncProgress) {
1073
+ record.syncProgress.assetId = entry.id;
1074
+ record.syncProgress.action = "conflict";
1075
+ }
499
1076
  const conflictBase = join(record.tmpDirectory, "conflicts", `${entry.id}-${safeWorkspaceName(entry.filename || entry.name, `script-${entry.id}`)}`);
500
1077
  await atomicWrite(`${conflictBase}.local`, localContent);
501
1078
  await atomicWrite(`${conflictBase}.remote`, remoteContent);
502
1079
  entry.localHash = hashContent(localContent);
1080
+ entry.downloaded = true;
503
1081
  entry.status = "conflict";
504
1082
  entry.error = `Local and remote script changed since the last sync. See ${relative(record.directory, conflictBase)}.*`;
505
1083
  }
@@ -521,12 +1099,21 @@ export class WorkspaceManager {
521
1099
  connected: record.connected,
522
1100
  lastSyncedAt: record.lastSyncedAt,
523
1101
  lastError: record.lastError,
1102
+ lastWarning: record.lastWarning,
1103
+ progress: record.syncPhase && record.syncStartedAt
1104
+ ? {
1105
+ phase: record.syncPhase,
1106
+ startedAt: record.syncStartedAt,
1107
+ ...(record.syncProgress || {}),
1108
+ }
1109
+ : null,
524
1110
  counts: {
525
1111
  assets: entries.filter((entry) => entry.type !== "folder").length,
526
1112
  folders: entries.filter((entry) => entry.type === "folder").length,
527
1113
  scripts: scripts.length,
528
1114
  scriptsSynced: scripts.filter((entry) => entry.status === "synced").length,
529
- localChanges: scripts.filter((entry) => entry.status === "local-change").length,
1115
+ localChanges: entries.filter((entry) => entry.status === "local-change").length,
1116
+ remoteChanges: entries.filter((entry) => entry.status === "remote-change").length,
530
1117
  conflicts: entries.filter((entry) => entry.status === "conflict").length,
531
1118
  lazyAssets: downloadable.filter((entry) => !entry.downloaded).length,
532
1119
  downloadedAssets: downloadable.filter((entry) => entry.downloaded).length,