playcanvas-agent-bridge-cli 0.3.0 → 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/extension/main.js CHANGED
@@ -7,7 +7,12 @@
7
7
 
8
8
  const MAX_LOGS = 500;
9
9
  const capturedLogs = [];
10
+ const daemonWaiters = new Map();
10
11
  let nextLogSeq = 1;
12
+ let builderPanel = null;
13
+ let builderRefreshTimer = null;
14
+ let selectedTemplateId = null;
15
+ let selectedTemplateAsset = null;
11
16
 
12
17
  function formatLogArg(value) {
13
18
  if (typeof value === "string") return value;
@@ -145,11 +150,14 @@
145
150
  if (editorSummary) return editorSummary;
146
151
 
147
152
  if (current instanceof Error) {
148
- return {
153
+ const normalized = {
149
154
  name: current.name,
150
155
  message: current.message,
151
156
  stack: current.stack
152
157
  };
158
+ if (typeof current.code === "string") normalized.code = current.code;
159
+ if (current.details !== undefined) normalized.details = normalize(current.details, depth + 1);
160
+ return normalized;
153
161
  }
154
162
 
155
163
  if (depth >= settings.maxDepth) {
@@ -188,31 +196,197 @@
188
196
  return "playcanvas";
189
197
  }
190
198
 
191
- function getRuntimeApp() {
199
+ function getAppCanvas(app) {
200
+ return (
201
+ (app && app.graphicsDevice && app.graphicsDevice.canvas) ||
202
+ (app && app.canvas) ||
203
+ null
204
+ );
205
+ }
206
+
207
+ function getPrimaryCanvas(app) {
208
+ return getAppCanvas(app) || document.querySelector("canvas");
209
+ }
210
+
211
+ function isVisibleElement(element) {
212
+ if (!element) return false;
213
+ const style = typeof window.getComputedStyle === "function"
214
+ ? window.getComputedStyle(element)
215
+ : null;
216
+ if (
217
+ style &&
218
+ (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0)
219
+ ) {
220
+ return false;
221
+ }
222
+ if (typeof element.getBoundingClientRect !== "function") return true;
223
+ const rect = element.getBoundingClientRect();
224
+ return rect.width > 0 && rect.height > 0;
225
+ }
226
+
227
+ function runtimeRegistryEntries(registry) {
228
+ if (!registry) return [];
229
+ if (typeof registry.entries === "function") {
230
+ try {
231
+ return Array.from(registry.entries());
232
+ } catch {
233
+ // Fall through to object entries.
234
+ }
235
+ }
236
+ if (Array.isArray(registry)) return registry.map((app, index) => [String(index), app]);
237
+ if (typeof registry === "object") return Object.entries(registry);
238
+ return [];
239
+ }
240
+
241
+ function isLiveRuntimeApp(app) {
242
+ return Boolean(app && app.root);
243
+ }
244
+
245
+ function resolveRuntimeApp() {
246
+ const explicitCandidates = [];
247
+ const fallbackCandidates = [];
248
+ const seen = new Set();
249
+ const add = (list, app, source) => {
250
+ if (!isLiveRuntimeApp(app) || seen.has(app)) return;
251
+ seen.add(app);
252
+ list.push({ app, source, order: list.length });
253
+ };
254
+ const callGetter = (list, owner, id, source) => {
255
+ try {
256
+ if (owner && typeof owner.getApplication === "function") {
257
+ add(list, owner.getApplication(id), source);
258
+ }
259
+ } catch {
260
+ // Continue through the compatibility fallbacks.
261
+ }
262
+ };
263
+
264
+ const pc = window.pc;
192
265
  try {
193
- if (
194
- window.pc &&
195
- window.pc.Application &&
196
- typeof window.pc.Application.getApplication === "function"
197
- ) {
198
- const app = window.pc.Application.getApplication();
199
- if (app) return app;
266
+ if (window.editor && typeof window.editor.call === "function") {
267
+ add(explicitCandidates, window.editor.call("viewport:app"), "editor.call(viewport:app)");
200
268
  }
201
269
  } catch {
202
- // Fall through to common global app locations.
270
+ // Launch can expose only a partial Editor event bus during startup.
271
+ }
272
+ const canvasIds = [
273
+ "application-canvas",
274
+ ...Array.from(document.querySelectorAll("canvas"))
275
+ .map((canvas) => canvas && canvas.id)
276
+ .filter((id) => id && id !== "application-canvas")
277
+ ];
278
+ for (const id of canvasIds) {
279
+ callGetter(
280
+ explicitCandidates,
281
+ pc && pc.AppBase,
282
+ id,
283
+ "pc.AppBase.getApplication(" + id + ")"
284
+ );
285
+ }
286
+ for (const [owner, label] of [
287
+ [pc && pc.AppBase, "pc.AppBase._applications"],
288
+ [pc && pc.Application, "pc.Application._applications"]
289
+ ]) {
290
+ for (const id of canvasIds) {
291
+ const match = runtimeRegistryEntries(owner && owner._applications)
292
+ .find(([key]) => String(key) === String(id));
293
+ if (match) add(explicitCandidates, match[1], label + "[" + id + "]");
294
+ }
295
+ }
296
+ for (const id of canvasIds) {
297
+ callGetter(
298
+ explicitCandidates,
299
+ pc && pc.Application,
300
+ id,
301
+ "pc.Application.getApplication(" + id + ")"
302
+ );
203
303
  }
204
304
 
205
- if (window.app && window.app.graphicsDevice) return window.app;
206
- if (window.pc && window.pc.app && window.pc.app.graphicsDevice) return window.pc.app;
207
- return null;
208
- }
305
+ if (explicitCandidates.length) {
306
+ const selected = explicitCandidates[0];
307
+ return {
308
+ ...selected,
309
+ canvas: getAppCanvas(selected.app),
310
+ rootChildCount: selected.app.root && Array.isArray(selected.app.root.children)
311
+ ? selected.app.root.children.length
312
+ : 0,
313
+ score: null
314
+ };
315
+ }
209
316
 
210
- function getPrimaryCanvas(app) {
211
- return (
212
- (app && app.graphicsDevice && app.graphicsDevice.canvas) ||
213
- (app && app.canvas) ||
214
- document.querySelector("canvas")
317
+ callGetter(fallbackCandidates, pc && pc.AppBase, undefined, "pc.AppBase.getApplication()");
318
+ callGetter(fallbackCandidates, pc && pc.Application, undefined, "pc.Application.getApplication()");
319
+
320
+ for (const [owner, label] of [
321
+ [pc && pc.AppBase, "pc.AppBase._applications"],
322
+ [pc && pc.Application, "pc.Application._applications"]
323
+ ]) {
324
+ for (const [key, app] of runtimeRegistryEntries(owner && owner._applications)) {
325
+ add(fallbackCandidates, app, label + "[" + key + "]");
326
+ }
327
+ }
328
+
329
+ add(fallbackCandidates, window.app, "window.app");
330
+ add(fallbackCandidates, pc && pc.app, "pc.app");
331
+
332
+ const ownedMatches = fallbackCandidates.filter((candidate) => {
333
+ const canvas = getAppCanvas(candidate.app);
334
+ return Boolean(canvas && canvas.id && canvasIds.includes(canvas.id));
335
+ });
336
+ const mainCanvasMatches = ownedMatches.filter(
337
+ (candidate) => getAppCanvas(candidate.app).id === "application-canvas"
215
338
  );
339
+ const selected = mainCanvasMatches.length === 1
340
+ ? mainCanvasMatches[0]
341
+ : ownedMatches.length === 1
342
+ ? ownedMatches[0]
343
+ : fallbackCandidates.length === 1
344
+ ? fallbackCandidates[0]
345
+ : null;
346
+ if (selected) {
347
+ return {
348
+ ...selected,
349
+ canvas: getAppCanvas(selected.app),
350
+ rootChildCount: Array.isArray(selected.app.root.children)
351
+ ? selected.app.root.children.length
352
+ : 0,
353
+ ambiguous: false,
354
+ candidateSources: fallbackCandidates.map((candidate) => candidate.source)
355
+ };
356
+ }
357
+
358
+ return {
359
+ app: null,
360
+ source: null,
361
+ canvas: null,
362
+ rootChildCount: 0,
363
+ ambiguous: fallbackCandidates.length > 1,
364
+ candidateSources: fallbackCandidates.map((candidate) => candidate.source)
365
+ };
366
+ }
367
+
368
+ function getScriptTypeCount(app) {
369
+ try {
370
+ return app && app.scripts && typeof app.scripts.list === "function"
371
+ ? app.scripts.list().length
372
+ : null;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+
378
+ function getRuntimeApp() {
379
+ return resolveRuntimeApp().app;
380
+ }
381
+
382
+ function isLaunchSplashVisible() {
383
+ const selectors = [
384
+ "#application-splash-wrapper",
385
+ "#application-splash",
386
+ ".application-splash-wrapper",
387
+ ".application-splash"
388
+ ];
389
+ return selectors.some((selector) => isVisibleElement(document.querySelector(selector)));
216
390
  }
217
391
 
218
392
  function getSceneIdFromUrl() {
@@ -231,10 +405,47 @@
231
405
  const config = window.config || {};
232
406
  const kind = getTargetKind();
233
407
  const editorReady = Boolean(window.editor && window.editor.api && window.editor.api.globals);
234
- const app = getRuntimeApp();
408
+ const runtime = resolveRuntimeApp();
409
+ const app = runtime.app;
235
410
  const canvasCount = document.querySelectorAll("canvas").length;
236
- const launchReady = kind === "launch" && document.readyState !== "loading";
237
- const ready = editorReady || launchReady;
411
+ const pageReady = document.readyState !== "loading";
412
+ const visibilityState = document.visibilityState || "unknown";
413
+ const runtimeCreated = Boolean(app && app.root);
414
+ const ownedCanvas = getAppCanvas(app);
415
+ const graphicsContextLost = Boolean(app && app.graphicsDevice && app.graphicsDevice.contextLost);
416
+ const graphicsReady = Boolean(
417
+ runtimeCreated && app.graphicsDevice && ownedCanvas && !graphicsContextLost
418
+ );
419
+ const rootChildren = app && app.root && Array.isArray(app.root.children)
420
+ ? app.root.children
421
+ : [];
422
+ const sceneRoot = app && app.scene ? app.scene.root : null;
423
+ const sceneLoaded = Boolean(
424
+ graphicsReady && rootChildren.length > 0 && (!sceneRoot || rootChildren.includes(sceneRoot))
425
+ );
426
+ const runtimeFrame = app && Number.isFinite(Number(app.frame)) ? Number(app.frame) : null;
427
+ const runtimeStarted = Boolean(sceneLoaded && runtimeFrame !== null && runtimeFrame > 0);
428
+ const scriptsReady = runtimeStarted;
429
+ const scriptTypeCount = getScriptTypeCount(app);
430
+ const splashVisible = kind === "launch" && isLaunchSplashVisible();
431
+ const lifecycleReady = Boolean(
432
+ pageReady && runtimeCreated && graphicsReady && sceneLoaded && runtimeStarted && !splashVisible
433
+ );
434
+ const readinessBlockers = [];
435
+ if (kind === "launch") {
436
+ if (!pageReady) readinessBlockers.push("page-loading");
437
+ if (visibilityState !== "visible") readinessBlockers.push("tab-hidden");
438
+ if (!runtimeCreated) readinessBlockers.push("runtime-not-created");
439
+ if (runtimeCreated && graphicsContextLost) readinessBlockers.push("graphics-context-lost");
440
+ if (runtimeCreated && !graphicsReady && !graphicsContextLost) {
441
+ readinessBlockers.push("graphics-not-ready");
442
+ }
443
+ if (runtimeCreated && !sceneLoaded) readinessBlockers.push("scene-not-loaded");
444
+ if (sceneLoaded && !runtimeStarted) readinessBlockers.push("runtime-not-started");
445
+ if (splashVisible) readinessBlockers.push("splash-visible");
446
+ }
447
+ const launchReady = kind === "launch" && lifecycleReady && visibilityState === "visible";
448
+ const ready = kind === "launch" ? launchReady : editorReady;
238
449
  return {
239
450
  kind,
240
451
  url: location.href,
@@ -243,16 +454,47 @@
243
454
  hasEditor: Boolean(window.editor),
244
455
  hasPc: Boolean(window.pc),
245
456
  hasRuntimeApp: Boolean(app),
457
+ runtimeAppSource: runtime.source || undefined,
458
+ runtimeAppAmbiguous: kind === "launch" ? Boolean(runtime.ambiguous) : undefined,
459
+ runtimeAppCandidateSources: kind === "launch" ? runtime.candidateSources || [] : undefined,
460
+ runtimeCanvasId: app && runtime.canvas && runtime.canvas.id
461
+ ? String(runtime.canvas.id)
462
+ : undefined,
463
+ engineVersion: kind === "launch" && window.pc && window.pc.version
464
+ ? String(window.pc.version)
465
+ : undefined,
466
+ readinessMode: kind === "launch" ? "heuristic" : undefined,
467
+ pageReady: kind === "launch" ? pageReady : undefined,
468
+ visibilityState: kind === "launch" ? visibilityState : undefined,
469
+ lifecycleReady: kind === "launch" ? lifecycleReady : undefined,
470
+ runtimeCreated: kind === "launch" ? runtimeCreated : undefined,
471
+ graphicsReady: kind === "launch" ? graphicsReady : undefined,
472
+ graphicsContextLost: kind === "launch" ? graphicsContextLost : undefined,
473
+ runtimeStarted: kind === "launch" ? runtimeStarted : undefined,
474
+ runtimeFrame: kind === "launch" ? runtimeFrame : undefined,
475
+ sceneLoaded: kind === "launch" ? sceneLoaded : undefined,
476
+ scriptsReady: kind === "launch" ? scriptsReady : undefined,
477
+ scriptTypeCount: kind === "launch" ? scriptTypeCount : undefined,
478
+ splashVisible: kind === "launch" ? splashVisible : undefined,
479
+ rootChildCount: kind === "launch" ? runtime.rootChildCount : undefined,
480
+ readinessBlockers: kind === "launch" ? readinessBlockers : undefined,
246
481
  canvasCount,
247
482
  projectId: config.project && config.project.id ? String(config.project.id) : undefined,
483
+ projectName: config.project && config.project.name ? String(config.project.name) : undefined,
248
484
  sceneId:
249
485
  (config.scene && config.scene.id ? String(config.scene.id) : undefined) ||
250
486
  getSceneIdFromUrl(),
487
+ sceneName: config.scene && config.scene.name ? String(config.scene.name) : undefined,
251
488
  branchId:
252
489
  (config.self && config.self.branch && config.self.branch.id
253
490
  ? String(config.self.branch.id)
254
491
  : undefined) ||
255
- (config.branch && config.branch.id ? String(config.branch.id) : undefined)
492
+ (config.branch && config.branch.id ? String(config.branch.id) : undefined),
493
+ branchName:
494
+ (config.self && config.self.branch && config.self.branch.name
495
+ ? String(config.self.branch.name)
496
+ : undefined) ||
497
+ (config.branch && config.branch.name ? String(config.branch.name) : undefined)
256
498
  };
257
499
  }
258
500
 
@@ -328,6 +570,297 @@
328
570
  return bytes;
329
571
  }
330
572
 
573
+ function base64FromBytes(bytes) {
574
+ const chunkSize = 0x8000;
575
+ let binary = "";
576
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
577
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
578
+ }
579
+ return btoa(binary);
580
+ }
581
+
582
+ function requireEditorAsset(assetId) {
583
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
584
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
585
+ }
586
+ const asset = window.editor.api.globals.assets.get(Number(assetId));
587
+ if (!asset) throw new Error("Asset not found: " + assetId);
588
+ return asset;
589
+ }
590
+
591
+ async function fetchAssetFile(asset) {
592
+ const filename = asset.get("file.filename") || asset.get("name");
593
+ if (!filename) throw new Error("Asset has no downloadable file: " + asset.get("id"));
594
+ const branchId =
595
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
596
+ (window.config && window.config.branch && window.config.branch.id);
597
+ const query = branchId ? "?branchId=" + encodeURIComponent(String(branchId)) : "";
598
+ const headers = {};
599
+ const accessToken = window.editor.api.globals.accessToken;
600
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
601
+ const response = await fetch(
602
+ "/api/assets/" + encodeURIComponent(String(asset.get("id"))) +
603
+ "/file/" + encodeURIComponent(String(filename)) + query,
604
+ { headers }
605
+ );
606
+ if (!response.ok) {
607
+ const body = await response.text().catch(() => "");
608
+ throw new Error(body || "Failed to download asset " + asset.get("id") + ".");
609
+ }
610
+ return { response, filename };
611
+ }
612
+
613
+ function workspaceSnapshot() {
614
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
615
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
616
+ }
617
+ return {
618
+ assets: window.editor.api.globals.assets.list().map(readAsset)
619
+ };
620
+ }
621
+
622
+ async function readAssetText(params) {
623
+ const asset = requireEditorAsset(params.assetId);
624
+ if (asset.get("type") !== "script") {
625
+ throw new Error("Asset is not a script: " + params.assetId);
626
+ }
627
+ const { response, filename } = await fetchAssetFile(asset);
628
+ return {
629
+ assetId: String(asset.get("id")),
630
+ filename,
631
+ text: await response.text()
632
+ };
633
+ }
634
+
635
+ async function readAssetFile(params) {
636
+ const asset = requireEditorAsset(params.assetId);
637
+ const { response, filename } = await fetchAssetFile(asset);
638
+ const bytes = new Uint8Array(await response.arrayBuffer());
639
+ return {
640
+ assetId: String(asset.get("id")),
641
+ filename,
642
+ mime: response.headers.get("content-type") || "application/octet-stream",
643
+ size: bytes.length,
644
+ base64: base64FromBytes(bytes)
645
+ };
646
+ }
647
+
648
+ async function readAssetResource(params) {
649
+ const asset = requireEditorAsset(params.assetId);
650
+ const file = plainAssetJson(asset)?.file || {};
651
+ const allowedUrls = new Set();
652
+ if (file.url) allowedUrls.add(String(file.url));
653
+ for (const variant of Object.values(file.variants || {})) {
654
+ if (variant && variant.url) allowedUrls.add(String(variant.url));
655
+ }
656
+ if (asset.get("type") === "font" && file.url) {
657
+ const mapCount = Number(plainAssetJson(asset)?.data?.info?.maps?.length || 0);
658
+ for (let index = 1; index < mapCount; index += 1) {
659
+ allowedUrls.add(String(file.url).replace(/(\.[^.]*)$/, `${index}$1`));
660
+ }
661
+ }
662
+ const url = String(params.url || "");
663
+ if (!url || !allowedUrls.has(url)) {
664
+ throw new Error("Requested URL does not belong to asset " + params.assetId + ".");
665
+ }
666
+ const resolvedUrl = new URL(url, location.href);
667
+ const headers = {};
668
+ const accessToken = window.editor.api.globals.accessToken;
669
+ const playCanvasHost =
670
+ resolvedUrl.hostname === "playcanvas.com" || resolvedUrl.hostname.endsWith(".playcanvas.com");
671
+ if (accessToken && playCanvasHost) headers.Authorization = "Bearer " + accessToken;
672
+ const response = await fetch(resolvedUrl.href, { headers });
673
+ if (!response.ok) {
674
+ const body = await response.text().catch(() => "");
675
+ throw new Error(body || "Failed to download asset resource " + params.assetId + ".");
676
+ }
677
+ const bytes = new Uint8Array(await response.arrayBuffer());
678
+ return {
679
+ assetId: String(asset.get("id")),
680
+ mime: response.headers.get("content-type") || "application/octet-stream",
681
+ size: bytes.length,
682
+ base64: base64FromBytes(bytes)
683
+ };
684
+ }
685
+
686
+ async function writeAssetFile(params) {
687
+ const asset = requireEditorAsset(params.assetId);
688
+ if (asset.get("type") === "script") {
689
+ throw new Error("Use the script text writer for script assets: " + params.assetId);
690
+ }
691
+ const filename = String(
692
+ params.filename || asset.get("file.filename") || asset.get("name") || "asset.bin"
693
+ );
694
+ const bytes = bytesFromBase64(String(params.base64 || ""));
695
+ const form = new FormData();
696
+ form.append("filename", filename);
697
+ form.append(
698
+ "file",
699
+ new Blob([bytes], { type: params.mime || "application/octet-stream" }),
700
+ filename
701
+ );
702
+ const branchId =
703
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
704
+ (window.config && window.config.branch && window.config.branch.id);
705
+ if (branchId) form.append("branchId", String(branchId));
706
+ const headers = {};
707
+ const accessToken = window.editor.api.globals.accessToken;
708
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
709
+ const response = await fetch("/api/assets/" + encodeURIComponent(String(asset.get("id"))), {
710
+ method: "PUT",
711
+ headers,
712
+ body: form
713
+ });
714
+ const body = await response.json().catch(() => ({}));
715
+ if (!response.ok || body.error) {
716
+ throw new Error(body.error || "Failed to update asset file.");
717
+ }
718
+ return {
719
+ assetId: String(asset.get("id")),
720
+ filename,
721
+ size: bytes.length,
722
+ response: body
723
+ };
724
+ }
725
+
726
+ async function writeScriptText(params) {
727
+ const asset = requireEditorAsset(params.assetId);
728
+ if (asset.get("type") !== "script") {
729
+ throw new Error("Asset is not a script: " + params.assetId);
730
+ }
731
+ const filename = asset.get("file.filename") || asset.get("name");
732
+ const form = new FormData();
733
+ form.append("filename", filename);
734
+ form.append("file", new Blob([String(params.text || "")], { type: "text/javascript" }), filename);
735
+ const branchId =
736
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
737
+ (window.config && window.config.branch && window.config.branch.id);
738
+ if (branchId) form.append("branchId", String(branchId));
739
+ const headers = {};
740
+ const accessToken = window.editor.api.globals.accessToken;
741
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
742
+ const response = await fetch("/api/assets/" + encodeURIComponent(String(asset.get("id"))), {
743
+ method: "PUT",
744
+ headers,
745
+ body: form
746
+ });
747
+ const body = await response.json().catch(() => ({}));
748
+ if (!response.ok || body.error) {
749
+ throw new Error(body.error || "Failed to update script asset.");
750
+ }
751
+
752
+ const parseResult = await new Promise((resolve, reject) => {
753
+ window.editor.call("scripts:parse", asset.observer, (error, data) => {
754
+ if (error) reject(new Error(String(error)));
755
+ else resolve(data || {});
756
+ });
757
+ });
758
+ return {
759
+ assetId: String(asset.get("id")),
760
+ filename,
761
+ parsed: true,
762
+ scripts: parseResult.scripts || {},
763
+ response: body
764
+ };
765
+ }
766
+
767
+ function plainAssetJson(asset) {
768
+ if (!asset) return null;
769
+ if (typeof asset.json === "function") return asset.json();
770
+ if (asset.observer && typeof asset.observer.json === "function") return asset.observer.json();
771
+ return null;
772
+ }
773
+
774
+ function collectAssetReferences(assets, value, ids, depth = 0) {
775
+ if (!value || typeof value !== "object" || depth > 100) return;
776
+ for (const [key, child] of Object.entries(value)) {
777
+ if (["id", "path", "uniqueId", "scope", "testTemplate"].includes(key)) continue;
778
+ if (Number.isInteger(child)) {
779
+ const referenced = assets.get(Number(child));
780
+ const id = String(child);
781
+ if (referenced && !ids.has(id)) {
782
+ ids.add(id);
783
+ collectAssetReferences(assets, plainAssetJson(referenced), ids, depth + 1);
784
+ }
785
+ } else if (child && typeof child === "object") {
786
+ collectAssetReferences(assets, child, ids, depth + 1);
787
+ }
788
+ }
789
+ }
790
+
791
+ function templateScriptNames(templateData) {
792
+ const names = new Set();
793
+ for (const entity of Object.values((templateData && templateData.entities) || {})) {
794
+ const scripts = entity && entity.components && entity.components.script &&
795
+ entity.components.script.scripts;
796
+ for (const name of Object.keys(scripts || {})) names.add(name);
797
+ }
798
+ return [...names];
799
+ }
800
+
801
+ function templateChildren(templateData) {
802
+ const ids = new Set();
803
+ for (const entity of Object.values((templateData && templateData.entities) || {})) {
804
+ const attributes = entity && entity.components && entity.components.script &&
805
+ entity.components.script.scripts &&
806
+ entity.components.script.scripts.sdsTinyRootHandler &&
807
+ entity.components.script.scripts.sdsTinyRootHandler.attributes;
808
+ if (attributes && attributes.type === "testTemplate" && Number.isInteger(attributes.testTemplate)) {
809
+ ids.add(String(attributes.testTemplate));
810
+ }
811
+ }
812
+ return [...ids];
813
+ }
814
+
815
+ function collectTemplateDependencies(params) {
816
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
817
+ throw new Error("Template builds require a ready PlayCanvas Editor target.");
818
+ }
819
+ const assets = window.editor.api.globals.assets;
820
+ const template = assets.get(Number(params.assetId));
821
+ if (!template || template.get("type") !== "template") {
822
+ throw new Error("Template asset not found: " + params.assetId);
823
+ }
824
+ const templateJson = plainAssetJson(template);
825
+ if (!templateJson || !templateJson.data) {
826
+ throw new Error("Template asset has no serializable data: " + params.assetId);
827
+ }
828
+
829
+ const ids = new Set();
830
+ collectAssetReferences(assets, templateJson.data, ids);
831
+ const scripts = [];
832
+ for (const name of templateScriptNames(templateJson.data)) {
833
+ const scriptAsset =
834
+ (typeof assets.getAssetForScript === "function" && assets.getAssetForScript(name)) ||
835
+ (window.editor.assets && typeof window.editor.assets.getAssetForScript === "function" &&
836
+ window.editor.assets.getAssetForScript(name)) ||
837
+ assets.list().find((asset) =>
838
+ asset.get("type") === "script" &&
839
+ (asset.get("name") === name || asset.get("data.scripts." + name) !== undefined)
840
+ );
841
+ if (!scriptAsset) continue;
842
+ const scriptJson = plainAssetJson(scriptAsset);
843
+ const filename = scriptJson && scriptJson.file && scriptJson.file.filename;
844
+ if (
845
+ name.startsWith("sds") ||
846
+ String(filename || (scriptJson && scriptJson.name) || "").startsWith("sds")
847
+ ) continue;
848
+ ids.add(String(scriptAsset.get("id")));
849
+ scripts.push({ name, assetId: String(scriptAsset.get("id")) });
850
+ }
851
+
852
+ return {
853
+ template: templateJson,
854
+ assets: [...ids].map((id) => plainAssetJson(assets.get(Number(id)))).filter(Boolean),
855
+ scripts,
856
+ childTemplateIds: templateChildren(templateJson.data),
857
+ projectUrl: window.config && window.config.project && window.config.project.id
858
+ ? "https://playcanvas.com/project/" + window.config.project.id + "/overview"
859
+ : null,
860
+ sceneUrl: location.href
861
+ };
862
+ }
863
+
331
864
  function withTimeout(promise, timeoutMs) {
332
865
  return new Promise((resolve, reject) => {
333
866
  const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
@@ -344,6 +877,187 @@
344
877
  });
345
878
  }
346
879
 
880
+ function daemonRequest(path, method, body, timeoutMs = 15000) {
881
+ const id = "daemon-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
882
+ return new Promise((resolve, reject) => {
883
+ const timer = setTimeout(() => {
884
+ daemonWaiters.delete(id);
885
+ reject(new Error("No response from the local pcbridge daemon."));
886
+ }, timeoutMs);
887
+ daemonWaiters.set(id, { resolve, reject, timer });
888
+ window.postMessage({
889
+ channel: CHANNEL,
890
+ side: "main",
891
+ type: "daemon-request",
892
+ id,
893
+ path,
894
+ method,
895
+ body: body || {}
896
+ }, "*");
897
+ });
898
+ }
899
+
900
+ function selectedAssetStateFromEditor() {
901
+ if (!window.editor) return { known: false, asset: null };
902
+ try {
903
+ const items = window.editor.call && window.editor.call("selector:items");
904
+ if (Array.isArray(items)) return { known: true, asset: items[0] || null };
905
+ } catch {
906
+ // Fall through to the public selection API.
907
+ }
908
+ const selection = window.editor.api && window.editor.api.globals &&
909
+ window.editor.api.globals.selection;
910
+ const items = selection && (
911
+ (Array.isArray(selection.items) && selection.items) ||
912
+ (typeof selection.list === "function" && selection.list()) ||
913
+ (typeof selection.get === "function" && selection.get())
914
+ );
915
+ return Array.isArray(items)
916
+ ? { known: true, asset: items[0] || null }
917
+ : { known: false, asset: null };
918
+ }
919
+
920
+ function destroyBuilderPanel() {
921
+ if (builderPanel && typeof builderPanel.destroy === "function") builderPanel.destroy();
922
+ builderPanel = null;
923
+ selectedTemplateId = null;
924
+ selectedTemplateAsset = null;
925
+ }
926
+
927
+ function builderPanelIsAttached(layout) {
928
+ if (!builderPanel || builderPanel.destroyed === true) return false;
929
+ if (builderPanel.dom && typeof builderPanel.dom.isConnected === "boolean") {
930
+ return builderPanel.dom.isConnected;
931
+ }
932
+ if ("parent" in builderPanel) return builderPanel.parent === layout;
933
+ return true;
934
+ }
935
+
936
+ function appendRow(pcui, container, labelText, control) {
937
+ const row = new pcui.Container();
938
+ row.flex = true;
939
+ row.flexDirection = "row";
940
+ row.append(new pcui.Label({ text: labelText }));
941
+ row.append(control);
942
+ container.append(row);
943
+ }
944
+
945
+ function showBuilderPanel(asset) {
946
+ const type = asset && typeof asset.get === "function" ? asset.get("type") : null;
947
+ const id = asset && typeof asset.get === "function" ? String(asset.get("id")) : null;
948
+ if (type !== "template" || !id) {
949
+ destroyBuilderPanel();
950
+ return;
951
+ }
952
+ const pcui = window.pcui;
953
+ const layout = window.editor && window.editor.call && window.editor.call("layout.attributes");
954
+ if (!pcui || !pcui.Container || !pcui.Button || !pcui.Label || !pcui.TextInput || !layout) return;
955
+ if (builderPanel && selectedTemplateId === id && builderPanelIsAttached(layout)) return;
956
+ destroyBuilderPanel();
957
+
958
+ const projectId = window.config && window.config.project && window.config.project.id
959
+ ? String(window.config.project.id)
960
+ : "project";
961
+ const suffixKey = `pcbridge:builder:${id}:suffix`;
962
+ const prefixKey = `pcbridge:builder:${projectId}:prefix`;
963
+ const container = new pcui.Container();
964
+ container.flex = true;
965
+ container.flexDirection = "column";
966
+ if (container.class && typeof container.class.add === "function") {
967
+ container.class.add("pcbridge-tiny-builder");
968
+ }
969
+ container.append(new pcui.Label({ text: "pcbridge Tiny Builder" }));
970
+ const prefixInput = new pcui.TextInput({ value: localStorage.getItem(prefixKey) || "" });
971
+ const suffixInput = new pcui.TextInput({ value: localStorage.getItem(suffixKey) || "" });
972
+ if (typeof prefixInput.on === "function") {
973
+ prefixInput.on("change", () => localStorage.setItem(prefixKey, String(prefixInput.value || "")));
974
+ suffixInput.on("change", () => localStorage.setItem(suffixKey, String(suffixInput.value || "")));
975
+ }
976
+ appendRow(pcui, container, "上传目录", prefixInput);
977
+ appendRow(pcui, container, "文件后缀", suffixInput);
978
+ const pathLabel = new pcui.Label({ text: localStorage.getItem(`pcbridge:builder:${id}:url`) || "" });
979
+ appendRow(pcui, container, "引用路径", pathLabel);
980
+ const buildButton = new pcui.Button({ text: "构建并上传到 S3" });
981
+ const copyButton = new pcui.Button({ text: "复制引用路径" });
982
+ const logLabel = new pcui.Label({ text: "从项目 .env 或工作区 .env 读取 S3 配置" });
983
+ copyButton.on("click", () => {
984
+ if (pathLabel.text) void navigator.clipboard.writeText(pathLabel.text);
985
+ });
986
+ buildButton.on("click", async () => {
987
+ buildButton.enabled = false;
988
+ try {
989
+ let job = await daemonRequest("/builder/jobs", "POST", {
990
+ templateAssetId: id,
991
+ suffix: String(suffixInput.value || ""),
992
+ prefix: String(prefixInput.value || "")
993
+ });
994
+ while (job && job.state !== "completed" && job.state !== "error") {
995
+ logLabel.text = job.message || job.state;
996
+ await new Promise((resolve) => setTimeout(resolve, 1000));
997
+ job = await daemonRequest(
998
+ "/builder/jobs/" + encodeURIComponent(job.id),
999
+ "GET",
1000
+ {},
1001
+ 30000
1002
+ );
1003
+ }
1004
+ if (!job || job.state === "error") {
1005
+ throw new Error((job && job.error) || "Template build failed.");
1006
+ }
1007
+ pathLabel.text = job.publicUrl || "";
1008
+ localStorage.setItem(`pcbridge:builder:${id}:url`, pathLabel.text);
1009
+ logLabel.text = job.message || "上传完成";
1010
+ } catch (error) {
1011
+ logLabel.text = "构建失败: " + String((error && error.message) || error);
1012
+ } finally {
1013
+ buildButton.enabled = true;
1014
+ }
1015
+ });
1016
+ container.append(buildButton);
1017
+ container.append(copyButton);
1018
+ container.append(logLabel);
1019
+ layout.append(container);
1020
+ builderPanel = container;
1021
+ selectedTemplateId = id;
1022
+ selectedTemplateAsset = asset;
1023
+ }
1024
+
1025
+ function scheduleBuilderPanelRefresh(asset) {
1026
+ if (builderRefreshTimer !== null) clearTimeout(builderRefreshTimer);
1027
+ builderRefreshTimer = setTimeout(() => {
1028
+ builderRefreshTimer = null;
1029
+ const selection = selectedAssetStateFromEditor();
1030
+ if (selection.known) showBuilderPanel(selection.asset);
1031
+ else showBuilderPanel(asset || selectedTemplateAsset);
1032
+ }, 150);
1033
+ }
1034
+
1035
+ function installBuilderPanel() {
1036
+ if (!location.pathname.startsWith("/editor") || typeof setInterval !== "function") return;
1037
+ let subscribed = false;
1038
+ setInterval(() => {
1039
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) return;
1040
+ if (!subscribed) {
1041
+ subscribed = true;
1042
+ const refresh = (asset) => scheduleBuilderPanelRefresh(asset);
1043
+ const legacy = window.editor.selection;
1044
+ if (legacy && typeof legacy.on === "function") {
1045
+ legacy.on("add", refresh);
1046
+ legacy.on("remove", () => refresh());
1047
+ }
1048
+ const selection = window.editor.api.globals.selection;
1049
+ if (selection && typeof selection.on === "function") {
1050
+ selection.on("add", refresh);
1051
+ selection.on("remove", () => refresh());
1052
+ selection.on("change", () => refresh());
1053
+ }
1054
+ }
1055
+ const selection = selectedAssetStateFromEditor();
1056
+ if (selection.known) showBuilderPanel(selection.asset);
1057
+ else if (selectedTemplateAsset) showBuilderPanel(selectedTemplateAsset);
1058
+ }, 1000);
1059
+ }
1060
+
347
1061
  async function evalInPage(params, requestId) {
348
1062
  const timeoutMs = Number(params.timeoutMs || 15000);
349
1063
  const command = {
@@ -361,6 +1075,7 @@
361
1075
  editor: window.editor,
362
1076
  pc: window.pc,
363
1077
  pcui: window.pcui,
1078
+ runtimeApp: getRuntimeApp(),
364
1079
  command,
365
1080
  serialize
366
1081
  };
@@ -374,6 +1089,7 @@
374
1089
  const editor = ctx.editor;
375
1090
  const pc = ctx.pc;
376
1091
  const pcui = ctx.pcui;
1092
+ const runtimeApp = ctx.runtimeApp;
377
1093
  const command = ctx.command;
378
1094
  const serialize = ctx.serialize;
379
1095
  return (async () => {
@@ -382,7 +1098,7 @@
382
1098
  `
383
1099
  );
384
1100
 
385
- return serialize(await withTimeout(fn(context), timeoutMs));
1101
+ return serialize(await withTimeout(fn(context), timeoutMs), params.serializeOptions);
386
1102
  }
387
1103
 
388
1104
  function encodeCanvas(canvas, params, source) {
@@ -629,6 +1345,13 @@
629
1345
  if (method === "bridge:clearLogs") return clearLogs();
630
1346
  if (method === "bridge:uploadAsset") return uploadAsset(params || {});
631
1347
  if (method === "bridge:focusViewport") return focusViewport(params || {});
1348
+ if (method === "bridge:workspaceSnapshot") return workspaceSnapshot();
1349
+ if (method === "bridge:collectTemplateDependencies") return collectTemplateDependencies(params || {});
1350
+ if (method === "bridge:readAssetText") return readAssetText(params || {});
1351
+ if (method === "bridge:readAssetFile") return readAssetFile(params || {});
1352
+ if (method === "bridge:readAssetResource") return readAssetResource(params || {});
1353
+ if (method === "bridge:writeAssetFile") return writeAssetFile(params || {});
1354
+ if (method === "bridge:writeScriptText") return writeScriptText(params || {});
632
1355
  throw new Error(`Unknown bridge method: ${method}`);
633
1356
  }
634
1357
 
@@ -636,6 +1359,15 @@
636
1359
  if (event.source !== window) return;
637
1360
  const message = event.data;
638
1361
  if (!message || message.channel !== CHANNEL || message.side !== "isolated") return;
1362
+ if (message.type === "daemon-response" && message.id) {
1363
+ const waiter = daemonWaiters.get(message.id);
1364
+ if (!waiter) return;
1365
+ daemonWaiters.delete(message.id);
1366
+ clearTimeout(waiter.timer);
1367
+ if (message.ok) waiter.resolve(message.data);
1368
+ else waiter.reject(message.error || new Error("Local daemon request failed."));
1369
+ return;
1370
+ }
639
1371
  if (message.type !== "request") return;
640
1372
 
641
1373
  const startedAt = performance.now();
@@ -668,5 +1400,6 @@
668
1400
  }
669
1401
  });
670
1402
 
1403
+ installBuilderPanel();
671
1404
  window.postMessage({ channel: CHANNEL, side: "main", type: "ready" }, "*");
672
1405
  })();