playcanvas-agent-bridge-cli 0.2.1 → 0.3.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
@@ -5,6 +5,80 @@
5
5
  if (window.__pcbridgeMainWorld) return;
6
6
  window.__pcbridgeMainWorld = true;
7
7
 
8
+ const MAX_LOGS = 500;
9
+ const capturedLogs = [];
10
+ let nextLogSeq = 1;
11
+
12
+ function formatLogArg(value) {
13
+ if (typeof value === "string") return value;
14
+ if (value instanceof Error) return value.stack || value.message;
15
+ try {
16
+ return JSON.stringify(serialize(value, {
17
+ maxDepth: 3,
18
+ maxArray: 20,
19
+ maxKeys: 30,
20
+ maxString: 1000
21
+ }));
22
+ } catch {
23
+ return String(value);
24
+ }
25
+ }
26
+
27
+ function pushLog(level, args, source) {
28
+ const list = Array.from(args || []);
29
+ const entry = {
30
+ seq: nextLogSeq,
31
+ time: new Date().toISOString(),
32
+ level,
33
+ source,
34
+ text: list.map(formatLogArg).join(" "),
35
+ args: list.map((item) => serialize(item, {
36
+ maxDepth: 3,
37
+ maxArray: 20,
38
+ maxKeys: 30,
39
+ maxString: 1000
40
+ }))
41
+ };
42
+ nextLogSeq += 1;
43
+ capturedLogs.push(entry);
44
+ while (capturedLogs.length > MAX_LOGS) capturedLogs.shift();
45
+ }
46
+
47
+ function patchConsoleCapture() {
48
+ if (window.__pcbridgeConsoleCapture) return;
49
+ window.__pcbridgeConsoleCapture = true;
50
+
51
+ const methods = ["debug", "log", "info", "warn", "error"];
52
+ for (const method of methods) {
53
+ const original = window.console && window.console[method];
54
+ if (typeof original !== "function") continue;
55
+ window.console[method] = function pcbridgeConsoleProxy(...args) {
56
+ try {
57
+ pushLog(method === "log" ? "info" : method, args, "console");
58
+ } catch {
59
+ // Preserve page console behavior even if log serialization fails.
60
+ }
61
+ return original.apply(this, args);
62
+ };
63
+ }
64
+
65
+ window.addEventListener("error", (event) => {
66
+ pushLog("error", [
67
+ event.message || "Uncaught error",
68
+ event.filename || "",
69
+ event.lineno || 0,
70
+ event.colno || 0,
71
+ event.error || null
72
+ ], "window.error");
73
+ });
74
+
75
+ window.addEventListener("unhandledrejection", (event) => {
76
+ pushLog("error", ["Unhandled promise rejection", event.reason || null], "unhandledrejection");
77
+ });
78
+ }
79
+
80
+ patchConsoleCapture();
81
+
8
82
  function safeGetEditorValue(value, path) {
9
83
  try {
10
84
  return value && typeof value.get === "function" ? value.get(path) : undefined;
@@ -108,18 +182,72 @@
108
182
  return normalize(value, 0);
109
183
  }
110
184
 
185
+ function getTargetKind() {
186
+ if (location.hostname === "launch.playcanvas.com") return "launch";
187
+ if (location.pathname.startsWith("/editor")) return "editor";
188
+ return "playcanvas";
189
+ }
190
+
191
+ function getRuntimeApp() {
192
+ 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;
200
+ }
201
+ } catch {
202
+ // Fall through to common global app locations.
203
+ }
204
+
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
+ }
209
+
210
+ function getPrimaryCanvas(app) {
211
+ return (
212
+ (app && app.graphicsDevice && app.graphicsDevice.canvas) ||
213
+ (app && app.canvas) ||
214
+ document.querySelector("canvas")
215
+ );
216
+ }
217
+
218
+ function getSceneIdFromUrl() {
219
+ const editorMatch = location.href.match(/\/editor\/scene\/([^/?#]+)/);
220
+ if (editorMatch) return editorMatch[1];
221
+
222
+ if (location.hostname === "launch.playcanvas.com") {
223
+ const launchMatch = location.pathname.match(/^\/([^/?#]+)/);
224
+ if (launchMatch) return launchMatch[1];
225
+ }
226
+
227
+ return undefined;
228
+ }
229
+
111
230
  function describeTarget() {
112
231
  const config = window.config || {};
113
- const ready = Boolean(window.editor && window.editor.api && window.editor.api.globals);
114
- const matchScene = location.href.match(/\/editor\/scene\/([^/?#]+)/);
232
+ const kind = getTargetKind();
233
+ const editorReady = Boolean(window.editor && window.editor.api && window.editor.api.globals);
234
+ const app = getRuntimeApp();
235
+ const canvasCount = document.querySelectorAll("canvas").length;
236
+ const launchReady = kind === "launch" && document.readyState !== "loading";
237
+ const ready = editorReady || launchReady;
115
238
  return {
239
+ kind,
116
240
  url: location.href,
117
241
  title: document.title || "",
118
242
  ready,
243
+ hasEditor: Boolean(window.editor),
244
+ hasPc: Boolean(window.pc),
245
+ hasRuntimeApp: Boolean(app),
246
+ canvasCount,
119
247
  projectId: config.project && config.project.id ? String(config.project.id) : undefined,
120
248
  sceneId:
121
249
  (config.scene && config.scene.id ? String(config.scene.id) : undefined) ||
122
- (matchScene ? matchScene[1] : undefined),
250
+ getSceneIdFromUrl(),
123
251
  branchId:
124
252
  (config.self && config.self.branch && config.self.branch.id
125
253
  ? String(config.self.branch.id)
@@ -128,6 +256,78 @@
128
256
  };
129
257
  }
130
258
 
259
+ function readAsset(asset) {
260
+ const get = (path) => {
261
+ try {
262
+ return asset.get(path);
263
+ } catch {
264
+ return undefined;
265
+ }
266
+ };
267
+ const path = get("path") || [];
268
+ return {
269
+ id: get("id"),
270
+ name: get("name"),
271
+ type: get("type"),
272
+ path,
273
+ folder: Array.isArray(path) && path.length ? path[path.length - 1] : null,
274
+ tags: get("tags") || [],
275
+ file: get("file") || null
276
+ };
277
+ }
278
+
279
+ function splitAssetPath(path) {
280
+ if (Array.isArray(path)) return path.map(String).map((part) => part.trim()).filter(Boolean);
281
+ return String(path || "")
282
+ .split("/")
283
+ .map((part) => part.trim())
284
+ .filter(Boolean);
285
+ }
286
+
287
+ function isChildFolder(asset, name, parent) {
288
+ if (!asset || asset.get("type") !== "folder" || asset.get("name") !== name) return false;
289
+ const path = asset.get("path") || [];
290
+ if (!parent) return path.length === 0;
291
+ return path[path.length - 1] === parent.get("id");
292
+ }
293
+
294
+ async function ensureFolderPath(assets, path) {
295
+ const created = [];
296
+ let parent = null;
297
+ for (const name of splitAssetPath(path)) {
298
+ let folder = assets.list().find((asset) => isChildFolder(asset, name, parent));
299
+ if (!folder) {
300
+ folder = await assets.createFolder({ name, folder: parent || undefined });
301
+ created.push(folder);
302
+ }
303
+ parent = folder;
304
+ }
305
+ return { folder: parent, created };
306
+ }
307
+
308
+ async function resolveFolder(assets, params) {
309
+ if (params.folderId !== undefined && params.folderId !== null && params.folderId !== "") {
310
+ const folder = assets.get(Number(params.folderId));
311
+ if (!folder || folder.get("type") !== "folder") {
312
+ throw new Error("Folder asset not found: " + params.folderId);
313
+ }
314
+ return { folder, created: [] };
315
+ }
316
+ if (params.folder) {
317
+ return ensureFolderPath(assets, params.folder);
318
+ }
319
+ return { folder: null, created: [] };
320
+ }
321
+
322
+ function bytesFromBase64(base64) {
323
+ const binary = atob(base64);
324
+ const bytes = new Uint8Array(binary.length);
325
+ for (let index = 0; index < binary.length; index += 1) {
326
+ bytes[index] = binary.charCodeAt(index);
327
+ }
328
+ return bytes;
329
+ }
330
+
131
331
  function withTimeout(promise, timeoutMs) {
132
332
  return new Promise((resolve, reject) => {
133
333
  const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
@@ -185,18 +385,32 @@
185
385
  return serialize(await withTimeout(fn(context), timeoutMs));
186
386
  }
187
387
 
188
- function captureViewport(params) {
189
- const app = window.editor.call("viewport:app");
190
- if (!app) throw new Error("Viewport app not found.");
191
- const device = app.graphicsDevice;
192
- const gl = device && device.gl;
193
- if (!gl) throw new Error("WebGL context not found.");
388
+ function encodeCanvas(canvas, params, source) {
389
+ const maxWidth = Number(params.maxWidth || 1200);
390
+ let outWidth = canvas.width;
391
+ let outHeight = canvas.height;
392
+ if (maxWidth > 0 && canvas.width > maxWidth) {
393
+ outWidth = maxWidth;
394
+ outHeight = Math.round(canvas.height * (maxWidth / canvas.width));
395
+ }
194
396
 
195
- window.editor.call("viewport:render");
196
- app.tick();
397
+ const dstCanvas = document.createElement("canvas");
398
+ dstCanvas.width = outWidth;
399
+ dstCanvas.height = outHeight;
400
+ dstCanvas.getContext("2d").drawImage(canvas, 0, 0, outWidth, outHeight);
197
401
 
198
- const width = device.width;
199
- const height = device.height;
402
+ const mime = params.format === "webp" ? "image/webp" : "image/png";
403
+ const dataUrl = dstCanvas.toDataURL(mime, Number(params.quality || 0.85));
404
+ return {
405
+ mime,
406
+ width: outWidth,
407
+ height: outHeight,
408
+ source,
409
+ base64: dataUrl.split(",")[1]
410
+ };
411
+ }
412
+
413
+ function canvasFromWebglPixels(gl, width, height) {
200
414
  const pixels = new Uint8Array(width * height * 4);
201
415
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
202
416
  gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
@@ -216,27 +430,193 @@
216
430
  srcCanvas
217
431
  .getContext("2d")
218
432
  .putImageData(new ImageData(new Uint8ClampedArray(flipped.buffer), width, height), 0, 0);
433
+ return srcCanvas;
434
+ }
219
435
 
220
- const maxWidth = Number(params.maxWidth || 1200);
221
- let outWidth = width;
222
- let outHeight = height;
223
- if (maxWidth > 0 && width > maxWidth) {
224
- outWidth = maxWidth;
225
- outHeight = Math.round(height * (maxWidth / width));
436
+ function captureEditorViewport(params) {
437
+ const app = window.editor.call("viewport:app");
438
+ if (!app) throw new Error("Viewport app not found.");
439
+ const device = app.graphicsDevice;
440
+ const gl = device && device.gl;
441
+ if (!gl) throw new Error("WebGL context not found.");
442
+
443
+ window.editor.call("viewport:render");
444
+ app.tick();
445
+
446
+ const width = device.width;
447
+ const height = device.height;
448
+ const srcCanvas = canvasFromWebglPixels(gl, width, height);
449
+ return encodeCanvas(srcCanvas, params, "editor-viewport");
450
+ }
451
+
452
+ function getCanvasWebglContext(canvas) {
453
+ const app = getRuntimeApp();
454
+ const appCanvas = getPrimaryCanvas(app);
455
+ if (appCanvas === canvas && app && app.graphicsDevice && app.graphicsDevice.gl) {
456
+ return app.graphicsDevice.gl;
226
457
  }
227
458
 
228
- const dstCanvas = document.createElement("canvas");
229
- dstCanvas.width = outWidth;
230
- dstCanvas.height = outHeight;
231
- dstCanvas.getContext("2d").drawImage(srcCanvas, 0, 0, outWidth, outHeight);
459
+ return (
460
+ canvas.getContext("webgl2") ||
461
+ canvas.getContext("webgl") ||
462
+ canvas.getContext("experimental-webgl")
463
+ );
464
+ }
465
+
466
+ function captureRuntimeCanvas(params) {
467
+ const app = getRuntimeApp();
468
+ const canvas = getPrimaryCanvas(app);
469
+ if (!canvas) {
470
+ throw new Error("PlayCanvas launch canvas not found.");
471
+ }
472
+
473
+ try {
474
+ const gl = getCanvasWebglContext(canvas);
475
+ if (gl && typeof gl.readPixels === "function") {
476
+ const width =
477
+ (app && app.graphicsDevice && app.graphicsDevice.width) ||
478
+ gl.drawingBufferWidth ||
479
+ canvas.width;
480
+ const height =
481
+ (app && app.graphicsDevice && app.graphicsDevice.height) ||
482
+ gl.drawingBufferHeight ||
483
+ canvas.height;
484
+ const srcCanvas = canvasFromWebglPixels(gl, width, height);
485
+ return encodeCanvas(srcCanvas, params, "launch-webgl");
486
+ }
487
+ } catch (error) {
488
+ pushLog("warn", ["WebGL capture failed; falling back to canvas capture.", error], "pcbridge");
489
+ }
490
+
491
+ return encodeCanvas(canvas, params, "launch-canvas");
492
+ }
493
+
494
+ function captureViewport(params) {
495
+ if (window.editor && typeof window.editor.call === "function") {
496
+ return captureEditorViewport(params);
497
+ }
498
+
499
+ return captureRuntimeCanvas(params);
500
+ }
501
+
502
+ function getLogs(params) {
503
+ const level = params.level ? String(params.level).toLowerCase() : null;
504
+ const since = params.since === undefined || params.since === null || params.since === ""
505
+ ? null
506
+ : Number(params.since);
507
+ const limit = Math.max(1, Math.min(Number(params.limit || 100), 500));
508
+ let items = capturedLogs;
509
+
510
+ if (level) {
511
+ items = items.filter((entry) => entry.level === level);
512
+ }
513
+ if (since !== null && Number.isFinite(since)) {
514
+ items = items.filter((entry) => entry.seq > since);
515
+ }
516
+
517
+ const total = items.length;
518
+ const hasExplicitOffset =
519
+ params.offset !== undefined && params.offset !== null && params.offset !== "";
520
+ const offset = hasExplicitOffset
521
+ ? Math.max(0, Number(params.offset || 0))
522
+ : Math.max(0, total - limit);
523
+ const page = items.slice(offset, offset + limit);
232
524
 
233
- const mime = params.format === "webp" ? "image/webp" : "image/png";
234
- const dataUrl = dstCanvas.toDataURL(mime, Number(params.quality || 0.85));
235
525
  return {
236
- mime,
237
- width: outWidth,
238
- height: outHeight,
239
- base64: dataUrl.split(",")[1]
526
+ items: page,
527
+ total,
528
+ offset,
529
+ limit,
530
+ hasMore: offset + page.length < total,
531
+ nextSince: page.length ? page[page.length - 1].seq : since
532
+ };
533
+ }
534
+
535
+ function clearLogs() {
536
+ const affected = capturedLogs.length;
537
+ capturedLogs.length = 0;
538
+ return { affected };
539
+ }
540
+
541
+ async function uploadAsset(params) {
542
+ if (!params.base64) throw new Error("base64 file content is required.");
543
+ if (!params.name) throw new Error("name is required.");
544
+ if (!params.type) throw new Error("type is required.");
545
+
546
+ const assets = window.editor.api.globals.assets;
547
+ const folderResult = await resolveFolder(assets, params);
548
+ const blob = new Blob([bytesFromBase64(params.base64)], {
549
+ type: params.mime || "application/octet-stream"
550
+ });
551
+ const asset = await assets.upload(
552
+ {
553
+ name: params.name,
554
+ type: params.type,
555
+ folder: folderResult.folder || undefined,
556
+ filename: params.filename || params.name,
557
+ file: blob,
558
+ preload: params.preload !== false
559
+ },
560
+ null
561
+ );
562
+ return {
563
+ asset: readAsset(asset),
564
+ createdFolders: folderResult.created.map(readAsset)
565
+ };
566
+ }
567
+
568
+ function focusViewport(params) {
569
+ const ids = Array.isArray(params.ids) && params.ids.length ? params.ids : [params.id];
570
+ const entitiesApi = window.editor.api.globals.entities;
571
+ const entities = ids.map((id) => entitiesApi.get(id)).filter(Boolean);
572
+ if (!entities.length) {
573
+ throw new Error("No valid entities found.");
574
+ }
575
+
576
+ window.editor.api.globals.selection.set(entities, { history: true });
577
+
578
+ const camera = window.editor.call("camera:current");
579
+ if (!camera) {
580
+ throw new Error("Could not retrieve current camera.");
581
+ }
582
+ const aabb = window.editor.call("selection:aabb");
583
+ if (!aabb) {
584
+ throw new Error("Could not calculate selection bounds.");
585
+ }
586
+
587
+ let distance = Math.max(aabb.halfExtents.x, aabb.halfExtents.y, aabb.halfExtents.z);
588
+ distance /= Math.tan(0.5 * camera.camera.fov * Math.PI / 180.0);
589
+ distance = distance * 1.1 + 1;
590
+
591
+ if (params.view) {
592
+ const views = {
593
+ top: [-90, 0],
594
+ bottom: [90, 0],
595
+ front: [0, 0],
596
+ back: [0, 180],
597
+ left: [0, -90],
598
+ right: [0, 90],
599
+ perspective: [-25, 45]
600
+ };
601
+ const angles = views[params.view];
602
+ if (angles) {
603
+ camera.setEulerAngles(angles[0], angles[1], 0);
604
+ }
605
+ } else if (
606
+ (params.yaw !== undefined && params.yaw !== null) ||
607
+ (params.pitch !== undefined && params.pitch !== null)
608
+ ) {
609
+ const yaw = params.yaw ?? 45;
610
+ const pitch = params.pitch ?? -25;
611
+ camera.setEulerAngles(pitch, yaw, 0);
612
+ }
613
+
614
+ window.editor.call("camera:focus", aabb.center, distance);
615
+ return {
616
+ focused: ids,
617
+ view: params.view || null,
618
+ yaw: params.yaw ?? null,
619
+ pitch: params.pitch ?? null
240
620
  };
241
621
  }
242
622
 
@@ -245,6 +625,10 @@
245
625
  if (method === "bridge:describeTarget") return describeTarget();
246
626
  if (method === "bridge:eval") return evalInPage(params || {}, requestId);
247
627
  if (method === "bridge:captureViewport") return captureViewport(params || {});
628
+ if (method === "bridge:getLogs") return getLogs(params || {});
629
+ if (method === "bridge:clearLogs") return clearLogs();
630
+ if (method === "bridge:uploadAsset") return uploadAsset(params || {});
631
+ if (method === "bridge:focusViewport") return focusViewport(params || {});
248
632
  throw new Error(`Unknown bridge method: ${method}`);
249
633
  }
250
634
 
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "PlayCanvas Agent Bridge",
4
- "description": "Connects open PlayCanvas Editor tabs to the local pcbridge daemon.",
5
- "version": "0.2.1",
4
+ "description": "Connects open PlayCanvas Editor and Launch tabs to the local pcbridge daemon.",
5
+ "version": "0.3.0",
6
6
  "permissions": ["activeTab", "storage"],
7
7
  "host_permissions": [
8
8
  "http://playcanvas.com/*",
@@ -21,16 +21,26 @@
21
21
  },
22
22
  "content_scripts": [
23
23
  {
24
- "matches": ["http://playcanvas.com/editor*", "https://playcanvas.com/editor*"],
24
+ "matches": [
25
+ "http://playcanvas.com/editor*",
26
+ "https://playcanvas.com/editor*",
27
+ "http://launch.playcanvas.com/*",
28
+ "https://launch.playcanvas.com/*"
29
+ ],
25
30
  "js": ["main.js"],
26
31
  "world": "MAIN",
27
- "run_at": "document_idle"
32
+ "run_at": "document_start"
28
33
  },
29
34
  {
30
- "matches": ["http://playcanvas.com/editor*", "https://playcanvas.com/editor*"],
35
+ "matches": [
36
+ "http://playcanvas.com/editor*",
37
+ "https://playcanvas.com/editor*",
38
+ "http://launch.playcanvas.com/*",
39
+ "https://launch.playcanvas.com/*"
40
+ ],
31
41
  "js": ["isolated.js"],
32
42
  "world": "ISOLATED",
33
- "run_at": "document_idle"
43
+ "run_at": "document_start"
34
44
  }
35
45
  ],
36
46
  "content_security_policy": {
@@ -8,7 +8,7 @@
8
8
  color: #1f2937;
9
9
  font: 13px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
10
10
  margin: 0;
11
- min-width: 280px;
11
+ min-width: 320px;
12
12
  padding: 14px;
13
13
  }
14
14
 
@@ -32,6 +32,38 @@
32
32
  margin: 0;
33
33
  word-break: break-all;
34
34
  }
35
+
36
+ .actions {
37
+ display: grid;
38
+ gap: 8px;
39
+ grid-template-columns: 1fr 1fr;
40
+ margin-top: 14px;
41
+ }
42
+
43
+ button {
44
+ background: #2563eb;
45
+ border: 0;
46
+ border-radius: 5px;
47
+ color: white;
48
+ cursor: pointer;
49
+ font: inherit;
50
+ padding: 8px;
51
+ }
52
+
53
+ button.secondary {
54
+ background: #4b5563;
55
+ }
56
+
57
+ button:disabled {
58
+ cursor: not-allowed;
59
+ opacity: 0.45;
60
+ }
61
+
62
+ #message {
63
+ color: #6b7280;
64
+ line-height: 1.4;
65
+ margin: 10px 0 0;
66
+ }
35
67
  </style>
36
68
  </head>
37
69
  <body>
@@ -41,7 +73,16 @@
41
73
  <dd id="daemon">Loading</dd>
42
74
  <dt>Tab</dt>
43
75
  <dd id="tab">Loading</dd>
76
+ <dt>Frontend</dt>
77
+ <dd id="frontend">Loading</dd>
78
+ <dt>Mode</dt>
79
+ <dd id="mode">Loading</dd>
44
80
  </dl>
81
+ <div class="actions">
82
+ <button id="use-custom" type="button">Use custom frontend</button>
83
+ <button id="use-official" class="secondary" type="button">Use official frontend</button>
84
+ </div>
85
+ <p id="message"></p>
45
86
  <script src="popup.js"></script>
46
87
  </body>
47
88
  </html>