playcanvas-agent-bridge-cli 0.6.0 → 0.6.2

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
@@ -14,7 +14,24 @@
14
14
  let selectedTemplateId = null;
15
15
  let selectedTemplateAsset = null;
16
16
  let workspaceEventsInstalled = false;
17
+ let sceneEventsInstalled = false;
18
+ let observedAssets = new WeakSet();
19
+ let observedEntities = new WeakSet();
17
20
  let workspaceSyncTimer = null;
21
+ let sceneSyncTimer = null;
22
+ let sceneInteractionHoldStartedAt = 0;
23
+ let pointerDownActive = false;
24
+ let workspaceMutationDepth = 0;
25
+ const dirtyAssetIds = new Set();
26
+ const removedAssetIds = new Set();
27
+ const dirtyEntityIds = new Set();
28
+ const removedEntityIds = new Set();
29
+ let sceneSettingsDirty = false;
30
+ let fullSceneDirty = false;
31
+
32
+ const TEXT_ASSET_TYPES = new Set(["script", "text", "json", "html", "css", "shader"]);
33
+ const DATA_JSON_ASSET_TYPES = new Set(["material", "template", "cubemap", "sprite", "animstategraph", "bundle"]);
34
+ const META_SUMMARY_KEYS = ["width", "height", "format", "alpha", "depth", "srgb", "meshes", "vertices", "triangles", "nodes", "materials", "textures", "animations", "duration", "channels", "sampleRate"];
18
35
 
19
36
  function formatLogArg(value) {
20
37
  if (typeof value === "string") return value;
@@ -86,6 +103,15 @@
86
103
 
87
104
  patchConsoleCapture();
88
105
 
106
+ function installPointerTracking() {
107
+ if (typeof window.addEventListener !== "function") return;
108
+ const onDown = () => { pointerDownActive = true; };
109
+ const onUp = () => { pointerDownActive = false; };
110
+ for (const ev of ["pointerdown", "mousedown"]) window.addEventListener(ev, onDown, true);
111
+ for (const ev of ["pointerup", "pointercancel", "mouseup", "blur"]) window.addEventListener(ev, onUp, true);
112
+ }
113
+ installPointerTracking();
114
+
89
115
  function safeGetEditorValue(value, path) {
90
116
  try {
91
117
  return value && typeof value.get === "function" ? value.get(path) : undefined;
@@ -193,8 +219,11 @@
193
219
  }
194
220
 
195
221
  function getTargetKind() {
196
- if (location.hostname === "launch.playcanvas.com") return "launch";
197
- if (location.pathname.startsWith("/editor")) return "editor";
222
+ if (location.hostname === "launch.playcanvas.com" || location.hostname === "pc-launch.sightp.com") return "launch";
223
+ const selfhost = Boolean(window.config && window.config.selfhost);
224
+ if ((location.hostname === "pc-editor.sightp.com" || selfhost) && /^\/launch\//.test(location.pathname)) return "launch";
225
+ if ((location.hostname === "playcanvas.com" || location.hostname === "pc-editor.sightp.com" || selfhost) &&
226
+ /^\/editor(?:\/|$)/.test(location.pathname)) return "editor";
198
227
  return "playcanvas";
199
228
  }
200
229
 
@@ -395,7 +424,10 @@
395
424
  const editorMatch = location.href.match(/\/editor\/scene\/([^/?#]+)/);
396
425
  if (editorMatch) return editorMatch[1];
397
426
 
398
- if (location.hostname === "launch.playcanvas.com") {
427
+ const selfhostLaunchMatch = location.pathname.match(/^\/launch\/([^/?#]+)/);
428
+ if (selfhostLaunchMatch) return selfhostLaunchMatch[1];
429
+
430
+ if (location.hostname === "launch.playcanvas.com" || location.hostname === "pc-launch.sightp.com") {
399
431
  const launchMatch = location.pathname.match(/^\/([^/?#]+)/);
400
432
  if (launchMatch) return launchMatch[1];
401
433
  }
@@ -450,6 +482,9 @@
450
482
  const ready = kind === "launch" ? launchReady : editorReady;
451
483
  return {
452
484
  kind,
485
+ platform: config.selfhost ? "selfhost" : "official",
486
+ bridgeProtocolVersion: 1,
487
+ processingProtocolVersion: config.selfhost && kind === "editor" && window.editor?.methods?.has("assets:import:request") ? 1 : null,
453
488
  url: location.href,
454
489
  title: document.title || "",
455
490
  ready,
@@ -509,17 +544,48 @@
509
544
  }
510
545
  };
511
546
  const path = get("path") || [];
512
- return {
547
+ const type = get("type");
548
+ const result = {
513
549
  id: get("id"),
514
550
  name: get("name"),
515
- type: get("type"),
551
+ type,
516
552
  source: get("source") || false,
517
553
  source_asset_id: get("source_asset_id") || null,
518
554
  path,
519
555
  folder: Array.isArray(path) && path.length ? path[path.length - 1] : null,
520
556
  tags: get("tags") || [],
557
+ preload: get("preload") !== false,
521
558
  file: get("file") || null
522
559
  };
560
+ if (DATA_JSON_ASSET_TYPES.has(type)) {
561
+ const plain = plainAssetJson(asset);
562
+ const rawData = plain && plain.data !== undefined ? plain.data : get("data");
563
+ result.data = clonePlainJson(rawData) || {};
564
+ }
565
+ const metaSummary = summarizeAssetMeta(get("meta"));
566
+ if (metaSummary) result.meta = metaSummary;
567
+ return result;
568
+ }
569
+
570
+ function summarizeAssetMeta(rawMeta) {
571
+ if (!rawMeta || typeof rawMeta !== "object" || Array.isArray(rawMeta)) return null;
572
+ const summary = {};
573
+ for (const key of META_SUMMARY_KEYS) {
574
+ const val = rawMeta[key];
575
+ if (typeof val === "number" || typeof val === "boolean" || typeof val === "string") {
576
+ summary[key] = val;
577
+ }
578
+ }
579
+ return Object.keys(summary).length ? summary : null;
580
+ }
581
+
582
+ function clonePlainJson(value) {
583
+ if (value === undefined) return null;
584
+ try {
585
+ return JSON.parse(JSON.stringify(value));
586
+ } catch {
587
+ return null;
588
+ }
523
589
  }
524
590
 
525
591
  function splitAssetPath(path) {
@@ -614,43 +680,334 @@
614
680
  return { response, filename };
615
681
  }
616
682
 
617
- function workspaceSnapshot() {
683
+ function getActiveSceneId() {
684
+ const config = window.config || {};
685
+ const id = (config.scene && config.scene.id ? String(config.scene.id) : "") || getSceneIdFromUrl() || "";
686
+ return id || null;
687
+ }
688
+
689
+ function getActiveSceneName() {
690
+ const liveName = window.editor?.api?.globals?.realtime?.scenes?.current?.data?.name;
691
+ if (liveName) return String(liveName);
692
+ const config = window.config || {};
693
+ return (config.scene && config.scene.name ? String(config.scene.name) : "") || null;
694
+ }
695
+
696
+ function readEntityPlain(entity) {
697
+ if (!entity) return null;
698
+ if (typeof entity.json === "function") return clonePlainJson(entity.json());
699
+ if (entity.observer && typeof entity.observer.json === "function") return clonePlainJson(entity.observer.json());
700
+ return null;
701
+ }
702
+
703
+ function readActiveScene() {
704
+ const globals = window.editor && window.editor.api && window.editor.api.globals;
705
+ const entitiesApi = globals && globals.entities;
706
+ if (!entitiesApi || !entitiesApi.root || typeof entitiesApi.list !== "function") return null;
707
+ const id = getActiveSceneId();
708
+ if (!id) return null;
709
+ const entities = {};
710
+ for (const entity of entitiesApi.list()) {
711
+ const data = readEntityPlain(entity);
712
+ if (data && data.resource_id) {
713
+ entities[String(data.resource_id)] = data;
714
+ }
715
+ }
716
+ const settingsApi = globals.settings && globals.settings.scene;
717
+ const settings = settingsApi && typeof settingsApi.json === "function"
718
+ ? clonePlainJson(settingsApi.json()) || {}
719
+ : {};
720
+ return {
721
+ id,
722
+ name: getActiveSceneName() || "Scene",
723
+ active: true,
724
+ settings,
725
+ entities
726
+ };
727
+ }
728
+
729
+ function listProjectScenesIfSupported() {
730
+ if (!window.editor || typeof window.editor.call !== "function") return Promise.resolve(null);
731
+ if (!window.editor.methods || typeof window.editor.methods.has !== "function" || !window.editor.methods.has("scenes:list")) {
732
+ return Promise.resolve(null);
733
+ }
734
+ return new Promise((resolve) => {
735
+ const timer = setTimeout(() => resolve(null), 5000);
736
+ try {
737
+ window.editor.call(
738
+ "scenes:list",
739
+ (list) => {
740
+ clearTimeout(timer);
741
+ if (!Array.isArray(list)) { resolve(null); return; }
742
+ resolve(list.map((item) => ({
743
+ id: String(item.id),
744
+ uniqueId: item.uniqueId !== undefined ? String(item.uniqueId) : undefined,
745
+ name: String(item.name || "Scene"),
746
+ modified: item.modified ? String(item.modified) : null
747
+ })));
748
+ },
749
+ () => {
750
+ clearTimeout(timer);
751
+ resolve(null);
752
+ }
753
+ );
754
+ } catch {
755
+ clearTimeout(timer);
756
+ resolve(null);
757
+ }
758
+ });
759
+ }
760
+
761
+ async function workspaceSnapshot() {
618
762
  if (!window.editor || !window.editor.api || !window.editor.api.globals) {
619
763
  throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
620
764
  }
621
- return {
765
+ const result = {
622
766
  assets: window.editor.api.globals.assets.list().map(readAsset)
623
767
  };
768
+ const activeScene = readActiveScene();
769
+ if (activeScene) result.activeScene = activeScene;
770
+ const scenes = await listProjectScenesIfSupported();
771
+ if (scenes) result.scenes = scenes;
772
+ return result;
624
773
  }
625
774
 
626
- function scheduleWorkspaceSync() {
775
+ async function withWorkspaceMutationSuppression(fn) {
776
+ workspaceMutationDepth += 1;
777
+ try {
778
+ return await fn();
779
+ } finally {
780
+ workspaceMutationDepth = Math.max(0, workspaceMutationDepth - 1);
781
+ }
782
+ }
783
+
784
+ function emitWorkspaceDelta(delta) {
785
+ window.postMessage({
786
+ channel: CHANNEL,
787
+ side: "main",
788
+ type: "workspace-delta",
789
+ delta
790
+ }, "*");
791
+ }
792
+
793
+ function flushAssetDelta() {
794
+ workspaceSyncTimer = null;
795
+ if (!window.editor?.api?.globals?.assets) return;
796
+ const assetsApi = window.editor.api.globals.assets;
797
+ const upsertedAssets = [];
798
+ for (const id of dirtyAssetIds) {
799
+ if (removedAssetIds.has(id)) continue;
800
+ const asset = assetsApi.get(Number(id));
801
+ if (asset) upsertedAssets.push(readAsset(asset));
802
+ }
803
+ const removed = [...removedAssetIds];
804
+ dirtyAssetIds.clear();
805
+ removedAssetIds.clear();
806
+ if (!upsertedAssets.length && !removed.length) return;
807
+ emitWorkspaceDelta({
808
+ upsertedAssets,
809
+ removedAssetIds: removed
810
+ });
811
+ }
812
+
813
+ function scheduleAssetDelta(assetId, removed = false) {
814
+ if (workspaceMutationDepth > 0) return;
815
+ if (assetId !== undefined && assetId !== null) {
816
+ const id = String(assetId);
817
+ if (removed) {
818
+ dirtyAssetIds.delete(id);
819
+ removedAssetIds.add(id);
820
+ } else {
821
+ removedAssetIds.delete(id);
822
+ dirtyAssetIds.add(id);
823
+ }
824
+ }
627
825
  if (workspaceSyncTimer) clearTimeout(workspaceSyncTimer);
628
- workspaceSyncTimer = setTimeout(() => {
629
- workspaceSyncTimer = null;
630
- void daemonRequest("/workspace/sync", "POST", {}, 60000).catch(() => undefined);
631
- }, 250);
826
+ workspaceSyncTimer = setTimeout(flushAssetDelta, 300);
827
+ }
828
+
829
+ function flushSceneDelta() {
830
+ sceneSyncTimer = null;
831
+ if (pointerDownActive && Date.now() - sceneInteractionHoldStartedAt < 5000) {
832
+ sceneSyncTimer = setTimeout(flushSceneDelta, 400);
833
+ return;
834
+ }
835
+ sceneInteractionHoldStartedAt = 0;
836
+ const sceneId = getActiveSceneId();
837
+ const globals = window.editor?.api?.globals;
838
+ if (!sceneId || !globals?.entities?.root) {
839
+ dirtyEntityIds.clear();
840
+ removedEntityIds.clear();
841
+ sceneSettingsDirty = false;
842
+ fullSceneDirty = false;
843
+ return;
844
+ }
845
+ if (fullSceneDirty) {
846
+ dirtyEntityIds.clear();
847
+ removedEntityIds.clear();
848
+ sceneSettingsDirty = false;
849
+ fullSceneDirty = false;
850
+ const activeScene = readActiveScene();
851
+ if (activeScene) emitWorkspaceDelta({ activeScene });
852
+ return;
853
+ }
854
+ const upsertedEntities = {};
855
+ for (const id of dirtyEntityIds) {
856
+ if (removedEntityIds.has(id)) continue;
857
+ const entity = globals.entities.get(id);
858
+ const plain = readEntityPlain(entity);
859
+ if (plain && plain.resource_id) upsertedEntities[String(plain.resource_id)] = plain;
860
+ }
861
+ const removed = [...removedEntityIds];
862
+ const includeSettings = sceneSettingsDirty;
863
+ dirtyEntityIds.clear();
864
+ removedEntityIds.clear();
865
+ sceneSettingsDirty = false;
866
+ if (!Object.keys(upsertedEntities).length && !removed.length && !includeSettings) return;
867
+ const sceneDelta = {
868
+ sceneId,
869
+ sceneName: getActiveSceneName() || "Scene",
870
+ upsertedEntities,
871
+ removedEntityIds: removed
872
+ };
873
+ if (includeSettings && globals.settings?.scene?.json) {
874
+ sceneDelta.settings = clonePlainJson(globals.settings.scene.json()) || {};
875
+ }
876
+ emitWorkspaceDelta({ sceneDelta });
877
+ }
878
+
879
+ function scheduleSceneDelta(options = {}) {
880
+ if (workspaceMutationDepth > 0) return;
881
+ if (options.full) fullSceneDirty = true;
882
+ if (options.settings) sceneSettingsDirty = true;
883
+ if (options.entityId) {
884
+ const id = String(options.entityId);
885
+ if (options.removed) {
886
+ dirtyEntityIds.delete(id);
887
+ removedEntityIds.add(id);
888
+ } else {
889
+ removedEntityIds.delete(id);
890
+ dirtyEntityIds.add(id);
891
+ }
892
+ }
893
+ if (!sceneInteractionHoldStartedAt) sceneInteractionHoldStartedAt = Date.now();
894
+ if (sceneSyncTimer) clearTimeout(sceneSyncTimer);
895
+ sceneSyncTimer = setTimeout(flushSceneDelta, 800);
632
896
  }
633
897
 
634
898
  function installWorkspaceEvents() {
635
- if (workspaceEventsInstalled || !window.editor?.api?.globals?.assets) return;
636
- const assets = window.editor.api.globals.assets;
637
- workspaceEventsInstalled = true;
638
- const observe = (asset) => {
639
- if (!asset || typeof asset.on !== "function") return;
640
- for (const event of ["file:hash:set", "file:filename:set", "path:set", "name:set"]) {
641
- try { asset.on(event, scheduleWorkspaceSync); } catch { /* optional observer event */ }
899
+ const globals = window.editor?.api?.globals;
900
+ if (globals?.assets && !workspaceEventsInstalled) {
901
+ const assets = globals.assets;
902
+ workspaceEventsInstalled = true;
903
+ const observeAsset = (asset) => {
904
+ if (!asset || typeof asset.on !== "function" || observedAssets.has(asset)) return;
905
+ observedAssets.add(asset);
906
+ const id = () => safeGetEditorValue(asset, "id");
907
+ const target = asset.observer && typeof asset.observer.on === "function" ? asset.observer : asset;
908
+ try {
909
+ target.on("*:set", (path) => {
910
+ if (!path) return;
911
+ if (path.startsWith("thumbnails") || path === "has_thumbnail" || path === "file.url") return;
912
+ scheduleAssetDelta(id(), false);
913
+ });
914
+ target.on("*:unset", (path) => {
915
+ if (!path || path.startsWith("thumbnails")) return;
916
+ scheduleAssetDelta(id(), false);
917
+ });
918
+ target.on("*:insert", () => scheduleAssetDelta(id(), false));
919
+ target.on("*:remove", () => scheduleAssetDelta(id(), false));
920
+ target.on("*:move", () => scheduleAssetDelta(id(), false));
921
+ } catch {
922
+ for (const event of ["file:hash:set", "file:filename:set", "path:set", "name:set"]) {
923
+ try { asset.on(event, () => scheduleAssetDelta(id(), false)); } catch { /* optional */ }
924
+ }
925
+ }
926
+ };
927
+ for (const asset of assets.list()) observeAsset(asset);
928
+ try {
929
+ assets.on("add", (asset) => {
930
+ observeAsset(asset);
931
+ scheduleAssetDelta(safeGetEditorValue(asset, "id"), false);
932
+ });
933
+ } catch { /* optional */ }
934
+ try {
935
+ assets.on("remove", (asset) => {
936
+ scheduleAssetDelta(safeGetEditorValue(asset, "id"), true);
937
+ });
938
+ } catch { /* optional */ }
939
+ try {
940
+ assets.on("move", (asset) => {
941
+ scheduleAssetDelta(safeGetEditorValue(asset, "id"), false);
942
+ });
943
+ } catch { /* optional */ }
944
+ try {
945
+ assets.on("load:all", () => {
946
+ for (const asset of assets.list()) observeAsset(asset);
947
+ if (workspaceMutationDepth === 0) {
948
+ void daemonRequest("/workspace/sync", "POST", {}, 60000).catch(() => undefined);
949
+ }
950
+ });
951
+ } catch { /* optional */ }
952
+ }
953
+
954
+ if (globals?.entities && typeof globals.entities.list === "function" && !sceneEventsInstalled) {
955
+ sceneEventsInstalled = true;
956
+ const entities = globals.entities;
957
+ const observeEntity = (entity) => {
958
+ if (!entity || observedEntities.has(entity)) return;
959
+ const target = entity.observer && typeof entity.observer.on === "function"
960
+ ? entity.observer
961
+ : typeof entity.on === "function" ? entity : null;
962
+ if (!target) return;
963
+ observedEntities.add(entity);
964
+ const id = () => safeGetEditorValue(entity, "resource_id");
965
+ for (const ev of ["*:set", "*:unset", "*:insert", "*:remove", "*:move"]) {
966
+ try { target.on(ev, () => scheduleSceneDelta({ entityId: id() })); } catch { /* optional */ }
967
+ }
968
+ };
969
+ for (const entity of entities.list()) observeEntity(entity);
970
+ if (typeof entities.on === "function") {
971
+ try {
972
+ entities.on("add", (entity) => {
973
+ observeEntity(entity);
974
+ scheduleSceneDelta({ entityId: safeGetEditorValue(entity, "resource_id") });
975
+ });
976
+ } catch { /* optional */ }
977
+ try {
978
+ entities.on("remove", (entity) => {
979
+ scheduleSceneDelta({ entityId: safeGetEditorValue(entity, "resource_id"), removed: true });
980
+ });
981
+ } catch { /* optional */ }
982
+ }
983
+ const sceneSettings = globals.settings?.scene;
984
+ const settingsTarget = sceneSettings?.observer && typeof sceneSettings.observer.on === "function"
985
+ ? sceneSettings.observer
986
+ : typeof sceneSettings?.on === "function" ? sceneSettings : null;
987
+ if (settingsTarget) {
988
+ for (const ev of ["*:set", "*:unset", "*:insert", "*:remove", "*:move"]) {
989
+ try { settingsTarget.on(ev, () => scheduleSceneDelta({ settings: true })); } catch { /* optional */ }
990
+ }
991
+ }
992
+ if (window.editor && typeof window.editor.on === "function") {
993
+ try {
994
+ window.editor.on("scene:load", () => {
995
+ for (const entity of entities.list()) observeEntity(entity);
996
+ scheduleSceneDelta({ full: true });
997
+ });
998
+ window.editor.on("scene:name", () => {
999
+ scheduleSceneDelta({ settings: true });
1000
+ });
1001
+ } catch { /* optional */ }
642
1002
  }
643
- };
644
- for (const asset of assets.list()) observe(asset);
645
- for (const event of ["add", "remove", "move", "load:all"]) {
646
- try { assets.on(event, (asset) => { observe(asset); scheduleWorkspaceSync(); }); } catch { /* optional assets event */ }
647
1003
  }
648
1004
  }
649
1005
 
650
1006
  async function readAssetText(params) {
651
1007
  const asset = requireEditorAsset(params.assetId);
652
- if (asset.get("type") !== "script") {
653
- throw new Error("Asset is not a script: " + params.assetId);
1008
+ const type = String(asset.get("type") || "");
1009
+ if (!TEXT_ASSET_TYPES.has(type)) {
1010
+ throw new Error("Asset is not a text asset: " + params.assetId);
654
1011
  }
655
1012
  const { response, filename } = await fetchAssetFile(asset);
656
1013
  return {
@@ -711,7 +1068,7 @@
711
1068
  };
712
1069
  }
713
1070
 
714
- async function writeAssetFile(params) {
1071
+ async function writeAssetFileInner(params) {
715
1072
  const asset = requireEditorAsset(params.assetId);
716
1073
  if (asset.get("type") === "script") {
717
1074
  throw new Error("Use the script text writer for script assets: " + params.assetId);
@@ -751,7 +1108,11 @@
751
1108
  };
752
1109
  }
753
1110
 
754
- async function renameAsset(params) {
1111
+ function writeAssetFile(params) {
1112
+ return withWorkspaceMutationSuppression(() => writeAssetFileInner(params));
1113
+ }
1114
+
1115
+ async function renameAssetInner(params) {
755
1116
  const asset = requireEditorAsset(params.assetId);
756
1117
  const assets = window.editor.api.globals.assets;
757
1118
  const folderResult = await resolveFolder(assets, params);
@@ -775,15 +1136,31 @@
775
1136
  return { asset: readAsset(asset), createdFolders: folderResult.created.map(readAsset) };
776
1137
  }
777
1138
 
778
- async function writeScriptText(params) {
1139
+ function renameAsset(params) {
1140
+ return withWorkspaceMutationSuppression(() => renameAssetInner(params));
1141
+ }
1142
+
1143
+ function textMimeForAssetType(type) {
1144
+ if (type === "script") return "text/javascript";
1145
+ if (type === "css") return "text/css";
1146
+ if (type === "html") return "text/html";
1147
+ if (type === "json") return "application/json";
1148
+ return "text/plain";
1149
+ }
1150
+
1151
+ async function writeAssetTextInner(params, requireScript = false) {
779
1152
  const asset = requireEditorAsset(params.assetId);
780
- if (asset.get("type") !== "script") {
1153
+ const type = String(asset.get("type") || "");
1154
+ if (requireScript && type !== "script") {
781
1155
  throw new Error("Asset is not a script: " + params.assetId);
782
1156
  }
783
- const filename = asset.get("file.filename") || asset.get("name");
1157
+ if (!TEXT_ASSET_TYPES.has(type)) {
1158
+ throw new Error("Asset is not a text asset: " + params.assetId);
1159
+ }
1160
+ const filename = String(params.filename || asset.get("file.filename") || asset.get("name") || "asset.txt");
784
1161
  const form = new FormData();
785
1162
  form.append("filename", filename);
786
- form.append("file", new Blob([String(params.text || "")], { type: "text/javascript" }), filename);
1163
+ form.append("file", new Blob([String(params.text || "")], { type: textMimeForAssetType(type) }), filename);
787
1164
  const branchId =
788
1165
  (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
789
1166
  (window.config && window.config.branch && window.config.branch.id);
@@ -801,21 +1178,281 @@
801
1178
  throw new Error(body.error || "Failed to update script asset.");
802
1179
  }
803
1180
 
804
- const parseResult = await new Promise((resolve, reject) => {
805
- window.editor.call("scripts:parse", asset.observer, (error, data) => {
806
- if (error) reject(new Error(String(error)));
807
- else resolve(data || {});
1181
+ let scripts = {};
1182
+ let parsed = false;
1183
+ if (type === "script" && window.editor && typeof window.editor.call === "function") {
1184
+ const parseResult = await new Promise((resolve, reject) => {
1185
+ window.editor.call("scripts:parse", asset.observer, (error, data) => {
1186
+ if (error) reject(new Error(String(error)));
1187
+ else resolve(data || {});
1188
+ });
808
1189
  });
809
- });
1190
+ scripts = parseResult.scripts || {};
1191
+ parsed = true;
1192
+ }
810
1193
  return {
811
1194
  assetId: String(asset.get("id")),
812
1195
  filename,
813
- parsed: true,
814
- scripts: parseResult.scripts || {},
1196
+ parsed,
1197
+ scripts,
815
1198
  response: body
816
1199
  };
817
1200
  }
818
1201
 
1202
+ function writeScriptText(params) {
1203
+ return withWorkspaceMutationSuppression(() => writeAssetTextInner(params, true));
1204
+ }
1205
+
1206
+ function writeAssetText(params) {
1207
+ return withWorkspaceMutationSuppression(() => writeAssetTextInner(params, false));
1208
+ }
1209
+
1210
+ function createDataAsset(params) {
1211
+ return withWorkspaceMutationSuppression(async () => {
1212
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
1213
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
1214
+ }
1215
+ const type = String(params.type || "");
1216
+ if (!DATA_JSON_ASSET_TYPES.has(type)) {
1217
+ throw new Error("Unsupported structured JSON asset type: " + type);
1218
+ }
1219
+ const name = String(params.name || "New Asset");
1220
+ const assets = window.editor.api.globals.assets;
1221
+ const folderResult = await resolveFolder(assets, params);
1222
+ const defaultData = window.editor.api.globals.schema?.assets?.getDefaultData?.(type) || {};
1223
+ const incomingData = params.data && typeof params.data === "object" && !Array.isArray(params.data)
1224
+ ? params.data
1225
+ : {};
1226
+ const mergedData = { ...defaultData, ...incomingData };
1227
+ const asset = await assets.upload(
1228
+ {
1229
+ name,
1230
+ type,
1231
+ folder: folderResult.folder || undefined,
1232
+ preload: params.preload !== false,
1233
+ tags: Array.isArray(params.tags) ? params.tags : [],
1234
+ data: mergedData
1235
+ },
1236
+ null
1237
+ );
1238
+ if (asset && typeof asset.set === "function") {
1239
+ if (Array.isArray(params.tags)) asset.set("tags", params.tags);
1240
+ if (typeof params.preload === "boolean") asset.set("preload", params.preload);
1241
+ for (const [key, value] of Object.entries(incomingData)) {
1242
+ asset.set("data." + key, value);
1243
+ }
1244
+ }
1245
+ return {
1246
+ asset: readAsset(asset),
1247
+ createdFolders: folderResult.created.map(readAsset)
1248
+ };
1249
+ });
1250
+ }
1251
+
1252
+ function patchAssetData(params) {
1253
+ return withWorkspaceMutationSuppression(async () => {
1254
+ const asset = requireEditorAsset(params.assetId);
1255
+ const type = String(asset.get("type") || "");
1256
+ if (!DATA_JSON_ASSET_TYPES.has(type)) {
1257
+ throw new Error("Asset is not a structured JSON asset: " + params.assetId);
1258
+ }
1259
+ if (typeof params.name === "string" && params.name && params.name !== asset.get("name")) {
1260
+ await new Promise((resolve, reject) => {
1261
+ const error = window.editor.call("assets:rename", asset.observer, params.name, (callbackError) => {
1262
+ if (callbackError) reject(new Error(String(callbackError)));
1263
+ else resolve();
1264
+ });
1265
+ if (error) reject(new Error(String(error)));
1266
+ });
1267
+ }
1268
+ if (Object.prototype.hasOwnProperty.call(params, "folder")) {
1269
+ const assets = window.editor.api.globals.assets;
1270
+ const folderResult = await resolveFolder(assets, params);
1271
+ if (typeof window.editor.call === "function") {
1272
+ const error = window.editor.call(
1273
+ "assets:fs:move",
1274
+ [asset.observer],
1275
+ folderResult.folder ? folderResult.folder.observer : null
1276
+ );
1277
+ if (error) throw new Error(String(error));
1278
+ }
1279
+ }
1280
+ if (typeof params.preload === "boolean") asset.set("preload", params.preload);
1281
+ if (Array.isArray(params.tags)) asset.set("tags", params.tags);
1282
+ for (const path of Array.isArray(params.unsets) ? params.unsets : []) {
1283
+ if (typeof asset.unset === "function") asset.unset("data." + path);
1284
+ else if (asset.observer && typeof asset.observer.unset === "function") asset.observer.unset("data." + path);
1285
+ }
1286
+ for (const change of Array.isArray(params.sets) ? params.sets : []) {
1287
+ if (change && typeof change.path === "string") {
1288
+ asset.set("data." + change.path, change.value);
1289
+ }
1290
+ }
1291
+ return { asset: readAsset(asset) };
1292
+ });
1293
+ }
1294
+
1295
+ function deleteAssets(params) {
1296
+ return withWorkspaceMutationSuppression(async () => {
1297
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
1298
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
1299
+ }
1300
+ const assets = window.editor.api.globals.assets;
1301
+ const ids = Array.isArray(params.assetIds) ? params.assetIds : [params.assetId];
1302
+ const found = [];
1303
+ const deletedIds = [];
1304
+ for (const rawId of ids) {
1305
+ if (rawId === undefined || rawId === null) continue;
1306
+ const asset = assets.get(Number(rawId));
1307
+ if (asset) {
1308
+ found.push(asset);
1309
+ deletedIds.push(String(asset.get("id")));
1310
+ }
1311
+ }
1312
+ if (!found.length) return { deletedIds: [] };
1313
+ if (typeof assets.delete === "function") {
1314
+ await assets.delete(found);
1315
+ } else if (typeof window.editor.call === "function") {
1316
+ window.editor.call("assets:delete", found.map((item) => item.observer || item));
1317
+ } else {
1318
+ throw new Error("Editor assets delete API is unavailable.");
1319
+ }
1320
+ return { deletedIds };
1321
+ });
1322
+ }
1323
+
1324
+ async function readScene(params) {
1325
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
1326
+ throw new Error("Scene operations require a ready PlayCanvas Editor target.");
1327
+ }
1328
+ const requestedId = String(params.sceneId || getActiveSceneId() || "");
1329
+ if (!requestedId) throw new Error("sceneId is required.");
1330
+ const activeId = getActiveSceneId();
1331
+ if (activeId && requestedId === activeId) {
1332
+ const activeScene = readActiveScene();
1333
+ if (activeScene) return activeScene;
1334
+ }
1335
+ if (typeof window.editor.call !== "function") {
1336
+ throw new Error("Editor scenes:get method is unavailable.");
1337
+ }
1338
+ const data = await new Promise((resolve, reject) => {
1339
+ window.editor.call("scenes:get", requestedId, (error, sceneData) => {
1340
+ if (error) reject(new Error(typeof error === "string" ? error : JSON.stringify(error)));
1341
+ else resolve(sceneData);
1342
+ });
1343
+ });
1344
+ if (!data || typeof data !== "object") {
1345
+ throw new Error("Scene not found: " + requestedId);
1346
+ }
1347
+ return {
1348
+ id: String(data.id || requestedId),
1349
+ name: String(data.name || "Scene"),
1350
+ active: false,
1351
+ modified: data.modified ? String(data.modified) : null,
1352
+ settings: clonePlainJson(data.settings) || {},
1353
+ entities: clonePlainJson(data.entities) || {}
1354
+ };
1355
+ }
1356
+
1357
+ function patchScene(params) {
1358
+ return withWorkspaceMutationSuppression(async () => {
1359
+ const globals = window.editor && window.editor.api && window.editor.api.globals;
1360
+ if (!globals || !globals.entities || !globals.entities.root) {
1361
+ throw new Error("Active scene is not loaded in the PlayCanvas Editor.");
1362
+ }
1363
+ const activeId = getActiveSceneId();
1364
+ if (params.sceneId && activeId && String(params.sceneId) !== activeId) {
1365
+ throw new Error(`Scene ${params.sceneId} is not active in the Editor (active: ${activeId}).`);
1366
+ }
1367
+ if (typeof params.name === "string" && params.name.trim()) {
1368
+ const nextName = params.name.trim();
1369
+ const currentRealtimeScene = globals.realtime && globals.realtime.scenes && globals.realtime.scenes.current;
1370
+ if (currentRealtimeScene && currentRealtimeScene.data && typeof window.editor.call === "function") {
1371
+ const oldName = currentRealtimeScene.data.name || "";
1372
+ if (oldName !== nextName) {
1373
+ window.editor.call("realtime:scene:op", { p: ["name"], od: oldName, oi: nextName });
1374
+ if (typeof window.editor.emit === "function") window.editor.emit("scene:name", nextName);
1375
+ }
1376
+ }
1377
+ if (window.config && window.config.scene) window.config.scene.name = nextName;
1378
+ }
1379
+ const entities = globals.entities;
1380
+
1381
+ for (const item of Array.isArray(params.creates) ? params.creates : []) {
1382
+ if (!item || !item.entity) continue;
1383
+ const data = { ...item.entity, children: [] };
1384
+ if (typeof data.parent === "string") {
1385
+ const parent = entities.get(data.parent);
1386
+ if (!parent) throw new Error("Parent entity not found: " + data.parent);
1387
+ data.parent = parent;
1388
+ } else if (!data.parent) {
1389
+ data.parent = entities.root;
1390
+ }
1391
+ const options = { history: true, select: false };
1392
+ if (Number.isInteger(item.index) && item.index >= 0) options.index = item.index;
1393
+ const created = entities.create(data, options);
1394
+ if (!created) throw new Error("Failed to create entity " + (data.resource_id || data.name || ""));
1395
+ }
1396
+
1397
+ for (const move of Array.isArray(params.reparents) ? params.reparents : []) {
1398
+ const entity = entities.get(move.id);
1399
+ const parent = entities.get(move.parent);
1400
+ if (!entity || !parent) continue;
1401
+ if (typeof entity.reparent === "function") {
1402
+ entity.reparent(parent, move.index, { history: true, preserveTransform: false });
1403
+ } else if (typeof entities.reparent === "function") {
1404
+ await entities.reparent([{ entity, parent, index: move.index }], {
1405
+ history: true,
1406
+ preserveTransform: false
1407
+ });
1408
+ }
1409
+ }
1410
+
1411
+ for (const update of Array.isArray(params.updates) ? params.updates : []) {
1412
+ const entity = entities.get(update.id);
1413
+ if (!entity) continue;
1414
+ for (const comp of Array.isArray(update.removedComponents) ? update.removedComponents : []) {
1415
+ if (entity.get("components." + comp)) entity.removeComponent(comp);
1416
+ }
1417
+ if (update.addedComponents && typeof update.addedComponents === "object") {
1418
+ for (const [comp, compData] of Object.entries(update.addedComponents)) {
1419
+ if (entity.get("components." + comp)) entity.set("components." + comp, compData || {});
1420
+ else entity.addComponent(comp, compData || {});
1421
+ }
1422
+ }
1423
+ for (const path of Array.isArray(update.unsets) ? update.unsets : []) {
1424
+ if (typeof entity.unset === "function") entity.unset(path);
1425
+ else if (entity.observer && typeof entity.observer.unset === "function") entity.observer.unset(path);
1426
+ }
1427
+ for (const change of Array.isArray(update.sets) ? update.sets : []) {
1428
+ if (change && typeof change.path === "string") entity.set(change.path, change.value);
1429
+ }
1430
+ }
1431
+
1432
+ const deleteIds = Array.isArray(params.deletes) ? params.deletes : [];
1433
+ if (deleteIds.length) {
1434
+ const toDelete = deleteIds.map((id) => entities.get(id)).filter(Boolean);
1435
+ if (toDelete.length) {
1436
+ if (typeof entities.delete === "function") await entities.delete(toDelete);
1437
+ else for (const entity of toDelete) entities.remove(entity);
1438
+ }
1439
+ }
1440
+
1441
+ const sceneSettings = globals.settings && globals.settings.scene;
1442
+ if (sceneSettings) {
1443
+ for (const path of Array.isArray(params.settingsUnsets) ? params.settingsUnsets : []) {
1444
+ if (typeof sceneSettings.unset === "function") sceneSettings.unset(path);
1445
+ else if (sceneSettings.observer && typeof sceneSettings.observer.unset === "function") sceneSettings.observer.unset(path);
1446
+ }
1447
+ for (const change of Array.isArray(params.settingsSets) ? params.settingsSets : []) {
1448
+ if (change && typeof change.path === "string") sceneSettings.set(change.path, change.value);
1449
+ }
1450
+ }
1451
+
1452
+ return { scene: readActiveScene() };
1453
+ });
1454
+ }
1455
+
819
1456
  function plainAssetJson(asset) {
820
1457
  if (!asset) return null;
821
1458
  if (typeof asset.json === "function") return asset.json();
@@ -1306,7 +1943,7 @@
1306
1943
  return { affected };
1307
1944
  }
1308
1945
 
1309
- async function uploadAsset(params) {
1946
+ async function uploadAssetInner(params) {
1310
1947
  if (!params.base64) throw new Error("base64 file content is required.");
1311
1948
  if (!params.name) throw new Error("name is required.");
1312
1949
 
@@ -1333,6 +1970,10 @@
1333
1970
  };
1334
1971
  }
1335
1972
 
1973
+ function uploadAsset(params) {
1974
+ return withWorkspaceMutationSuppression(() => uploadAssetInner(params));
1975
+ }
1976
+
1336
1977
  function focusViewport(params) {
1337
1978
  const ids = Array.isArray(params.ids) && params.ids.length ? params.ids : [params.id];
1338
1979
  const entitiesApi = window.editor.api.globals.entities;
@@ -1389,6 +2030,28 @@
1389
2030
  }
1390
2031
 
1391
2032
  async function callMethod(method, params, requestId) {
2033
+ if (method === "bridge:importJob") {
2034
+ if (getTargetKind() !== "editor" || !window.config?.selfhost || !window.editor?.api?.globals) {
2035
+ throw Object.assign(new Error("Selfhost Editor required"), { code: "SELFHOST_EDITOR_REQUIRED" });
2036
+ }
2037
+ if (!window.editor.methods?.has("assets:import:request")) {
2038
+ throw Object.assign(new Error("Refresh the upgraded selfhost Editor before importing"), { code: "PROCESSING_EDITOR_UNSUPPORTED" });
2039
+ }
2040
+ const api = window.editor.api.globals;
2041
+ const context = { projectId: api.projectId, branchId: api.branchId };
2042
+ const action = params.action;
2043
+ let path, verb = "GET", body;
2044
+ if (action === "list") path = `/jobs?projectId=${api.projectId}&branchId=${encodeURIComponent(api.branchId)}`;
2045
+ else if (action === "submit") {
2046
+ if (!/^\d+$/.test(params.assetId || "") || !["model", "texture"].includes(params.kind)) throw new Error("Invalid import submission");
2047
+ path = `/${params.assetId}/${params.kind === "texture" ? "texture" : "reimport"}`;
2048
+ verb = "POST"; body = { ...context, options: params.options || {} };
2049
+ } else if (["status", "cancel", "retry"].includes(action) && /^[a-zA-Z0-9-]{1,100}$/.test(params.jobId || "")) {
2050
+ path = `/jobs/${params.jobId}${action === "status" ? "" : `/${action}`}`;
2051
+ if (action !== "status") { verb = "POST"; body = {}; }
2052
+ } else throw new Error("Invalid import action");
2053
+ return window.editor.call("assets:import:request", path, verb, body);
2054
+ }
1392
2055
  if (method === "bridge:ping") return { pong: true, href: location.href };
1393
2056
  if (method === "bridge:describeTarget") return describeTarget();
1394
2057
  if (method === "bridge:eval") return evalInPage(params || {}, requestId);
@@ -1408,6 +2071,12 @@
1408
2071
  if (method === "bridge:writeAssetFile") return writeAssetFile(params || {});
1409
2072
  if (method === "bridge:renameAsset") return renameAsset(params || {});
1410
2073
  if (method === "bridge:writeScriptText") return writeScriptText(params || {});
2074
+ if (method === "bridge:writeAssetText") return writeAssetText(params || {});
2075
+ if (method === "bridge:createDataAsset") return createDataAsset(params || {});
2076
+ if (method === "bridge:patchAssetData") return patchAssetData(params || {});
2077
+ if (method === "bridge:deleteAssets") return deleteAssets(params || {});
2078
+ if (method === "bridge:readScene") return readScene(params || {});
2079
+ if (method === "bridge:patchScene") return patchScene(params || {});
1411
2080
  throw new Error(`Unknown bridge method: ${method}`);
1412
2081
  }
1413
2082