@panomc/sdk 1.0.0-dev.9 → 2.0.0-dev.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.
Files changed (166) hide show
  1. package/api/routes.core.json +3702 -0
  2. package/bin/api/__tests__/api-compat.test.mjs +97 -0
  3. package/bin/api/__tests__/check-paths.test.mjs +113 -0
  4. package/bin/api/__tests__/cli.test.mjs +44 -0
  5. package/bin/api/__tests__/extract-routes.test.mjs +132 -0
  6. package/bin/api/__tests__/fixtures/core-new/Pano/api/paths.old-new.json +82 -0
  7. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  8. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  9. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  10. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  11. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  12. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  13. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  14. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  15. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  16. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  17. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  18. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  19. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  20. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  21. package/bin/api/__tests__/fixtures/plugin-new/api/paths.old-new.json +66 -0
  22. package/bin/api/__tests__/fixtures/plugin-new/build.gradle.kts +42 -0
  23. package/bin/api/__tests__/fixtures/plugin-new/gradle.properties +4 -0
  24. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  25. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  26. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  27. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  28. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  29. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  30. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  31. package/bin/api/__tests__/fixtures/plugin-new/src/panel/Things.js +4 -0
  32. package/bin/api/__tests__/fixtures/plugin-new/src/theme/Logo.svelte +9 -0
  33. package/bin/api/__tests__/fixtures/plugin-new/src/theme/api.js +29 -0
  34. package/bin/api/__tests__/fixtures/plugin-old/build.gradle.kts +22 -0
  35. package/bin/api/__tests__/fixtures/plugin-old/gradle.properties +4 -0
  36. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  37. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  38. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  39. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  40. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  41. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  42. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  43. package/bin/api/__tests__/fixtures/plugin-old/src/panel/Things.js +4 -0
  44. package/bin/api/__tests__/fixtures/plugin-old/src/theme/Logo.svelte +9 -0
  45. package/bin/api/__tests__/fixtures/plugin-old/src/theme/api.js +29 -0
  46. package/bin/api/__tests__/fixtures/refusals/gradle.properties +1 -0
  47. package/bin/api/__tests__/fixtures/refusals/src/main/kotlin/x/Bad.kt +39 -0
  48. package/bin/api/__tests__/fixtures/unresolved/src/main/kotlin/x/Orphan.kt +19 -0
  49. package/bin/api/__tests__/helpers.mjs +48 -0
  50. package/bin/api/__tests__/migrate-v1.test.mjs +377 -0
  51. package/bin/api/__tests__/openapi-snapshot.test.mjs +120 -0
  52. package/bin/api/api-compat.mjs +204 -0
  53. package/bin/api/check-paths.mjs +135 -0
  54. package/bin/api/cli.mjs +83 -0
  55. package/bin/api/extract-routes.mjs +129 -0
  56. package/bin/api/js-scan.mjs +337 -0
  57. package/bin/api/kotlin.mjs +366 -0
  58. package/bin/api/migrate-v1.mjs +330 -0
  59. package/bin/api/openapi-snapshot.mjs +112 -0
  60. package/bin/api/project.mjs +172 -0
  61. package/bin/api/rename-table.mjs +66 -0
  62. package/bin/api/util.mjs +194 -0
  63. package/bin/pano-api.js +5 -0
  64. package/build/plugin-api-rollup.js +46 -0
  65. package/core/css/pano-tokens.css +225 -0
  66. package/core/favicon/apple-touch-icon.png +0 -0
  67. package/core/favicon/favicon-96x96.png +0 -0
  68. package/core/favicon/favicon.ico +0 -0
  69. package/core/favicon/favicon.svg +1 -0
  70. package/core/favicon/site.webmanifest +21 -0
  71. package/core/favicon/web-app-manifest-192x192.png +0 -0
  72. package/core/favicon/web-app-manifest-512x512.png +0 -0
  73. package/core/favicon_old/android-icon-144x144.png +0 -0
  74. package/core/favicon_old/android-icon-192x192.png +0 -0
  75. package/core/favicon_old/android-icon-36x36.png +0 -0
  76. package/core/favicon_old/android-icon-48x48.png +0 -0
  77. package/core/favicon_old/android-icon-72x72.png +0 -0
  78. package/core/favicon_old/android-icon-96x96.png +0 -0
  79. package/core/favicon_old/apple-icon-114x114.png +0 -0
  80. package/core/favicon_old/apple-icon-120x120.png +0 -0
  81. package/core/favicon_old/apple-icon-144x144.png +0 -0
  82. package/core/favicon_old/apple-icon-152x152.png +0 -0
  83. package/core/favicon_old/apple-icon-180x180.png +0 -0
  84. package/core/favicon_old/apple-icon-57x57.png +0 -0
  85. package/core/favicon_old/apple-icon-60x60.png +0 -0
  86. package/core/favicon_old/apple-icon-72x72.png +0 -0
  87. package/core/favicon_old/apple-icon-76x76.png +0 -0
  88. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  89. package/core/favicon_old/apple-icon.png +0 -0
  90. package/core/favicon_old/browserconfig.xml +11 -0
  91. package/core/favicon_old/favicon-16x16.png +0 -0
  92. package/core/favicon_old/favicon-32x32.png +0 -0
  93. package/core/favicon_old/favicon-96x96.png +0 -0
  94. package/core/favicon_old/favicon.ico +0 -0
  95. package/core/favicon_old/manifest.json +41 -0
  96. package/core/favicon_old/ms-icon-144x144.png +0 -0
  97. package/core/favicon_old/ms-icon-150x150.png +0 -0
  98. package/core/favicon_old/ms-icon-310x310.png +0 -0
  99. package/core/favicon_old/ms-icon-70x70.png +0 -0
  100. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  101. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  102. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  103. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  104. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  105. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  106. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  107. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  108. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  109. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  110. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  111. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  112. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  113. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  114. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  115. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  116. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  117. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  118. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  119. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  120. package/core/js/ControllerRegistry.js +421 -0
  121. package/core/js/NotificationManager.js +62 -0
  122. package/core/js/PluginAPI.js +39 -0
  123. package/core/js/PluginManager.js +851 -0
  124. package/core/js/RouteMatcher.js +142 -0
  125. package/core/js/__tests__/ControllerRegistry.test.js +378 -0
  126. package/core/js/__tests__/NotificationManager.test.js +57 -0
  127. package/core/js/__tests__/PluginAPI.test.js +25 -0
  128. package/core/js/__tests__/RouteMatcher.test.js +33 -0
  129. package/core/js/__tests__/accessClient.test.js +582 -0
  130. package/core/js/__tests__/api.util.v1.test.js +336 -0
  131. package/core/js/__tests__/appStores.test.js +47 -0
  132. package/core/js/__tests__/devBounce.test.js +28 -0
  133. package/core/js/__tests__/html.util.test.js +18 -0
  134. package/core/js/__tests__/pluginFolder.util.test.js +106 -0
  135. package/core/js/__tests__/pluginPackage.test.js +134 -0
  136. package/core/js/__tests__/pluginUiZip.test.js +47 -0
  137. package/core/js/__tests__/sdkLevel.test.js +34 -0
  138. package/core/js/api.util.js +433 -0
  139. package/core/js/appStores.js +93 -0
  140. package/core/js/basePath.js +10 -0
  141. package/core/js/html.util.js +26 -0
  142. package/core/js/pluginFolder.util.js +95 -0
  143. package/core/js/tooltip.util.js +59 -0
  144. package/core/js/variables.js +95 -0
  145. package/core/js/version.util.js +100 -0
  146. package/core/scss/_pano-tokens.scss +51 -0
  147. package/core/scss/custom-bootstrap.scss +210 -0
  148. package/core/scss/fonts.scss +85 -0
  149. package/core/scss/main.scss +389 -0
  150. package/core/scss/themes.scss +122 -0
  151. package/package.json +63 -11
  152. package/src/__tests__/controllers.test.js +220 -0
  153. package/src/__tests__/views.spike.test.js +472 -0
  154. package/src/components/{index.js → panel.js} +9 -7
  155. package/src/components/theme.js +18 -0
  156. package/src/controllers.js +127 -0
  157. package/src/index.js +1 -1
  158. package/src/runtime-specifiers.js +88 -0
  159. package/src/svelte.js +3 -2
  160. package/src/types.js +5 -3
  161. package/src/utils/api.js +42 -1
  162. package/src/utils/auth.js +8 -0
  163. package/src/utils/component.js +4 -2
  164. package/src/utils/route.js +16 -0
  165. package/src/utils/text.js +8 -0
  166. package/src/views.js +29 -0
@@ -0,0 +1,851 @@
1
+ import fs from "fs";
2
+
3
+ import { error as httpError } from "@sveltejs/kit";
4
+ import { browser, dev } from "$app/env";
5
+ import { get, writable } from "svelte/store";
6
+ import ApiUtil from "$lib/api.util.js";
7
+ import { base } from "./basePath.js";
8
+
9
+ import { init as initPluginAPI, panoApiClient, panoApiServer } from "$lib/PluginAPI.js";
10
+ import { PanoPlugin } from "@panomc/sdk";
11
+ import { findMatch } from "./RouteMatcher.js";
12
+ import { removePluginUiFiles, replacePluginUiFiles, readPluginPackage } from "./pluginFolder.util.js";
13
+
14
+ export let registeredPages = {};
15
+
16
+ export { findMatch };
17
+
18
+ let path, url, admZip;
19
+
20
+ let serverSidePrepared = false;
21
+ let serverSideInitialized = false;
22
+ let lastProcessedBackendHash = null;
23
+ let lastProcessedFrontendHash = null;
24
+ let clientSideInitialized = false;
25
+ let clientSidePluginHash = null;
26
+
27
+ // In-flight preparePlugins promise. Filesystem mutations in verifyPlugins are not safe to
28
+ // interleave between concurrent SSR requests; concurrent runs were producing partial states
29
+ // where some files were being deleted while others were being read.
30
+ let preparePluginsInflight = null;
31
+
32
+ // In-flight initializePlugins promise, keyed by the frontend plugin hash it is building for.
33
+ // Without it, concurrent SSR requests each reset the shared module-global stores (registeredPages,
34
+ // livePluginInstances, the plugins store) mid-flight, racing each other into torn/blank plugin UI,
35
+ // double onLoad calls and transient false 404s. Claimed synchronously before any await.
36
+ let initializePluginsInflight = null;
37
+ let initializePluginsInflightHash = null;
38
+
39
+
40
+
41
+ if (!browser) {
42
+ const pathStuff = await import('path');
43
+ const urlStuff = await import('url');
44
+ const admZipStuff = await import('adm-zip');
45
+
46
+ path = pathStuff;
47
+ url = urlStuff;
48
+ admZip = admZipStuff.default;
49
+ }
50
+
51
+ export const plugins = writable({});
52
+
53
+ /** pluginId -> namespace, from each plugin folder's pano-plugin.json (old plugins have none). */
54
+ const pluginNamespaces = new Map();
55
+ let namespaceSink = null;
56
+
57
+ /** @returns {Record<string,string>} the pluginId -> ns table (the alias rule of the view registry) */
58
+ export function getPluginNamespaces() {
59
+ return Object.fromEntries(pluginNamespaces);
60
+ }
61
+
62
+ /** The view registry hands in a function that receives the pluginId -> ns table on every change. */
63
+ export function setNamespaceSink(fn) {
64
+ namespaceSink = typeof fn === 'function' ? fn : null;
65
+ if (namespaceSink) namespaceSink(getPluginNamespaces());
66
+ }
67
+
68
+ /** Reads pano-plugin.json into the plugin entry and the namespace table (theme process only). */
69
+ function applyPluginPackage(pluginId, plugin, pluginFolder) {
70
+ const pkg = readPluginPackage(pluginFolder);
71
+ const before = pluginNamespaces.get(pluginId);
72
+ if (pkg?.namespace) {
73
+ plugin.namespace = pkg.namespace;
74
+ if (pkg.styles !== undefined) plugin.styles = pkg.styles;
75
+ if (pkg.views !== undefined) plugin.views = pkg.views;
76
+ pluginNamespaces.set(pluginId, pkg.namespace);
77
+ } else {
78
+ delete plugin.namespace;
79
+ delete plugin.styles;
80
+ delete plugin.views;
81
+ pluginNamespaces.delete(pluginId);
82
+ }
83
+ if (namespaceSink && before !== pluginNamespaces.get(pluginId)) namespaceSink(getPluginNamespaces());
84
+ }
85
+
86
+ const pluginsFolder = 'plugins';
87
+ const manifestFileName = 'manifest.json';
88
+
89
+ function log(message) {
90
+ if (dev) console.log(`[Plugin Manager] ${message}`);
91
+ }
92
+
93
+ function error(message) {
94
+ if (dev) console.error(`[Plugin Manager] ${message}`);
95
+ }
96
+
97
+ function debug(message) {
98
+ if (dev) console.debug(`[Plugin Manager] ${message}`);
99
+ }
100
+
101
+ function createPluginsFolder() {
102
+ if (!fs.existsSync(pluginsFolder)) {
103
+ fs.mkdirSync(pluginsFolder, { recursive: true });
104
+ }
105
+ }
106
+
107
+ function isDirectory(path) {
108
+ try {
109
+ return fs.statSync(path).isDirectory();
110
+ } catch (error) {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ async function downloadAndExtractZip(file, outputDir) {
116
+ const arrayBuffer = await file.arrayBuffer();
117
+ const buffer = Buffer.from(arrayBuffer);
118
+ const zip = new admZip(buffer, {});
119
+
120
+ zip.extractAllTo(outputDir, true);
121
+ }
122
+
123
+ function readPluginsFromFolder(siteInfo) {
124
+ const readPluginsFolder = fs.readdirSync(pluginsFolder);
125
+
126
+ const plugins = {};
127
+
128
+ readPluginsFolder
129
+ .filter((pluginId) => isDirectory(path.join(pluginsFolder, pluginId)))
130
+ .forEach((pluginId) => {
131
+ try {
132
+ const manifestFile = fs.readFileSync(path.join(pluginsFolder, pluginId, manifestFileName), {
133
+ encoding: 'utf8',
134
+ flag: 'r',
135
+ });
136
+
137
+ plugins[pluginId] = JSON.parse(manifestFile);
138
+ } catch (_) {
139
+ // if (siteInfo.developmentMode) {
140
+ // plugins[pluginId] = {
141
+ // version: 'dev-build',
142
+ // uiHash: 'dev-build',
143
+ // };
144
+ // }
145
+ }
146
+ });
147
+
148
+ return plugins;
149
+ }
150
+
151
+ // Core endpoint GetPluginUiZipAPI; the path is relative to the API root, ApiUtil adds the version prefix (doc 04).
152
+ export async function downloadPluginUiZip(pluginId) {
153
+ return await ApiUtil.get({
154
+ path: `/plugins/${pluginId}/_/ui.zip`,
155
+ blob: true,
156
+ });
157
+ }
158
+
159
+ // A plugin folder counts as "intact" only if all three pieces produced by a real install
160
+ // are present: the root manifest.json and both the server/ and client/ subdirs. Anything
161
+ // else is a shell folder — left over from a download that 404'd, an extraction that
162
+ // produced an empty zip, an update that swapped out the old subdirs and then couldn't
163
+ // move new ones in, or a crashed install/update where the staging dir never got renamed
164
+ // into place. We need to recognize and purge these eagerly: readPluginsFromFolder silently
165
+ // drops them (manifest read fails → not in pluginsInFolder), so they slip past the rest
166
+ // of verifyPlugins and then make the install path's existsSync check think the plugin
167
+ // is "already there", which discards the fresh download.
168
+ function isPluginFolderIntact(pluginFolder) {
169
+ return (
170
+ fs.existsSync(path.join(pluginFolder, manifestFileName)) &&
171
+ isDirectory(path.join(pluginFolder, 'server')) &&
172
+ isDirectory(path.join(pluginFolder, 'client'))
173
+ );
174
+ }
175
+
176
+ function purgeIncompletePluginFolders() {
177
+ let entries;
178
+ try {
179
+ entries = fs.readdirSync(pluginsFolder);
180
+ } catch {
181
+ return;
182
+ }
183
+
184
+ entries.forEach((entry) => {
185
+ const entryPath = path.join(pluginsFolder, entry);
186
+ if (!isDirectory(entryPath)) return;
187
+
188
+ // Stale staging dirs from a previous crashed install/update (".pluginId.install.<pid>.<ts>"
189
+ // / ".pluginId.update.<pid>.<ts>"). The preparePluginsInflight lock guarantees no
190
+ // install is running in parallel with verifyPlugins, so any leading-dot dir here is
191
+ // dead and safe to remove.
192
+ if (entry.startsWith('.')) {
193
+ log(`Removing stale staging dir '${entry}'...`);
194
+ fs.rmSync(entryPath, { recursive: true, force: true });
195
+ return;
196
+ }
197
+
198
+ if (!isPluginFolderIntact(entryPath)) {
199
+ log(`Removing incomplete plugin UI files of '${entry}'...`);
200
+ removePluginUiFiles(entryPath);
201
+ // Also drop it from the live store if a previous run added it there.
202
+ plugins.update((p) => {
203
+ delete p[entry];
204
+ return p;
205
+ });
206
+ }
207
+ });
208
+ }
209
+
210
+ async function verifyPlugins(siteInfo) {
211
+ // this method is fully BFF (backend for front-end) SSR
212
+
213
+ const pluginsInfo = siteInfo.plugins;
214
+
215
+ // Phase 0: scrub any shell/staging folders before we trust readPluginsFromFolder's view.
216
+ // Doing this up front means the rest of verifyPlugins operates on a known-clean disk,
217
+ // which kills the failure mode where a half-installed folder kept making the install
218
+ // path's existsSync check throw away every fresh download. The caller's
219
+ // pluginsInFolder snapshot is discarded — we re-read after purge.
220
+ purgeIncompletePluginFolders();
221
+
222
+ const pluginsInFolder = readPluginsFromFolder(siteInfo);
223
+ const pluginIdInFolderList = Object.keys(pluginsInFolder);
224
+
225
+ // After Phase 0 every folder on disk is intact (manifest + server/ + client/), so
226
+ // pluginIdInFolderList only contains plugins we can trust. The legacy "fix broken
227
+ // folder" pass that used to live here is now redundant — Phase 0 covers every shape
228
+ // of brokenness it tried to repair, and does so before we trust the snapshot.
229
+ pluginIdInFolderList.forEach((pluginId) => {
230
+ // Wipe plugins the BE no longer reports (disabled, uninstalled, lost license, etc.).
231
+ if (!pluginsInfo[pluginId]) {
232
+ log(`Removing '${pluginId}' folder...`);
233
+
234
+ removePluginUiFiles(path.join(pluginsFolder, pluginId));
235
+
236
+ plugins.update((p) => {
237
+ delete p[pluginId];
238
+ return p;
239
+ });
240
+ return;
241
+ }
242
+
243
+ // Plugin is intact on disk and still wanted by the BE — surface it via the store.
244
+ //
245
+ // Dev mode used to WIPE every folder here on every SSR pass so `bun dev` rebuilds
246
+ // reach the page without needing the BE-side uiHash to roll. That opened a window
247
+ // spanning the whole re-download in which /plugins/<id>/resources/... 404'd: any
248
+ // browser module fetch racing an SSR pass failed, and when its one cache-busted
249
+ // retry landed in the same window the plugin was dropped for the entire session
250
+ // (page renders via SSR, then loses every plugin UI at CSR). Instead, poison the
251
+ // stored uiHash so the update pass below re-downloads just as eagerly, but through
252
+ // downloadAndInstallPlugin's staged download + atomic rename — the old build keeps
253
+ // serving until the new one is in place, so the missing-folder window collapses
254
+ // from ~download-time to the two-rename instant (which the browser-side
255
+ // cache-busted retry already absorbs).
256
+ plugins.update((p) => {
257
+ p[pluginId] = siteInfo.developmentMode
258
+ ? { ...pluginsInFolder[pluginId], uiHash: `dev-stale-${Date.now()}` }
259
+ : pluginsInFolder[pluginId];
260
+ return p;
261
+ });
262
+ });
263
+
264
+ // Drop store entries the current pluginIdInFolderList no longer backs (e.g. left
265
+ // over from a previous run before Phase 0 deleted the underlying folder).
266
+ Object.keys(get(plugins))
267
+ .filter((pluginId) => !pluginIdInFolderList.includes(pluginId))
268
+ .forEach((pluginId) => {
269
+ log(`Removing plugin '${pluginId}'...`);
270
+
271
+ plugins.update((p) => {
272
+ delete p[pluginId];
273
+ return p;
274
+ });
275
+ });
276
+
277
+ // Install plugin if it exists in pluginsInfo (BE) and not installed
278
+ const notInstalledPlugins = Object.keys(pluginsInfo).filter(
279
+ // this prevents it must be enabled and loaded in BE, otherwise UI is null
280
+ (pluginId) => !get(plugins)[pluginId],
281
+ );
282
+
283
+ await Promise.all(
284
+ notInstalledPlugins.map((pluginId) =>
285
+ downloadAndInstallPlugin(pluginId, pluginsInfo[pluginId], 'install'),
286
+ ),
287
+ );
288
+
289
+ // Update plugins whose on-disk version/uiHash doesn't match what the backend now serves.
290
+ // This is where dev-mode `bun dev` rebuilds get picked up (BE bumps the hash, we re-fetch).
291
+ await Promise.all(
292
+ Object.keys(get(plugins)).map(async (pluginId) => {
293
+ const pluginInfoManifest = pluginsInfo[pluginId];
294
+ if (!pluginInfoManifest) return;
295
+
296
+ const pluginManifest = get(plugins)[pluginId];
297
+ if (
298
+ pluginManifest.version === pluginInfoManifest.version &&
299
+ pluginManifest.uiHash === pluginInfoManifest.uiHash
300
+ ) {
301
+ return;
302
+ }
303
+
304
+ await downloadAndInstallPlugin(pluginId, pluginInfoManifest, 'update');
305
+ }),
306
+ );
307
+ }
308
+
309
+ /**
310
+ * Download the plugin-ui.zip for a plugin and atomically replace its folder with the new
311
+ * content. Used for both first-time installs and updates — the two used to have separate
312
+ * code paths and the update path's per-subdir swap could leave the folder as a manifest-
313
+ * only shell when the downloaded zip was malformed (no server/ or no client/ inside).
314
+ * One code path means one set of invariants to enforce.
315
+ *
316
+ * Invariant after a successful return: pluginFolder contains manifest.json + server/ +
317
+ * client/, and the `plugins` store entry matches what's on disk.
318
+ *
319
+ * On any failure (download error, malformed zip, missing server/ or client/, fs error)
320
+ * we leave the previous on-disk state untouched (so an old working build keeps serving)
321
+ * and drop the plugin from the store so the rest of the SSR pass and the browser-side
322
+ * loader skip it cleanly instead of trying to import files that don't exist. The
323
+ * `bun dev` workflow is unaffected: BE bumps the uiHash on rebuild, this function runs,
324
+ * and the new build replaces the old one wholesale.
325
+ */
326
+ async function downloadAndInstallPlugin(pluginId, pluginManifest, mode) {
327
+ const pluginFolder = path.join(pluginsFolder, pluginId);
328
+ const tmpDir = path.join(pluginsFolder, `.${pluginId}.${mode}.${process.pid}.${Date.now()}`);
329
+
330
+ log(`${mode === 'install' ? 'Installing' : 'Updating'} plugin '${pluginId}'...`);
331
+ log(`Downloading '${pluginId}'...`);
332
+
333
+ try {
334
+ const file = await downloadPluginUiZip(pluginId);
335
+ await downloadAndExtractZip(file, tmpDir);
336
+
337
+ // Skip plugins whose download didn't yield a valid UI build. This is the symptom of
338
+ // either a 404/empty response that adm-zip didn't reject, or a publisher mistake.
339
+ // Either way we don't want to commit a manifest-only shell folder to disk.
340
+ if (
341
+ !isDirectory(path.join(tmpDir, 'server')) ||
342
+ !isDirectory(path.join(tmpDir, 'client'))
343
+ ) {
344
+ fs.rmSync(tmpDir, { recursive: true, force: true });
345
+ error(`Plugin '${pluginId}' download is missing server/ or client/ — skipping.`);
346
+ plugins.update((p) => {
347
+ delete p[pluginId];
348
+ return p;
349
+ });
350
+ return;
351
+ }
352
+
353
+ fs.writeFileSync(path.join(tmpDir, manifestFileName), JSON.stringify(pluginManifest, null, 2));
354
+
355
+ // Full-folder swap: rm-rf the old (Phase 0 already removed anything broken; the only
356
+ // case `pluginFolder` exists here is a clean update), then rename our staged dir in.
357
+ // The window where pluginFolder is briefly missing is the two-rename interval —
358
+ // microseconds — and Phase 0 + the inflight lock guarantee nothing else is reading
359
+ // mid-swap from SSR. Browser-side imports race against rename naturally; if one
360
+ // lands in the gap it 404s, and the PluginManager's reload-once retry resolves it.
361
+ // Only the UI-owned entries (client/, server/, manifest.json) are swapped: the folder is
362
+ // also the plugin's data folder (config.conf, secret.key, ...) and must survive.
363
+ replacePluginUiFiles(tmpDir, pluginFolder);
364
+
365
+ plugins.update((p) => {
366
+ p[pluginId] = structuredClone(pluginManifest);
367
+ return p;
368
+ });
369
+
370
+ log(`'${pluginId}' successfully ${mode === 'install' ? 'installed' : 'updated'}.`);
371
+ } catch (e) {
372
+ fs.rmSync(tmpDir, { recursive: true, force: true });
373
+ error(`Failed to ${mode} plugin '${pluginId}': ${e?.message ?? e}`);
374
+ // Don't surface the error: a single bad plugin must not break SSR for the rest of
375
+ // the panel. Drop the entry so downstream code doesn't try to load it.
376
+ plugins.update((p) => {
377
+ delete p[pluginId];
378
+ return p;
379
+ });
380
+ }
381
+ }
382
+
383
+ export async function preparePlugins(siteInfo) {
384
+ // The backend is the source of truth for the plugin set. While it is unreachable
385
+ // (still booting, restarting, crashed) siteInfo arrives undefined/empty — fail with a
386
+ // real 503 instead of a TypeError-turned-500 with a stack trace, so proxies and
387
+ // monitoring see "temporarily unavailable" and the first request after the backend
388
+ // returns recovers normally.
389
+ if (!siteInfo || typeof siteInfo !== "object" || !siteInfo.plugins) {
390
+ throw httpError(503, "Pano backend is not reachable yet");
391
+ }
392
+
393
+ const currentBackendHash = JSON.stringify(siteInfo.plugins);
394
+
395
+ // Loop so that after awaiting another request's preparation we recheck the cache: it may
396
+ // have produced the state we need (then we exit immediately), or it may have produced a
397
+ // different state (then we claim a fresh run).
398
+ while (true) {
399
+ if (preparePluginsInflight) {
400
+ try { await preparePluginsInflight; } catch { /* the owner re-throws to its caller */ }
401
+ continue;
402
+ }
403
+
404
+ const isCacheHit = !browser && !siteInfo.developmentMode && serverSidePrepared && lastProcessedBackendHash === currentBackendHash;
405
+ if (isCacheHit) break;
406
+
407
+ // Claim the lock synchronously before any await — otherwise two callers can both observe
408
+ // `preparePluginsInflight === null` and race.
409
+ preparePluginsInflight = (async () => {
410
+ createPluginsFolder();
411
+ await verifyPlugins(siteInfo);
412
+ if (!browser) {
413
+ serverSidePrepared = true;
414
+ lastProcessedBackendHash = currentBackendHash;
415
+ }
416
+ })();
417
+ try {
418
+ await preparePluginsInflight;
419
+ } finally {
420
+ preparePluginsInflight = null;
421
+ }
422
+ break;
423
+ }
424
+
425
+ const newSiteInfoPlugins = {};
426
+ const loadedPlugins = get(plugins);
427
+ Object.keys(loadedPlugins).forEach((pluginId) => {
428
+ const plugin = loadedPlugins[pluginId];
429
+ // In some versions version is an object containing metadata, in others it's directly on the plugin.
430
+ const vObj = plugin.version;
431
+ const { version, uiHash } = (vObj && typeof vObj === 'object') ? vObj : plugin;
432
+ const deps = plugin.dependencies;
433
+ newSiteInfoPlugins[pluginId] = { version, uiHash, ...(deps ? { dependencies: deps } : {}) };
434
+ });
435
+ siteInfo.plugins = newSiteInfoPlugins;
436
+ }
437
+
438
+
439
+ function generateStablePluginHash(siteInfoPlugins) {
440
+ const stableData = {};
441
+ // Sort plugin ids so the hash is independent of object iteration order.
442
+ for (const id of Object.keys(siteInfoPlugins || {}).sort()) {
443
+ const plugin = siteInfoPlugins[id];
444
+ const vObj = plugin.version;
445
+ const { version, uiHash } = (vObj && typeof vObj === "object") ? vObj : plugin;
446
+ // Include dependencies (load-order relevant): a dep-only change must invalidate the init
447
+ // cache, otherwise the topological load order can go stale while version/uiHash are equal.
448
+ // Normalize to a sorted array so the dep set — not its declaration order — is what matters.
449
+ const deps = Array.isArray(plugin.dependencies) ? [...plugin.dependencies].sort() : [];
450
+ stableData[id] = { version, uiHash, dependencies: deps };
451
+ }
452
+ return JSON.stringify(stableData);
453
+ }
454
+
455
+ // Live plugin instances on the client. Re-init calls __destroy() on these so a
456
+ // plugin's onUnload runs and any subscriptions it registered via this._unsubscribers
457
+ // get cleaned up before its next onLoad (or before it disappears on disable/remove).
458
+ const livePluginInstances = new Map();
459
+
460
+ async function destroyLivePluginInstances() {
461
+ if (livePluginInstances.size === 0) return;
462
+ const entries = Array.from(livePluginInstances.entries());
463
+ livePluginInstances.clear();
464
+ await Promise.allSettled(
465
+ entries.map(async ([pluginId, instance]) => {
466
+ try {
467
+ await instance.__destroy?.();
468
+ } catch (e) {
469
+ if (dev) console.error(`[PluginManager] __destroy failed for ${pluginId}:`, e);
470
+ }
471
+ })
472
+ );
473
+ }
474
+
475
+ function isInitializeCacheHit(siteInfo, currentFrontendHash) {
476
+ // SSR cache: skip if already initialized with the same plugin set
477
+ if (!browser && !siteInfo.developmentMode && serverSideInitialized && lastProcessedFrontendHash === currentFrontendHash) {
478
+ return true;
479
+ }
480
+ // Client-side cache: skip if already initialized with the same plugin set
481
+ if (browser && clientSideInitialized && clientSidePluginHash === currentFrontendHash) {
482
+ return true;
483
+ }
484
+ return false;
485
+ }
486
+
487
+ async function doInitializePlugins(siteInfo, currentFrontendHash) {
488
+ // Build the new route table in a LOCAL map and swap the live binding atomically once it is
489
+ // fully populated, instead of clearing the live `registeredPages` and rebuilding it in place.
490
+ // Plugins register into the live binding from their onLoad (via PluginAPI), so we point it at
491
+ // the fresh map for the duration of the build and only ever expose a complete table — a
492
+ // reader (findMatch) racing a rebuild sees either the old complete table or the new complete
493
+ // one, never a half-cleared one.
494
+ const previousRegisteredPages = registeredPages;
495
+ const newRegisteredPages = {};
496
+ registeredPages = newRegisteredPages;
497
+
498
+ try {
499
+ if (browser) {
500
+ await destroyLivePluginInstances();
501
+ }
502
+
503
+ await initPluginAPI();
504
+
505
+ if (browser) {
506
+ const pluginsInfo = siteInfo.plugins;
507
+
508
+ plugins.set(pluginsInfo);
509
+ }
510
+
511
+ await loadPlugins(siteInfo);
512
+ } catch (e) {
513
+ // On failure, restore the previous complete table so we don't leave a partial one live.
514
+ registeredPages = previousRegisteredPages;
515
+ throw e;
516
+ }
517
+
518
+ if (!browser) {
519
+ serverSideInitialized = true;
520
+ lastProcessedFrontendHash = currentFrontendHash;
521
+ } else {
522
+ clientSideInitialized = true;
523
+ clientSidePluginHash = currentFrontendHash;
524
+ }
525
+ }
526
+
527
+ export async function initializePlugins(siteInfo) {
528
+ const currentFrontendHash = generateStablePluginHash(siteInfo.plugins);
529
+
530
+ // Loop so that after awaiting another request's in-flight init we recheck the cache: it may
531
+ // have produced exactly the state we need (exit), or a different one (claim a fresh run).
532
+ while (true) {
533
+ if (isInitializeCacheHit(siteInfo, currentFrontendHash)) return;
534
+
535
+ if (initializePluginsInflight) {
536
+ // Someone is already initializing. If it's for our hash, just await it and we're done;
537
+ // otherwise await it and re-loop to claim our own run against the now-settled state.
538
+ const sameHash = initializePluginsInflightHash === currentFrontendHash;
539
+ try { await initializePluginsInflight; } catch { /* the owner re-throws to its caller */ }
540
+ if (sameHash && isInitializeCacheHit(siteInfo, currentFrontendHash)) return;
541
+ continue;
542
+ }
543
+
544
+ // Claim the lock synchronously before any await — otherwise two callers can both observe
545
+ // `initializePluginsInflight === null` and race, each resetting the shared stores.
546
+ initializePluginsInflightHash = currentFrontendHash;
547
+ initializePluginsInflight = doInitializePlugins(siteInfo, currentFrontendHash);
548
+ try {
549
+ await initializePluginsInflight;
550
+ } finally {
551
+ initializePluginsInflight = null;
552
+ initializePluginsInflightHash = null;
553
+ }
554
+ return;
555
+ }
556
+ }
557
+
558
+
559
+ const moduleCache = new Map();
560
+
561
+ function buildPluginDependencyGraph(loadedPlugins) {
562
+ const pluginIds = new Set(Object.keys(loadedPlugins));
563
+ const graph = {};
564
+ for (const pluginId of pluginIds) {
565
+ const plugin = loadedPlugins[pluginId];
566
+ // Only include dependencies that are actually loaded
567
+ const deps = (plugin.dependencies || []).filter(dep => pluginIds.has(dep));
568
+ graph[pluginId] = deps;
569
+ }
570
+ return graph;
571
+ }
572
+
573
+ function topologicalSortPlugins(graph) {
574
+ const inDegree = {};
575
+ const adj = {};
576
+
577
+ for (const node of Object.keys(graph)) {
578
+ if (!(node in inDegree)) inDegree[node] = 0;
579
+ if (!(node in adj)) adj[node] = [];
580
+ }
581
+
582
+ for (const [node, deps] of Object.entries(graph)) {
583
+ for (const dep of deps) {
584
+ if (!(dep in adj)) {
585
+ adj[dep] = [];
586
+ }
587
+ if (!(dep in inDegree)) inDegree[dep] = 0;
588
+ adj[dep].push(node);
589
+ inDegree[node] = (inDegree[node] || 0) + 1;
590
+ }
591
+ }
592
+
593
+ const levels = [];
594
+ let queue = Object.keys(inDegree).filter(n => inDegree[n] === 0);
595
+
596
+ while (queue.length > 0) {
597
+ levels.push([...queue]);
598
+ const nextQueue = [];
599
+ for (const node of queue) {
600
+ for (const neighbor of (adj[node] || [])) {
601
+ inDegree[neighbor]--;
602
+ if (inDegree[neighbor] === 0) nextQueue.push(neighbor);
603
+ }
604
+ }
605
+ queue = nextQueue;
606
+ }
607
+
608
+ // Fallback: if circular deps prevent resolution, run remaining plugins
609
+ const resolved = new Set(levels.flat());
610
+ const unresolved = Object.keys(graph).filter(n => !resolved.has(n));
611
+ if (unresolved.length > 0) {
612
+ levels.push(unresolved);
613
+ }
614
+
615
+ return levels;
616
+ }
617
+
618
+ /**
619
+ * SDK 2.0: a plugin client or server module must export `panoSdk = 2` (the plugin kit's generated
620
+ * entry does). Anything else was built for @panomc/sdk 1.x and is dropped from the plugins store.
621
+ * @returns {string[]} ids of the skipped plugins
622
+ */
623
+ export function dropOldSdkPlugins() {
624
+ const skipped = [];
625
+
626
+ for (const [pluginId, plugin] of Object.entries(get(plugins))) {
627
+ if (!plugin?.module || plugin.module.panoSdk === 2) continue;
628
+
629
+ console.error(
630
+ `[Plugin Manager] ${pluginId} was built for @panomc/sdk 1.x and does not load on this Pano; rebuild it with @panomc/plugin-kit`,
631
+ );
632
+ skipped.push(pluginId);
633
+ }
634
+
635
+ if (skipped.length) {
636
+ plugins.update((p) => {
637
+ for (const pluginId of skipped) delete p[pluginId];
638
+ return p;
639
+ });
640
+ }
641
+
642
+ return skipped;
643
+ }
644
+
645
+ async function loadPlugins(siteInfo) {
646
+ // Phase 1: Import all plugin modules in parallel for faster loading
647
+ const pluginIds = Object.keys(get(plugins));
648
+
649
+ await Promise.all(
650
+ pluginIds.map(async (pluginId) => {
651
+ const plugin = get(plugins)[pluginId];
652
+ if (!plugin) return;
653
+
654
+ if (browser) {
655
+ // The `?v=<uiHash>` segment is what gives this URL meaning as a content identifier:
656
+ // the browser module cache is keyed by URL, so distinct hashes get distinct cache
657
+ // entries. Without this, a plugin update mutates server-side files but the browser
658
+ // keeps using the old module from its cache for the rest of the session.
659
+ const uiHashSuffix = plugin.uiHash ? `?v=${plugin.uiHash}` : '';
660
+ const reloadKey = `pano:plugin-reload:${pluginId}:${plugin.uiHash || 'no-hash'}`;
661
+ const moduleUrl = `${base}/plugins/${pluginId}/resources/plugin-ui/client/client.mjs${uiHashSuffix}`;
662
+ // Permanent, deterministic failures where re-fetching the exact same bytes fails
663
+ // identically forever — reloading is useless and punishes every fresh tab:
664
+ // - SyntaxError / "does not provide an export named …" / "is not a module":
665
+ // the plugin was built against a different svelte/SDK (ABI/version skew).
666
+ // - "Failed to resolve module specifier" (Chrome) / "was a bare specifier" (Firefox)
667
+ // / "does not resolve to a valid URL" (Safari): the plugin imports a bare
668
+ // specifier absent from the host import map — resolution never touches the
669
+ // network, so retry and reload cannot change the outcome.
670
+ // - "[pano-runtime] …": the host runtime registry rejected the specifier.
671
+ const isVersionSkewError = (err) =>
672
+ err instanceof SyntaxError ||
673
+ /does not provide an export named|is not a module|Unexpected (token|reserved word|end of input)|Failed to resolve module specifier|bare specifier|does not resolve to a valid URL|pano-runtime/i.test(
674
+ String(err?.message ?? err),
675
+ );
676
+ try {
677
+ try {
678
+ plugin.module = await import(/* @vite-ignore */ moduleUrl);
679
+ } catch (firstError) {
680
+ if (isVersionSkewError(firstError)) throw firstError;
681
+ // A failed module fetch is cached in the document's module map (per HTML
682
+ // spec) — re-importing the SAME URL returns the cached failure without a
683
+ // network attempt. A changed query string is a new module-map key AND a
684
+ // new HTTP-cache key, so transient 404s (mid-update swap window, proxy
685
+ // hiccup) recover here without the full reload below.
686
+ const retryUrl = `${moduleUrl}${uiHashSuffix ? '&' : '?'}r=${Date.now().toString(36)}`;
687
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load, retrying with cache-bust…`, firstError);
688
+ plugin.module = await import(/* @vite-ignore */ retryUrl);
689
+ }
690
+ sessionStorage.removeItem(reloadKey);
691
+ } catch (e) {
692
+ // Classify the failure before deciding whether to reload. A reload only helps the
693
+ // genuinely *transient* cases — the plugin was updated and a chunk is mid-rename, or
694
+ // the file briefly 404s during the two-rename swap — where a fresh fetch resolves it.
695
+ //
696
+ // Version skew (see isVersionSkewError above): reloading punishes every fresh tab
697
+ // with a forced refresh loop, so we skip the plugin immediately with a warn and NO
698
+ // reload.
699
+ if (isVersionSkewError(e)) {
700
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load and looks like a version mismatch (the plugin may be built for an incompatible svelte/SDK version); skipping without reload.`, e);
701
+ sessionStorage.removeItem(reloadKey);
702
+ plugins.update((p) => {
703
+ delete p[pluginId];
704
+ return p;
705
+ });
706
+ return;
707
+ }
708
+
709
+ // Transient case (chunk-missing / mid-rename): reload once to resync — but only once
710
+ // per uiHash, since a permanent 404 would otherwise cause an infinite F5 loop.
711
+ const alreadyReloaded = sessionStorage.getItem(reloadKey) === '1';
712
+ if (!alreadyReloaded) {
713
+ sessionStorage.setItem(reloadKey, '1');
714
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load, reloading once…`, e);
715
+ location.reload();
716
+ throw e;
717
+ }
718
+ // Second failure for the same uiHash: stop the loop. Drop the plugin from the store
719
+ // so the UI can render the rest of the page without it.
720
+ console.error(`[Plugin Manager] '${pluginId}' client module is permanently broken (uiHash=${plugin.uiHash}); skipping. The on-disk plugin files are likely corrupt — clear the panel-ui 'plugins/${pluginId}' folder on the server.`, e);
721
+ plugins.update((p) => {
722
+ delete p[pluginId];
723
+ return p;
724
+ });
725
+ }
726
+ } else {
727
+ const pluginFolder = path.join(pluginsFolder, pluginId);
728
+ applyPluginPackage(pluginId, plugin, pluginFolder);
729
+ const pluginManifest = plugin;
730
+ const pluginHash = pluginManifest.uiHash || "no-hash";
731
+ const cacheKey = `${pluginId}-${pluginHash}`;
732
+
733
+ if (moduleCache.has(cacheKey) && !siteInfo.developmentMode) {
734
+ plugin.module = moduleCache.get(cacheKey);
735
+ return;
736
+ }
737
+
738
+ // Cache-buster for Node's ESM module cache (keyed by resolved URL). In dev we use a
739
+ // timestamp so every SSR pass re-imports the freshly rebuilt module. In production we
740
+ // mirror the client branch and key on the plugin's uiHash: without this the ESM cache
741
+ // returns the STALE server module after a plugin update, producing an SSR/client
742
+ // hydration mismatch (client uses the new hashed module, server keeps the old one).
743
+ const importSuffix = siteInfo.developmentMode
744
+ ? `?${Date.now()}`
745
+ : (pluginHash !== "no-hash" ? `?v=${pluginHash}` : "");
746
+ const mainPath = path.join(pluginFolder, "server", "server.mjs") + importSuffix;
747
+
748
+ const __filename = url.fileURLToPath(import.meta.url);
749
+
750
+ const currentDir = path.dirname(__filename); // Directory of the current file
751
+ const targetFile = path.resolve(currentDir, process.cwd()); // Absolute path of the target file
752
+
753
+ const relativePath = path.relative(currentDir, targetFile);
754
+ const levels = relativePath.split(path.sep).length;
755
+
756
+ const upDirs = `..${path.sep}`.repeat(levels); // Repeating '../' based on the number of levels
757
+
758
+ let module;
759
+
760
+ try {
761
+ module = await import(/* @vite-ignore */ upDirs + mainPath);
762
+ } catch {
763
+ try {
764
+ module = await import(
765
+ /* @vite-ignore */ "file://" +
766
+ path.join(path.resolve(upDirs + mainPath, process.cwd(), mainPath))
767
+ );
768
+ } catch (e) {
769
+ error(`${pluginId} could not run! Error:`);
770
+ error(e);
771
+
772
+ plugins.update((p) => {
773
+ delete p[pluginId];
774
+ return p;
775
+ });
776
+
777
+ return;
778
+ }
779
+ }
780
+
781
+ plugin.module = module;
782
+ if (!siteInfo.developmentMode) {
783
+ // Evict this plugin's previous (different-uiHash) entries before caching the new one,
784
+ // so moduleCache stays bounded — without this it grew one stale entry per plugin
785
+ // update for the lifetime of the process, and old modules were never released.
786
+ const prefix = `${pluginId}-`;
787
+ for (const key of moduleCache.keys()) {
788
+ if (key !== cacheKey && key.startsWith(prefix)) {
789
+ moduleCache.delete(key);
790
+ }
791
+ }
792
+ moduleCache.set(cacheKey, module);
793
+ }
794
+ }
795
+ })
796
+ );
797
+
798
+ dropOldSdkPlugins();
799
+
800
+ // Phase 2: Initialize plugins with dependency-aware batching (topological sort)
801
+ // Plugins at the same dependency level run in parallel; levels execute sequentially
802
+ const pluginDepGraph = buildPluginDependencyGraph(get(plugins));
803
+ const loadLevels = topologicalSortPlugins(pluginDepGraph);
804
+
805
+ for (const level of loadLevels) {
806
+ await Promise.all(
807
+ level.map(async (pluginId) => {
808
+ const plugin = get(plugins)[pluginId];
809
+ if (!plugin?.module?.default) return;
810
+
811
+ const PluginClass = plugin.module.default;
812
+
813
+ // Validate BEFORE instantiating. `PluginClass` is a constructor, so the old
814
+ // `PluginClass instanceof PanoPlugin` was always false and never rejected anything.
815
+ // A strict `prototype instanceof PanoPlugin` is wrong across bundles too: released
816
+ // plugins bundle their OWN copy of the SDK, so their PanoPlugin base class is a
817
+ // different identity than the host's. Accept the cross-bundle duck-type marker
818
+ // (`static isPanoPlugin`, inherited by subclasses), and skip the offending plugin
819
+ // instead of throwing — one bad plugin must not kill the whole load level.
820
+ const isValidPluginClass =
821
+ typeof PluginClass === "function" &&
822
+ (PluginClass === PanoPlugin ||
823
+ PluginClass.prototype instanceof PanoPlugin ||
824
+ PluginClass.isPanoPlugin === true);
825
+
826
+ if (!isValidPluginClass) {
827
+ error(`Plugin '${pluginId}' does not extend PanoPlugin; skipping.`);
828
+ plugins.update((p) => {
829
+ delete p[pluginId];
830
+ return p;
831
+ });
832
+ return;
833
+ }
834
+
835
+ const instance = new PluginClass({ pluginId });
836
+
837
+ instance.pano = browser ? panoApiClient : panoApiServer;
838
+
839
+ if (browser) {
840
+ livePluginInstances.set(pluginId, instance);
841
+ }
842
+
843
+ try {
844
+ await instance.onLoad();
845
+ } catch (e) {
846
+ if (dev) console.error(`[PluginManager] Failed to load plugin ${pluginId}:`, e);
847
+ }
848
+ })
849
+ );
850
+ }
851
+ }