@panomc/sdk 1.0.0-dev.6 → 1.0.0-dev.60

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 (85) hide show
  1. package/README.md +3 -3
  2. package/core/favicon/apple-touch-icon.png +0 -0
  3. package/core/favicon/favicon-96x96.png +0 -0
  4. package/core/favicon/favicon.ico +0 -0
  5. package/core/favicon/favicon.svg +1 -0
  6. package/core/favicon/site.webmanifest +21 -0
  7. package/core/favicon/web-app-manifest-192x192.png +0 -0
  8. package/core/favicon/web-app-manifest-512x512.png +0 -0
  9. package/core/favicon_old/android-icon-144x144.png +0 -0
  10. package/core/favicon_old/android-icon-192x192.png +0 -0
  11. package/core/favicon_old/android-icon-36x36.png +0 -0
  12. package/core/favicon_old/android-icon-48x48.png +0 -0
  13. package/core/favicon_old/android-icon-72x72.png +0 -0
  14. package/core/favicon_old/android-icon-96x96.png +0 -0
  15. package/core/favicon_old/apple-icon-114x114.png +0 -0
  16. package/core/favicon_old/apple-icon-120x120.png +0 -0
  17. package/core/favicon_old/apple-icon-144x144.png +0 -0
  18. package/core/favicon_old/apple-icon-152x152.png +0 -0
  19. package/core/favicon_old/apple-icon-180x180.png +0 -0
  20. package/core/favicon_old/apple-icon-57x57.png +0 -0
  21. package/core/favicon_old/apple-icon-60x60.png +0 -0
  22. package/core/favicon_old/apple-icon-72x72.png +0 -0
  23. package/core/favicon_old/apple-icon-76x76.png +0 -0
  24. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  25. package/core/favicon_old/apple-icon.png +0 -0
  26. package/core/favicon_old/browserconfig.xml +11 -0
  27. package/core/favicon_old/favicon-16x16.png +0 -0
  28. package/core/favicon_old/favicon-32x32.png +0 -0
  29. package/core/favicon_old/favicon-96x96.png +0 -0
  30. package/core/favicon_old/favicon.ico +0 -0
  31. package/core/favicon_old/manifest.json +41 -0
  32. package/core/favicon_old/ms-icon-144x144.png +0 -0
  33. package/core/favicon_old/ms-icon-150x150.png +0 -0
  34. package/core/favicon_old/ms-icon-310x310.png +0 -0
  35. package/core/favicon_old/ms-icon-70x70.png +0 -0
  36. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  37. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  38. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  39. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  40. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  41. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  42. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  43. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  44. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  45. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  46. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  47. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  48. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  49. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  50. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  51. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  52. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  53. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  54. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  55. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  56. package/core/js/NotificationManager.js +19 -0
  57. package/core/js/PluginAPI.js +29 -0
  58. package/core/js/PluginManager.js +789 -0
  59. package/core/js/RouteMatcher.js +134 -0
  60. package/core/js/api.util.js +270 -0
  61. package/core/js/tooltip.util.js +59 -0
  62. package/core/js/variables.js +75 -0
  63. package/core/js/version.util.js +100 -0
  64. package/core/scss/custom-bootstrap.scss +187 -0
  65. package/core/scss/fonts.scss +85 -0
  66. package/core/scss/main.scss +385 -0
  67. package/core/scss/themes.scss +97 -0
  68. package/package.json +30 -10
  69. package/src/api/plugin-context.js +3 -3
  70. package/src/api/plugin.js +6 -6
  71. package/src/components/{index.js → panel.js} +12 -8
  72. package/src/components/theme.js +13 -0
  73. package/src/index.js +3 -3
  74. package/src/internal/index.js +1 -1
  75. package/src/internal/pano-context.js +4 -4
  76. package/src/svelte.js +4 -3
  77. package/src/toasts/index.js +2 -2
  78. package/src/types.js +1 -1
  79. package/src/utils/api.js +2 -2
  80. package/src/utils/auth.js +8 -0
  81. package/src/utils/component.js +11 -9
  82. package/src/utils/language.js +2 -2
  83. package/src/utils/text.js +8 -0
  84. package/src/utils/tooltip.js +1 -1
  85. package/src/variables.js +1 -1
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Simple route matcher that supports literals, dynamic segments [param],
3
+ * catch-all segments [...param], and basic regex patterns.
4
+ */
5
+ export class RouteMatcher {
6
+ /**
7
+ * Matches a path against a pattern.
8
+ * @param {string} pattern - The route pattern (e.g., '/announcements/[id]')
9
+ * @param {string} path - The actual path (e.g., '/announcements/123')
10
+ * @returns {object|null} - Params object if matched, null otherwise
11
+ */
12
+ static match(pattern, path) {
13
+ // Normalize path: remove query params and trailing slash
14
+ const [pathOnly] = path.split('?');
15
+ const normalizedPath = pathOnly === '/' ? '/' : pathOnly.replace(/\/$/, '');
16
+ const normalizedPattern = pattern === '/' ? '/' : pattern.replace(/\/$/, '');
17
+
18
+ // 1. Literal match
19
+ if (normalizedPattern === normalizedPath) {
20
+ return {};
21
+ }
22
+
23
+ // 2. Regex match
24
+ // Regex must be explicitly opted in with a `re:` prefix — we must NOT infer "this is a
25
+ // regex" from a leading/trailing slash, since a normal plugin path with a trailing slash
26
+ // (e.g. `/news/`) would otherwise be reinterpreted as an UNANCHORED regex and silently
27
+ // hijack unrelated routes. The body is anchored as `^(?:...)$` so it can't partial-match.
28
+ if (pattern.startsWith('re:')) {
29
+ try {
30
+ const regex = new RegExp(`^(?:${pattern.slice(3)})$`);
31
+ const match = normalizedPath.match(regex);
32
+ if (match) {
33
+ return match.groups || {};
34
+ }
35
+ } catch (e) {
36
+ console.error('Invalid regex pattern:', pattern, e);
37
+ }
38
+ }
39
+
40
+ // 3. Segment-based match (SvelteKit style)
41
+ const patternSegments = normalizedPattern.split('/').filter(Boolean);
42
+ const pathSegments = normalizedPath.split('/').filter(Boolean);
43
+
44
+ const params = {};
45
+
46
+ // Check for catch-all [...param]
47
+ const catchAllIndex = patternSegments.findIndex((s) => s.startsWith('[...') && s.endsWith(']'));
48
+
49
+ if (catchAllIndex !== -1) {
50
+ // SvelteKit only allows a rest param as the FINAL segment. A catch-all that isn't last
51
+ // would greedily absorb every trailing segment and ignore the pattern's suffix, so a
52
+ // pattern like `/[...rest]/edit` would wrongly match `/a/b/c`. Reject it outright.
53
+ if (catchAllIndex !== patternSegments.length - 1) return null;
54
+
55
+ // Logic for catch-all
56
+ if (pathSegments.length < catchAllIndex) return null;
57
+
58
+ for (let i = 0; i < catchAllIndex; i++) {
59
+ if (!this.segmentsMatch(patternSegments[i], pathSegments[i], params)) {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ const paramName = patternSegments[catchAllIndex].slice(4, -1);
65
+ params[paramName] = pathSegments.slice(catchAllIndex).join('/');
66
+ return params;
67
+ }
68
+
69
+ // Normal segment match
70
+ if (patternSegments.length !== pathSegments.length) {
71
+ return null;
72
+ }
73
+
74
+ for (let i = 0; i < patternSegments.length; i++) {
75
+ if (!this.segmentsMatch(patternSegments[i], pathSegments[i], params)) {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ return params;
81
+ }
82
+
83
+ static segmentsMatch(patternSegment, pathSegment, params) {
84
+ if (patternSegment.startsWith('[') && patternSegment.endsWith(']')) {
85
+ const paramName = patternSegment.slice(1, -1);
86
+ params[paramName] = pathSegment;
87
+ return true;
88
+ }
89
+ if (patternSegment.startsWith(':')) {
90
+ const paramName = patternSegment.slice(1);
91
+ params[paramName] = pathSegment;
92
+ return true;
93
+ }
94
+ return patternSegment === pathSegment;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Canonical form of a route key/path used for the exact-match fast path: query stripped and a
100
+ * single trailing slash removed (but `/` preserved). Used at BOTH registration and lookup so
101
+ * `/foo` and `/foo/` collapse to one entry and the exact-match map lookup always hits instead
102
+ * of falling through to the slower (and buggier) regex/segment branch.
103
+ * @param {string} path
104
+ * @returns {string}
105
+ */
106
+ export function canonicalizeRouteKey(path) {
107
+ const [pathOnly] = String(path).split('?');
108
+ return pathOnly === '/' ? '/' : pathOnly.replace(/\/$/, '');
109
+ }
110
+
111
+ /**
112
+ * Finds a registered page matching the given path.
113
+ * @param {Object} registeredPages - Map of patterns to page objects
114
+ * @param {string} path - The path to match
115
+ * @returns {Object|null} - The matching page object with params, or null
116
+ */
117
+ export function findMatch(registeredPages, path) {
118
+ // First, try exact match for performance
119
+ const normalizedPath = canonicalizeRouteKey(path);
120
+
121
+ if (registeredPages[normalizedPath]) {
122
+ return { ...registeredPages[normalizedPath], params: {} };
123
+ }
124
+
125
+ // Then, try more complex matches
126
+ for (const pattern in registeredPages) {
127
+ const params = RouteMatcher.match(pattern, path);
128
+ if (params) {
129
+ return { ...registeredPages[pattern], params };
130
+ }
131
+ }
132
+
133
+ return null;
134
+ }
@@ -0,0 +1,270 @@
1
+ import { API_URL, CSRF_HEADER } from "$lib/variables.js";
2
+ import { get } from "svelte/store";
3
+ import { page } from "$app/stores";
4
+ import { browser } from "$app/environment";
5
+ import { initialized } from "$lib/Store.js";
6
+ import { show } from "$lib/components/ToastContainer.svelte";
7
+
8
+ // Constants for network error handling
9
+ export const NETWORK_ERROR = 'NETWORK_ERROR';
10
+ export const networkErrorBody = { result: 'error', error: NETWORK_ERROR };
11
+
12
+ const NETWORK_RETRY_DELAY_MS = 400;
13
+
14
+ function isIdempotent(method) {
15
+ return !method || ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase());
16
+ }
17
+
18
+ // Function to build query parameters from an object
19
+ export function buildQueryParams(params) {
20
+ const queryString = Object.keys(params)
21
+ .filter((key) => params[key])
22
+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
23
+ .join('&');
24
+ return queryString === '' ? '' : '?' + queryString;
25
+ }
26
+
27
+ const ApiUtil = {
28
+ interceptors: {},
29
+
30
+ // GET request
31
+ async get({ path, request, csrfToken, token, blob, handler }) {
32
+ return this.customRequest({
33
+ path,
34
+ request,
35
+ csrfToken,
36
+ token,
37
+ blob,
38
+ handler,
39
+ });
40
+ },
41
+
42
+ // POST request
43
+ async post({ path, request, body, headers, csrfToken, token, blob, handler, onUploadProgress }) {
44
+ return this.customRequest({
45
+ path,
46
+ data: { method: 'POST', credentials: 'include', body, headers },
47
+ request,
48
+ csrfToken,
49
+ token,
50
+ blob,
51
+ handler,
52
+ onUploadProgress,
53
+ });
54
+ },
55
+
56
+ // PUT request
57
+ async put({ path, request, body, headers, csrfToken, token, blob, handler, onUploadProgress }) {
58
+ return this.customRequest({
59
+ path,
60
+ data: { method: 'PUT', credentials: 'include', body, headers },
61
+ request,
62
+ csrfToken,
63
+ token,
64
+ blob,
65
+ handler,
66
+ onUploadProgress,
67
+ });
68
+ },
69
+
70
+ // DELETE request
71
+ async delete({ path, request, headers, csrfToken, token, blob, handler }) {
72
+ return this.customRequest({
73
+ path,
74
+ data: { method: 'DELETE', headers },
75
+ request,
76
+ csrfToken,
77
+ token,
78
+ blob,
79
+ handler,
80
+ });
81
+ },
82
+
83
+ // Custom request handler
84
+ async customRequest({ path, data = {}, request, csrfToken, token, blob, handler, onUploadProgress }) {
85
+ // Retrieve CSRF token if not provided
86
+ if (!csrfToken) {
87
+ let session;
88
+ if (request && typeof request.parent === "function") {
89
+ const parentData = await request.parent();
90
+ session = parentData.session;
91
+ } else if (browser && get(page).data) {
92
+ session = get(page).data.session;
93
+ }
94
+ csrfToken = session && session.csrfToken;
95
+ }
96
+
97
+ // Set CSRF header if token is available
98
+ const CSRFHeader = csrfToken ? { [CSRF_HEADER]: csrfToken } : {};
99
+
100
+ // Convert body to JSON string if not FormData
101
+ if (!(data.body instanceof FormData)) {
102
+ data.body = JSON.stringify(data.body);
103
+ data.headers = { 'Content-Type': 'application/json', ...data.headers };
104
+ }
105
+
106
+ // Set request options
107
+ const options = {
108
+ ...data,
109
+ headers: { ...data.headers, ...CSRFHeader },
110
+ };
111
+
112
+ // Add Authorization header if token is provided
113
+ if (token) {
114
+ options.headers['Authorization'] = `Bearer ${token}`;
115
+ } else if ('credentials' in Request.prototype) {
116
+ options['credentials'] = 'include';
117
+ }
118
+
119
+ // When the app runs behind the Pano backend's reverse proxy, SvelteKit load
120
+ // functions must use relative paths so SSR and CSR fetch URLs match.
121
+ // SvelteKit deduplicates event.fetch calls by URL — if SSR uses an absolute URL
122
+ // (e.g. http://0.0.0.0:8088/api/...) but CSR uses relative (/api/...), the client
123
+ // will re-fetch instead of using the serialized SSR response.
124
+ //
125
+ // For the Pano website (api.panomc.com on Cloudflare Pages), both SSR and CSR
126
+ // already use the same absolute URL, so dedup works naturally — no change needed.
127
+ const hasEventFetch = request && request.fetch;
128
+ const isReverseProxied = !API_URL.includes(".panomc.com");
129
+
130
+ if (hasEventFetch && isReverseProxied) {
131
+ // Reverse proxy scenario: use relative path for consistent SSR↔CSR dedup.
132
+ // handleFetch in hooks.server.js will rewrite this to the backend URL during SSR.
133
+ if (!path.startsWith("/api/")) {
134
+ path = `/api/${path.replace("/api/", "")}`;
135
+ }
136
+ } else if ((request && !get(initialized)) || !browser || API_URL.includes(".panomc.com")) {
137
+ let apiUrl = API_URL;
138
+
139
+ if (
140
+ !API_URL.includes(".panomc.com") &&
141
+ import.meta.env.PROD &&
142
+ browser &&
143
+ get(initialized)
144
+ ) {
145
+ apiUrl = "/api"
146
+ }
147
+
148
+ if (browser && (API_URL.includes("0.0.0.0") || API_URL.includes("127.0.0.1") || API_URL.includes("localhost"))) {
149
+ apiUrl = "/api"
150
+ }
151
+
152
+ path = `${apiUrl}/${path.replace('/api/', '')}`;
153
+ }
154
+
155
+ const bodyHandler = (response) => (blob ? response.blob() : response.text());
156
+ const jsonParseHandler = (json) => {
157
+ try {
158
+ return JSON.parse(json);
159
+ } catch (err) {
160
+ return json;
161
+ }
162
+ };
163
+
164
+ const requestCall = (rejectHandler) => {
165
+ const reject = async (err) => {
166
+ console.log(err);
167
+ if (rejectHandler) {
168
+ throw new Error(err);
169
+ }
170
+
171
+ if (!this.interceptors.errorHandler || !handler) {
172
+ return;
173
+ }
174
+
175
+ this.interceptors.errorHandler(requestCall);
176
+ };
177
+
178
+ if (onUploadProgress && browser && data.body instanceof FormData) {
179
+ return new Promise((resolve, rejectFn) => {
180
+ const xhr = new XMLHttpRequest();
181
+ xhr.open(data.method, path);
182
+
183
+ if (options.credentials === 'include') {
184
+ xhr.withCredentials = true;
185
+ }
186
+
187
+ const headersToSet = { ...options.headers };
188
+ delete headersToSet['Content-Type'];
189
+
190
+ Object.keys(headersToSet).forEach((key) => {
191
+ xhr.setRequestHeader(key, headersToSet[key]);
192
+ });
193
+
194
+ xhr.upload.onprogress = (event) => {
195
+ if (event.lengthComputable) {
196
+ onUploadProgress(event.loaded / event.total);
197
+ }
198
+ };
199
+
200
+ xhr.onload = async () => {
201
+ try {
202
+ let parsedJson;
203
+ try {
204
+ parsedJson = JSON.parse(xhr.responseText);
205
+ } catch (err) {
206
+ parsedJson = xhr.responseText;
207
+ }
208
+
209
+ if (parsedJson?.error === 'DISABLED_FOR_DEMO') {
210
+ if (browser) {
211
+ await show("components.toasts.demo-mode-restricted");
212
+ }
213
+ resolve();
214
+ return;
215
+ }
216
+
217
+ const finalData = handler ? await handler(parsedJson, rejectFn) : parsedJson;
218
+ resolve(finalData);
219
+ } catch (err) {
220
+ rejectFn(err);
221
+ }
222
+ };
223
+
224
+ xhr.onerror = () => rejectFn('NETWORK_ERROR');
225
+
226
+ xhr.send(data.body);
227
+ }).catch(reject);
228
+ }
229
+
230
+ // Perform fetch request
231
+ const doFetch = () =>
232
+ request && request.fetch ? request.fetch(path, options) : fetch(path, options);
233
+
234
+ // A request that never got a response (fetch rejected) is retried ONCE before the
235
+ // offline splash: browsers reuse a pooled HTTP/3 connection that the peer may have
236
+ // just idled out (Firefox: 30 s), and the request on it fails instantly although the
237
+ // server is fine. A new connection succeeds. Only idempotent methods, so a POST/PUT
238
+ // is never sent twice; HTTP error responses are not retried (fetch resolves them).
239
+ const fetchMethod =
240
+ browser && isIdempotent(data.method)
241
+ ? doFetch().catch((err) => {
242
+ if (err?.name === 'AbortError') throw err;
243
+
244
+ return new Promise((resolve) => setTimeout(resolve, NETWORK_RETRY_DELAY_MS)).then(
245
+ doFetch,
246
+ );
247
+ })
248
+ : doFetch();
249
+
250
+ // Handle response
251
+ return fetchMethod
252
+ .then(bodyHandler)
253
+ .then(jsonParseHandler)
254
+ .then(async (parsedJson) => {
255
+ if (parsedJson?.error === 'DISABLED_FOR_DEMO') {
256
+ if (browser) {
257
+ await show("components.toasts.demo-mode-restricted");
258
+ }
259
+ return;
260
+ }
261
+ return handler ? await handler(parsedJson, reject) : parsedJson;
262
+ })
263
+ .catch(reject);
264
+ };
265
+
266
+ return requestCall();
267
+ },
268
+ };
269
+
270
+ export default ApiUtil;
@@ -0,0 +1,59 @@
1
+ import tippy from 'tippy.js';
2
+ import 'tippy.js/dist/tippy.css';
3
+ import { page } from '$app/stores';
4
+
5
+ function setTooltip(element, [value, options]) {
6
+ const instance = typeof element._tippy === 'undefined' ? tippy(element) : element._tippy;
7
+
8
+ instance.setContent(value);
9
+ instance.setProps(options);
10
+ }
11
+
12
+ export default function tooltip(element, properties) {
13
+ let unsubscribePage;
14
+ let instance;
15
+
16
+ const init = (props) => {
17
+ if (!props) return;
18
+
19
+ let [value, options] = props;
20
+ if (!value) {
21
+ if (instance) instance.destroy();
22
+ instance = null;
23
+ return;
24
+ }
25
+
26
+ if (!instance) {
27
+ instance = tippy(element);
28
+ }
29
+
30
+ const mergedOptions = {
31
+ content: value,
32
+ placement: 'bottom',
33
+ interactive: true,
34
+ animation: 'fade',
35
+ ...options
36
+ };
37
+
38
+ instance.setProps(mergedOptions);
39
+
40
+ if (!unsubscribePage) {
41
+ unsubscribePage = page.subscribe(() => {
42
+ if (instance) instance.hide();
43
+ });
44
+ }
45
+ };
46
+
47
+ init(properties);
48
+
49
+ return {
50
+ update(updatedProperties) {
51
+ init(updatedProperties);
52
+ },
53
+
54
+ destroy() {
55
+ if (instance) instance.destroy();
56
+ if (unsubscribePage) unsubscribePage();
57
+ },
58
+ };
59
+ }
@@ -0,0 +1,75 @@
1
+ export let API_URL = import.meta.env.VITE_API_URL;
2
+ export const UI_URL = import.meta.env.VITE_UI_URL ?? '/';
3
+ export const PANEL_URL = import.meta.env.VITE_PANEL_URL ?? '/panel';
4
+ export const SETUP_URL = import.meta.env.VITE_SETUP_URL ?? '/';
5
+ export let PANO_WEBSITE_URL = import.meta.env.VITE_PANO_WEBSITE_URL;
6
+ export let PANO_WEBSITE_API_URL = import.meta.env.VITE_PANO_WEBSITE_API_URL;
7
+ export const PRERELEASE = import.meta.env.VITE_PRERELEASE;
8
+
9
+ // Default matches the Pano backend's cookie prefix — a theme without an explicit
10
+ // VITE_COOKIE_PREFIX would otherwise look up 'undefinedauth_token' and treat every
11
+ // logged-in visitor as anonymous on SSR navigations.
12
+ export const COOKIE_PREFIX = import.meta.env.VITE_COOKIE_PREFIX ?? 'pano_';
13
+
14
+ export const CSRF_TOKEN_COOKIE_NAME = 'csrf_token';
15
+ export const JWT_COOKIE_NAME = 'auth_token';
16
+
17
+ export const CSRF_HEADER = 'X-CSRF-Token';
18
+
19
+ export function checkDomainRedirection() {
20
+ if (typeof window === 'undefined' || !API_URL || API_URL.startsWith('/')) return;
21
+
22
+ // In production API_URL is the Pano host's internal backend address (loopback or
23
+ // server.host:internal-port) — never a browser-reachable origin, so redirecting on it
24
+ // would bounce reverse-proxied visitors to the internal port. Canonical-host redirects
25
+ // are owned by the backend (WebsiteUrlRedirectHandler); this helper only smooths the
26
+ // dev workflow: hitting a vite dev port directly bounces you into the Pano dev server.
27
+ if (!import.meta.env.DEV) return;
28
+
29
+ try {
30
+ const apiUrl = new URL(API_URL);
31
+ const currentUrl = new URL(window.location.href);
32
+
33
+ // Only bounce when the page was opened on the vite port of the SAME machine
34
+ // (localhost:3000 -> localhost:8088). Reaching the Pano dev server through another
35
+ // hostname — a LAN address, ngrok, cloudflared — is legitimate: Pano already proxies vite
36
+ // for that visitor, and API_URL's host means nothing on their machine.
37
+ if (!isSameDevHost(currentUrl.hostname, apiUrl.hostname)) return;
38
+
39
+ if (currentUrl.port !== apiUrl.port || currentUrl.protocol !== apiUrl.protocol) {
40
+ const basePath = UI_URL || PANEL_URL || SETUP_URL || '/';
41
+ let pathname = currentUrl.pathname;
42
+
43
+ if (basePath !== '/' && !pathname.startsWith(basePath)) {
44
+ pathname = basePath + (pathname === '/' ? '' : pathname);
45
+ }
46
+
47
+ const targetUrl = new URL(pathname + currentUrl.search + currentUrl.hash, apiUrl.origin);
48
+ window.location.href = targetUrl.toString();
49
+ }
50
+ } catch (e) {
51
+ console.error('Failed to check domain redirection:', e);
52
+ }
53
+ }
54
+
55
+ function isLoopbackHost(hostname) {
56
+ const h = hostname.toLowerCase();
57
+ return h === 'localhost' || h.endsWith('.localhost') || h === '[::1]' || h.startsWith('127.');
58
+ }
59
+
60
+ function isSameDevHost(a, b) {
61
+ const norm = (h) => (isLoopbackHost(h) ? 'localhost' : h.toLowerCase());
62
+ return norm(a) === norm(b);
63
+ }
64
+
65
+ export function updateApiUrl(apiUrl) {
66
+ API_URL = apiUrl;
67
+ }
68
+
69
+ export function updatePanoWebsiteUrl(panoWebsiteUrl) {
70
+ PANO_WEBSITE_URL = panoWebsiteUrl;
71
+ }
72
+
73
+ export function updatePanoWebsiteApiUrl(panoWebsiteApiUrl) {
74
+ PANO_WEBSITE_API_URL = panoWebsiteApiUrl;
75
+ }
@@ -0,0 +1,100 @@
1
+ /** Matches Kotlin `VersionUtil.isSemVer` (optional leading v tag). */
2
+ function isSemVer(version) {
3
+ return /^v?\d+\.\d+\.\d+(-[\w.]+)?$/.test(version);
4
+ }
5
+
6
+ /** Kotlin `parseVersion(removePrefix(version, "v"))` with hyphen split limited to core + prerelease remainder. */
7
+ function parseVersion(version) {
8
+ const cleanVersion = version.replace(/^v/, '');
9
+ const hyphen = cleanVersion.indexOf('-');
10
+ const corePart = hyphen === -1 ? cleanVersion : cleanVersion.slice(0, hyphen);
11
+ const preRaw = hyphen === -1 ? '' : cleanVersion.slice(hyphen + 1);
12
+ const coreParts = corePart.split('.').map((p) => Number(p));
13
+ const preParts = preRaw
14
+ ? preRaw.split('.').map((part) => {
15
+ const parsed = /^-?\d+$/.test(part) ? Number(part) : NaN;
16
+ return Number.isNaN(parsed) ? part : parsed;
17
+ })
18
+ : [];
19
+ return { coreParts, preParts };
20
+ }
21
+
22
+ /** Kotlin `compareVersions`; does not coerce non-tags (opaque tags compare only via `===`). */
23
+ export function compareVersions(a, b) {
24
+ const isASemVer = isSemVer(a);
25
+ const isBSemVer = isSemVer(b);
26
+
27
+ if (!isASemVer && !isBSemVer) return 0;
28
+ if (!isASemVer) return -1;
29
+ if (!isBSemVer) return 1;
30
+
31
+ const va = parseVersion(a);
32
+ const vb = parseVersion(b);
33
+
34
+ const len = Math.max(va.coreParts.length, vb.coreParts.length);
35
+ for (let i = 0; i < len; i++) {
36
+ const ai = va.coreParts[i] || 0;
37
+ const bi = vb.coreParts[i] || 0;
38
+ if (ai !== bi) return ai - bi;
39
+ }
40
+
41
+ const prePriority = ['alpha', 'beta'];
42
+
43
+ const isAPre = va.preParts.length > 0;
44
+ const isBPre = vb.preParts.length > 0;
45
+
46
+ if (!isAPre && isBPre) return 1;
47
+ if (isAPre && !isBPre) return -1;
48
+
49
+ for (let i = 0; i < Math.max(va.preParts.length, vb.preParts.length); i++) {
50
+ const ap = va.preParts[i];
51
+ const bp = vb.preParts[i];
52
+ if (ap === bp) continue;
53
+
54
+ if (typeof ap === 'string' && typeof bp === 'string') {
55
+ const ai = prePriority.indexOf(ap);
56
+ const bi = prePriority.indexOf(bp);
57
+ return (ai === -1 ? 99 : ai) - (bi === -1 ? 99 : bi);
58
+ }
59
+ if (typeof ap === 'number' && typeof bp === 'number') return ap - bp;
60
+ return typeof ap === 'string' ? -1 : 1;
61
+ }
62
+
63
+ return 0;
64
+ }
65
+
66
+ /** Kotlin `isVersionHigher` — installed `local-build` is treated below any normal semver release. */
67
+ export function isStoreVersionHigher(latestPublishedTag, installedTag) {
68
+ const normalizedInstalled =
69
+ installedTag === 'local-build' ? 'v1.0.0-alpha.0' : installedTag;
70
+ return compareVersions(latestPublishedTag, normalizedInstalled) > 0;
71
+ }
72
+
73
+ /**
74
+ * Same release according to Kotlin store rules (exact tag strings or semver-equal, including optional `v`).
75
+ */
76
+ export function areStoreVersionTagsEqual(a, b) {
77
+ if (a === b) return true;
78
+ if (a == null || b == null) return false;
79
+ if (!isSemVer(a) || !isSemVer(b)) return false;
80
+ return compareVersions(a, b) === 0;
81
+ }
82
+
83
+ export function isPanoVersionCompatible(current, required) {
84
+ if (current === 'local-build') return true;
85
+ if (!isSemVer(current) || !isSemVer(required)) return false;
86
+
87
+ const currentParsed = parseVersion(current);
88
+ const requiredParsed = parseVersion(required);
89
+
90
+ const coreEqual =
91
+ JSON.stringify(currentParsed.coreParts) === JSON.stringify(requiredParsed.coreParts);
92
+
93
+ const requiredIsPre = requiredParsed.preParts.length > 0;
94
+
95
+ if (coreEqual && !requiredIsPre) {
96
+ return true;
97
+ }
98
+
99
+ return compareVersions(current, required) >= 0;
100
+ }