@stagepass/loader 1.1.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Herz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # `@stagepass/loader`
2
+
3
+ Universal browser runtime for Stagepass.
4
+
5
+ The loader reads Stagepass session state and swaps tagged production assets with local `.sp` assets during development. It also exposes a runtime API via `sp` / `stagepass`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @stagepass/loader@2.0.0
11
+ ```
12
+
13
+ ## CDN Usage
14
+
15
+ Pin exact versions in production (jsDelivr preferred; unpkg alternative):
16
+
17
+ ```html
18
+ <script
19
+ src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2.0.0/dist/loader.min.js"
20
+ data-stagepass-version="2.0.0"
21
+ ></script>
22
+ ```
23
+
24
+ ```html
25
+ <script src="https://unpkg.com/@stagepass/loader@2.0.0/dist/loader.min.js"></script>
26
+ ```
27
+
28
+ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
29
+
30
+ ## What it does
31
+
32
+ - Processes `script[data-stagepass]:not([data-stagepass-processed])` and `link[rel="stylesheet"][data-stagepass]:not([data-stagepass-processed])`.
33
+ - Uses `data-src` (scripts) / `data-href` (stylesheets) as the production URL.
34
+ - Uses `data-stagepass-path` as an optional local path; if omitted while swapping, the filename is taken from the production URL.
35
+ - Inserts the new element before the original, then removes the original (`data-stagepass-processed` prevents double work).
36
+ - Local session: cache-bust with a single `?_cb=<timestamp>` per page load.
37
+ - Production: version bust with `data-stagepass-version` (loader tag) and/or `data-stagepass-v` (per asset) → `?v=<version>` (URL-encoded; existing query/hash preserved).
38
+ - `data-stagepass-cachebust="true"` is legacy and **does not** timestamp every production view in v2.
39
+ - Session expiry (default **12 h**): `data-stagepass-session-hours` on the loader tag.
40
+ - Optional legacy global console mute: `data-stagepass-mute-console="true"` (production, no session only).
41
+ - Dynamically created scripts use `async=false` unless the original had `async`; `defer` is added when neither async nor defer was set (keeps classic order).
42
+ - Chrome Local Network Access: best-effort permission query; badge/console hint when state is `prompt` or `denied`.
43
+
44
+ ## Loader tag attributes
45
+
46
+ | Attribute | Effect |
47
+ | :--- | :--- |
48
+ | `data-stagepass-version` | Production default `?v=<version>` for swapped/tagged assets without a per-asset override. |
49
+ | `data-stagepass-session-hours` | Session lifetime in hours (positive number; default `12`). |
50
+ | `data-stagepass-mute-console="true"` | Opt-in legacy mute of `console.log/warn/error/info/debug` in production when no session. |
51
+
52
+ ## Asset attributes
53
+
54
+ | Attribute | Effect |
55
+ | :--- | :--- |
56
+ | `data-stagepass` | Marks the element for processing (any value). |
57
+ | `data-src` / `data-href` | Production URL (required for processing). |
58
+ | `data-stagepass-path` | Local path under the linked project root (optional). |
59
+ | `data-stagepass-v` | Per-asset production `?v=<version>` (overrides loader `data-stagepass-version`). |
60
+ | `data-stagepass-cachebust` | Legacy; ignored for production timestamps in v2. |
61
+ | `data-stagepass-processed` | Internal; set after processing. |
62
+
63
+ ## URL Modes
64
+
65
+ - `?stagepass=my-project.sp`: activate local swapping (expires; default 12 h).
66
+ - `?stagepass=debug`: logging only (no asset swap).
67
+ - `?stagepass=off` / `0` / `false`: clear the session.
68
+
69
+ Allowed session values: `*.sp`, `localhost`, `localhost:<port>`, `debug`. Invalid values are rejected/cleared.
70
+
71
+ After handling, `?stagepass=` is removed with `history.replaceState` (other query params and the hash are kept).
72
+
73
+ Storage key: `localStorage.stagepass_domain` → JSON `{ "domain": "…", "expires": <ms> }`. Legacy plain-string values are cleared.
74
+
75
+ ## Badge
76
+
77
+ Shown only while a session is active (including debug). Click clears the session and reloads.
78
+
79
+ | State | Text |
80
+ | :--- | :--- |
81
+ | Active swap | `STAGEPASS ACTIVE` |
82
+ | Debug | `STAGEPASS DEBUG` |
83
+ | Active + LNA prompt/denied | `STAGEPASS · ALLOW LOCAL NETWORK` |
84
+ | Debug + LNA prompt/denied | `STAGEPASS DEBUG · LNA` |
85
+
86
+ ## Runtime API
87
+
88
+ Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`). Types ship in `global.d.ts`. There are **no** custom DOM events.
89
+
90
+ ```js
91
+ sp.vars.isLocal // boolean: session swap active or page on localhost
92
+ sp.vars.env // 'local' | 'staging' | 'production'
93
+ sp.vars.domain // active .sp domain, or page hostname when no swap
94
+ sp.vars.timestamp // session start ms while swapping; otherwise 0
95
+ sp.vars.version // package version (build-time)
96
+ sp.vars.client // theme / browser / os / device / viewport / locale / capabilities
97
+
98
+ sp.resolveLocalUrl('js/app.js') // local HTTPS URL while swapping; '' otherwise
99
+ sp.log('…') / sp.log('warn', '…') / sp.log('error', '…')
100
+ sp.warn('…')
101
+ sp.error('…')
102
+ ```
103
+
104
+ Logging helpers only print while a Stagepass session is active. Deprecated globals `splog` / `spwarn` / `sperror` were removed in v2.
105
+
106
+ ## Related Packages
107
+
108
+ - `@stagepass/cli`: creates and manages `.sp` infrastructure.
109
+ - `@stagepass/modules`: optional modules that extend the loader (`inject`, `cookies`).
110
+
111
+ ## Repository
112
+
113
+ - Full docs and examples: [stagepass repository](https://github.com/arobertherz/stagepass)
package/dist/loader.js CHANGED
@@ -1,9 +1,144 @@
1
1
  var Stagepass = (() => {
2
+ // src/domain.ts
3
+ function isValidDomain(d) {
4
+ if (typeof d !== "string" || !d) return false;
5
+ if (d === "debug" || d === "localhost") return true;
6
+ if (d.startsWith("localhost:")) {
7
+ const port = d.slice("localhost:".length);
8
+ return /^[0-9]{1,5}$/.test(port) && Number(port) <= 65535;
9
+ }
10
+ return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.sp$/i.test(
11
+ d
12
+ );
13
+ }
14
+ function cleanDomain(d) {
15
+ if (!d) return null;
16
+ return d.replace(/^https?:\/\//i, "").replace(/\/$/, "");
17
+ }
18
+
19
+ // src/session.ts
20
+ var SESSION_KEY = "stagepass_domain";
21
+ var DEFAULT_SESSION_HOURS = 12;
22
+ function parseSession(raw, now = Date.now()) {
23
+ if (!raw) return null;
24
+ if (!raw.startsWith("{")) {
25
+ return null;
26
+ }
27
+ try {
28
+ const parsed = JSON.parse(raw);
29
+ if (typeof parsed.domain !== "string" || typeof parsed.expires !== "number" || !Number.isFinite(parsed.expires)) {
30
+ return null;
31
+ }
32
+ if (!isValidDomain(parsed.domain)) return null;
33
+ if (parsed.expires <= now) return null;
34
+ return { domain: parsed.domain, expires: parsed.expires };
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ function createSession(domain, hours = DEFAULT_SESSION_HOURS, now = Date.now()) {
40
+ const safeHours = Number.isFinite(hours) && hours > 0 ? hours : DEFAULT_SESSION_HOURS;
41
+ return {
42
+ domain,
43
+ expires: now + safeHours * 60 * 60 * 1e3
44
+ };
45
+ }
46
+ function serializeSession(record) {
47
+ return JSON.stringify(record);
48
+ }
49
+ function parseSessionHours(value) {
50
+ if (value == null || value === "") return DEFAULT_SESSION_HOURS;
51
+ const n = Number(value);
52
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_SESSION_HOURS;
53
+ return n;
54
+ }
55
+
56
+ // src/url.ts
57
+ function appendQueryParam(url, key, value) {
58
+ if (!url || typeof url !== "string") return url;
59
+ const encoded = encodeURIComponent(value);
60
+ const hashIdx = url.indexOf("#");
61
+ const hash = hashIdx >= 0 ? url.slice(hashIdx) : "";
62
+ const base = hashIdx >= 0 ? url.slice(0, hashIdx) : url;
63
+ const sep = base.includes("?") ? "&" : "?";
64
+ return `${base}${sep}${encodeURIComponent(key)}=${encoded}${hash}`;
65
+ }
66
+ function buildLocalAssetUrl(domain, relativePath, cacheBust) {
67
+ const clean = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
68
+ return `https://${domain}/${clean}?_cb=${encodeURIComponent(String(cacheBust))}`;
69
+ }
70
+
71
+ // src/lna.ts
72
+ async function queryLoopbackPermission() {
73
+ const perms = typeof navigator !== "undefined" ? navigator.permissions : void 0;
74
+ if (!perms || typeof perms.query !== "function") {
75
+ return "unknown";
76
+ }
77
+ const names = ["loopback-network", "local-network-access"];
78
+ for (const name of names) {
79
+ try {
80
+ const status = await perms.query({ name });
81
+ const state = status && status.state;
82
+ if (state === "granted" || state === "prompt" || state === "denied") {
83
+ return state;
84
+ }
85
+ } catch {
86
+ }
87
+ }
88
+ return "unknown";
89
+ }
90
+ function lnaHintMessage(state) {
91
+ if (state === "prompt") {
92
+ return "Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.";
93
+ }
94
+ if (state === "denied") {
95
+ return "Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.";
96
+ }
97
+ return null;
98
+ }
99
+
100
+ // src/script-attrs.ts
101
+ function applyScriptLoadOrder(script, source) {
102
+ const hadAsync = source.hasAttribute("async");
103
+ const hadDefer = source.hasAttribute("defer");
104
+ if (hadAsync) {
105
+ script.async = true;
106
+ } else {
107
+ script.async = false;
108
+ if (!hadDefer) {
109
+ script.defer = true;
110
+ }
111
+ }
112
+ }
113
+
2
114
  // src/index.ts
3
115
  (function() {
4
- const K = "stagepass_domain";
116
+ const K = SESSION_KEY;
5
117
  const P = "stagepass";
6
- const isValidDomain = (d) => d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
118
+ const PKG_VERSION = true ? "2.0.0" : "0.0.0";
119
+ function getLoaderScript() {
120
+ try {
121
+ if (document.currentScript instanceof HTMLScriptElement) {
122
+ return document.currentScript;
123
+ }
124
+ } catch (_) {
125
+ }
126
+ try {
127
+ const scripts = document.querySelectorAll('script[src*="loader"]');
128
+ for (let i = scripts.length - 1; i >= 0; i--) {
129
+ const s = scripts[i];
130
+ if (/loader(?:\.min)?\.js/i.test(s.src || "")) return s;
131
+ }
132
+ } catch (_) {
133
+ }
134
+ return null;
135
+ }
136
+ const loaderScript = getLoaderScript();
137
+ const muteConsole = (loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-mute-console")) === "true";
138
+ const sessionHours = parseSessionHours(
139
+ loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-session-hours")
140
+ );
141
+ const loaderVersionAttr = loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-version");
7
142
  const p = new URLSearchParams(window.location.search);
8
143
  function getCallerLocation() {
9
144
  var _a;
@@ -23,26 +158,23 @@ var Stagepass = (() => {
23
158
  }
24
159
  return "";
25
160
  }
161
+ let hasActiveSession = false;
26
162
  function log(level, ...args) {
27
- const v = localStorage.getItem(K);
28
- if (!v) return;
29
- const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
30
- const loc = getCallerLocation();
31
- const pre = `[\u{1F3AB} ${t}${loc ? " |" + loc : ""}]`;
32
- if (level === "error") {
33
- console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
34
- } else if (console[level]) {
35
- console[level](pre, ...args);
36
- } else {
37
- console.log(pre, level, ...args);
38
- }
39
- }
40
- const splog = (...args) => log("log", ...args);
41
- const spwarn = (...args) => log("warn", ...args);
42
- const sperror = (...args) => log("error", ...args);
43
- window.splog = splog;
44
- window.spwarn = spwarn;
45
- window.sperror = sperror;
163
+ if (!hasActiveSession) return;
164
+ try {
165
+ const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
166
+ const loc = getCallerLocation();
167
+ const pre = `[\u{1F3AB} ${t}${loc ? " |" + loc : ""}]`;
168
+ if (level === "error") {
169
+ console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
170
+ } else if (console[level]) {
171
+ console[level](pre, ...args);
172
+ } else {
173
+ console.log(pre, level, ...args);
174
+ }
175
+ } catch (_) {
176
+ }
177
+ }
46
178
  function spLog(...args) {
47
179
  let level = "log";
48
180
  if (args.length > 0 && (args[0] === "warn" || args[0] === "error")) {
@@ -53,40 +185,81 @@ var Stagepass = (() => {
53
185
  }
54
186
  const spWarn = (...args) => log("warn", ...args);
55
187
  const spError = (...args) => log("error", ...args);
56
- const clean = (d) => d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
188
+ function readSessionDomain() {
189
+ try {
190
+ const raw = localStorage.getItem(K);
191
+ const record = parseSession(raw);
192
+ if (!record) {
193
+ if (raw) localStorage.removeItem(K);
194
+ return null;
195
+ }
196
+ return record.domain;
197
+ } catch (_) {
198
+ return null;
199
+ }
200
+ }
201
+ function writeSession(domain) {
202
+ try {
203
+ const record = createSession(domain, sessionHours);
204
+ localStorage.setItem(K, serializeSession(record));
205
+ } catch (_) {
206
+ }
207
+ }
208
+ function clearSession() {
209
+ try {
210
+ localStorage.removeItem(K);
211
+ } catch (_) {
212
+ }
213
+ }
57
214
  let paramProcessed = false;
58
- let sv = localStorage.getItem(K);
215
+ let sv = readSessionDomain();
59
216
  if (p.has(P)) {
60
217
  const v = p.get(P);
61
218
  if (v === "off" || v === "0" || v === "false") {
62
- localStorage.removeItem(K);
219
+ clearSession();
63
220
  sv = null;
64
- splog("\u{1F50C} Stagepass disconnected.");
221
+ hasActiveSession = true;
222
+ log("log", "\u{1F50C} Stagepass disconnected.");
223
+ hasActiveSession = false;
65
224
  } else if (v) {
66
- const c = v === "debug" ? "debug" : clean(v);
225
+ const c = v === "debug" ? "debug" : cleanDomain(v);
67
226
  if (c && isValidDomain(c)) {
68
- localStorage.setItem(K, c);
227
+ writeSession(c);
69
228
  sv = c;
70
- splog(c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`);
229
+ hasActiveSession = true;
230
+ log(
231
+ "log",
232
+ c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`
233
+ );
71
234
  paramProcessed = true;
72
235
  } else if (c) {
73
- spwarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
236
+ hasActiveSession = true;
237
+ spWarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
238
+ hasActiveSession = false;
74
239
  }
75
240
  }
76
- p.delete(P);
77
- const s = p.toString();
78
- window.history.replaceState({}, "", window.location.pathname + (s ? `?${s}` : "") + window.location.hash);
241
+ try {
242
+ p.delete(P);
243
+ const s = p.toString();
244
+ window.history.replaceState(
245
+ {},
246
+ "",
247
+ window.location.pathname + (s ? `?${s}` : "") + window.location.hash
248
+ );
249
+ } catch (_) {
250
+ }
79
251
  }
80
252
  if (sv && !isValidDomain(sv)) {
81
- localStorage.removeItem(K);
253
+ clearSession();
82
254
  sv = null;
83
255
  }
84
- if (sv && !paramProcessed && sv !== "debug") {
85
- splog(`\u{1F50C} Stagepass connected to: ${sv}`);
256
+ hasActiveSession = !!(sv && isValidDomain(sv));
257
+ if (sv && !paramProcessed && sv !== "debug" && hasActiveSession) {
258
+ log("log", `\u{1F50C} Stagepass connected to: ${sv}`);
86
259
  }
87
260
  const dev = !!sv;
88
261
  const swap = !!sv && sv !== "debug";
89
- const dom = swap ? clean(sv) : null;
262
+ const dom = swap ? cleanDomain(sv) : null;
90
263
  const now = swap ? Date.now() : 0;
91
264
  const cacheBust = now;
92
265
  const sessionStartTime = now;
@@ -94,110 +267,306 @@ var Stagepass = (() => {
94
267
  const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
95
268
  const isLocal = swap || isLocalhost;
96
269
  const env = isLocal ? "local" : hostname.endsWith(".webflow.io") ? "staging" : "production";
97
- const hasValidSession = sv && isValidDomain(sv);
98
- const shouldSuppress = !hasValidSession && !p.has(P);
99
- if (shouldSuppress && env === "production") {
100
- const noop = () => {
270
+ if (muteConsole && env === "production" && !hasActiveSession) {
271
+ try {
272
+ const noop = () => {
273
+ };
274
+ console.log = console.warn = console.error = console.info = console.debug = noop;
275
+ } catch (_) {
276
+ }
277
+ }
278
+ function getBrowserInfo(ua) {
279
+ let family = "unknown";
280
+ let major = null;
281
+ let m = null;
282
+ if (/Edg\/(\d+)/.test(ua)) {
283
+ family = "edge";
284
+ m = ua.match(/Edg\/(\d+)/);
285
+ } else if (/OPR\/(\d+)/.test(ua)) {
286
+ family = "opera";
287
+ m = ua.match(/OPR\/(\d+)/);
288
+ } else if (/Firefox\/(\d+)/.test(ua)) {
289
+ family = "firefox";
290
+ m = ua.match(/Firefox\/(\d+)/);
291
+ } else if (/Chrome\/(\d+)/.test(ua)) {
292
+ family = "chrome";
293
+ m = ua.match(/Chrome\/(\d+)/);
294
+ } else if (/Version\/(\d+).+Safari\//.test(ua)) {
295
+ family = "safari";
296
+ m = ua.match(/Version\/(\d+)/);
297
+ }
298
+ if (m && m[1]) major = Number(m[1]);
299
+ return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
300
+ }
301
+ function getOsInfo(ua) {
302
+ if (/Android/i.test(ua)) return { family: "android" };
303
+ if (/iPhone|iPad|iPod/i.test(ua)) return { family: "ios" };
304
+ if (/Mac OS X|Macintosh/i.test(ua)) return { family: "macos" };
305
+ if (/Windows NT/i.test(ua)) return { family: "windows" };
306
+ if (/Linux/i.test(ua)) return { family: "linux" };
307
+ return { family: "unknown" };
308
+ }
309
+ function getDeviceInfo(ua) {
310
+ const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
311
+ let type = "desktop";
312
+ if (/iPad|Tablet/i.test(ua)) type = "tablet";
313
+ else if (/Mobi|Android.+Mobile|iPhone/i.test(ua)) type = "mobile";
314
+ else if (/Android/i.test(ua) && touch) type = "tablet";
315
+ return { type, touch };
316
+ }
317
+ function getThemeInfo() {
318
+ let preferred = "no-preference";
319
+ let current = "unknown";
320
+ try {
321
+ if (window.matchMedia) {
322
+ if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
323
+ preferred = "dark";
324
+ current = "dark";
325
+ } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
326
+ preferred = "light";
327
+ current = "light";
328
+ }
329
+ }
330
+ } catch (_) {
331
+ }
332
+ return { preferred, current };
333
+ }
334
+ function hasStorage(type) {
335
+ try {
336
+ const storage = window[type];
337
+ const key = "__stagepass_test__";
338
+ storage.setItem(key, "1");
339
+ storage.removeItem(key);
340
+ return true;
341
+ } catch (_) {
342
+ return false;
343
+ }
344
+ }
345
+ function getClientInfo() {
346
+ const ua = navigator.userAgent || "";
347
+ let timezone = null;
348
+ try {
349
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
350
+ } catch (_) {
351
+ }
352
+ return {
353
+ theme: getThemeInfo(),
354
+ browser: getBrowserInfo(ua),
355
+ os: getOsInfo(ua),
356
+ device: getDeviceInfo(ua),
357
+ viewport: {
358
+ width: window.innerWidth || 0,
359
+ height: window.innerHeight || 0,
360
+ dpr: window.devicePixelRatio || 1
361
+ },
362
+ locale: {
363
+ language: navigator.language || "unknown",
364
+ timezone
365
+ },
366
+ capabilities: {
367
+ cookiesEnabled: navigator.cookieEnabled === true,
368
+ localStorage: hasStorage("localStorage"),
369
+ sessionStorage: hasStorage("sessionStorage")
370
+ }
101
371
  };
102
- console.log = console.warn = console.error = console.info = console.debug = noop;
103
372
  }
104
373
  const stagepassObj = window.stagepass || {};
374
+ const clientInfo = getClientInfo();
105
375
  stagepassObj.vars = Object.freeze({
106
376
  isLocal,
107
377
  env,
108
378
  domain: dom || hostname,
109
379
  timestamp: sessionStartTime,
110
- version: "1.1.4"
380
+ version: PKG_VERSION,
381
+ client: clientInfo
111
382
  });
112
383
  stagepassObj.log = spLog;
113
384
  stagepassObj.warn = spWarn;
114
385
  stagepassObj.error = spError;
115
386
  stagepassObj.resolveLocalUrl = (relativePath) => {
116
387
  const v = stagepassObj.vars;
117
- if (!v.isLocal || !v.domain) return "";
118
- const clean2 = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
119
- return clean2 ? `https://${v.domain}/${clean2}?_cb=${v.timestamp}` : "";
388
+ if (!swap || !dom || !relativePath) return "";
389
+ return buildLocalAssetUrl(dom, relativePath, v.timestamp || Date.now());
120
390
  };
121
391
  window.stagepass = stagepassObj;
122
392
  globalThis.stagepass = stagepassObj;
123
393
  window.sp = stagepassObj;
124
394
  globalThis.sp = stagepassObj;
395
+ try {
396
+ if (window.matchMedia) {
397
+ const darkMq = window.matchMedia("(prefers-color-scheme: dark)");
398
+ const lightMq = window.matchMedia("(prefers-color-scheme: light)");
399
+ const updateTheme = () => {
400
+ var _a, _b;
401
+ if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.theme)) return;
402
+ if (darkMq.matches) {
403
+ stagepassObj.vars.client.theme.current = "dark";
404
+ stagepassObj.vars.client.theme.preferred = "dark";
405
+ } else if (lightMq.matches) {
406
+ stagepassObj.vars.client.theme.current = "light";
407
+ stagepassObj.vars.client.theme.preferred = "light";
408
+ } else {
409
+ stagepassObj.vars.client.theme.current = "unknown";
410
+ stagepassObj.vars.client.theme.preferred = "no-preference";
411
+ }
412
+ };
413
+ if (typeof darkMq.addEventListener === "function") {
414
+ darkMq.addEventListener("change", updateTheme);
415
+ lightMq.addEventListener("change", updateTheme);
416
+ } else if (typeof darkMq.addListener === "function") {
417
+ darkMq.addListener(updateTheme);
418
+ lightMq.addListener(updateTheme);
419
+ }
420
+ }
421
+ } catch (_) {
422
+ }
423
+ const updateViewport = () => {
424
+ var _a, _b;
425
+ if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.viewport)) return;
426
+ stagepassObj.vars.client.viewport.width = window.innerWidth || 0;
427
+ stagepassObj.vars.client.viewport.height = window.innerHeight || 0;
428
+ stagepassObj.vars.client.viewport.dpr = window.devicePixelRatio || 1;
429
+ };
430
+ window.addEventListener("resize", updateViewport);
431
+ let lnaState = "unknown";
432
+ let lnaHint = null;
433
+ function resolveAssetUrl(el, productionSrc, localPath) {
434
+ if (swap && localPath && dom) {
435
+ return buildLocalAssetUrl(dom, localPath, cacheBust);
436
+ }
437
+ const perAssetVersion = el.getAttribute("data-stagepass-v");
438
+ const version = perAssetVersion || loaderVersionAttr;
439
+ if (version) {
440
+ return appendQueryParam(productionSrc, "v", version);
441
+ }
442
+ return productionSrc;
443
+ }
125
444
  function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
126
445
  document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
127
- el.setAttribute("data-stagepass-processed", "true");
128
- let lp = el.getAttribute(pathAttr);
129
- const ps = el.getAttribute(srcAttr);
130
- if (!ps) return;
131
- if (!lp && ps && swap && dom) {
132
- try {
133
- const urlObj = new URL(ps);
134
- const pathParts = urlObj.pathname.split("/");
135
- lp = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
136
- } catch (e) {
137
- const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
138
- if (match) lp = match[1];
446
+ try {
447
+ el.setAttribute("data-stagepass-processed", "true");
448
+ let lp = el.getAttribute(pathAttr);
449
+ const ps = el.getAttribute(srcAttr);
450
+ if (!ps) return;
451
+ if (!lp && ps && swap && dom) {
452
+ try {
453
+ const urlObj = new URL(ps);
454
+ const pathParts = urlObj.pathname.split("/");
455
+ lp = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
456
+ } catch (e) {
457
+ const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
458
+ if (match) lp = match[1];
459
+ }
139
460
  }
140
- }
141
- let url;
142
- if (swap && lp && dom) {
143
- url = `https://${dom}/${lp.startsWith("/") ? lp.substring(1) : lp}?_cb=${cacheBust}`;
144
- } else if (el.getAttribute("data-stagepass-cachebust") === "true") {
145
- url = ps + (ps.includes("?") ? "&" : "?") + "_cb=" + Date.now();
146
- } else {
147
- url = ps;
148
- }
149
- if (!url) return;
150
- const n = document.createElement(type);
151
- if (type === "script") {
152
- n.src = url;
153
- Array.from(el.attributes).forEach((a) => {
154
- const attr = a;
155
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
156
- });
157
- if (!el.hasAttribute("async") && !el.hasAttribute("defer")) n.setAttribute("defer", "");
158
- } else {
159
- n.rel = "stylesheet";
160
- n.href = url;
161
- Array.from(el.attributes).forEach((a) => {
162
- const attr = a;
163
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
164
- });
165
- }
166
- if (el.parentNode) {
167
- el.parentNode.insertBefore(n, el);
168
- el.remove();
169
- } else {
170
- sperror(`${type} injection failed: No parent node`);
461
+ const url = resolveAssetUrl(el, ps, lp);
462
+ if (!url) return;
463
+ const n = document.createElement(type);
464
+ if (type === "script") {
465
+ n.src = url;
466
+ Array.from(el.attributes).forEach((a) => {
467
+ const attr = a;
468
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
469
+ });
470
+ applyScriptLoadOrder(n, el);
471
+ } else {
472
+ n.rel = "stylesheet";
473
+ n.href = url;
474
+ Array.from(el.attributes).forEach((a) => {
475
+ const attr = a;
476
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
477
+ });
478
+ }
479
+ if (el.parentNode) {
480
+ el.parentNode.insertBefore(n, el);
481
+ el.remove();
482
+ } else {
483
+ spError(`${type} injection failed: No parent node`);
484
+ }
485
+ } catch (_) {
171
486
  }
172
487
  });
173
488
  }
174
489
  const process = () => {
175
- swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", ["data-src", "data-stagepass", "data-stagepass-path", "data-stagepass-cachebust"]);
176
- swapEl('link[rel="stylesheet"][data-stagepass]', "data-stagepass-path", "data-href", "link", ["href", "data-href", "data-stagepass", "data-stagepass-path", "data-stagepass-cachebust"]);
490
+ try {
491
+ swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", [
492
+ "data-src",
493
+ "data-stagepass",
494
+ "data-stagepass-path",
495
+ "data-stagepass-cachebust",
496
+ "data-stagepass-v"
497
+ ]);
498
+ swapEl(
499
+ 'link[rel="stylesheet"][data-stagepass]',
500
+ "data-stagepass-path",
501
+ "data-href",
502
+ "link",
503
+ [
504
+ "href",
505
+ "data-href",
506
+ "data-stagepass",
507
+ "data-stagepass-path",
508
+ "data-stagepass-cachebust",
509
+ "data-stagepass-v"
510
+ ]
511
+ );
512
+ } catch (_) {
513
+ }
177
514
  };
178
- process();
179
- if (document.readyState === "loading") {
180
- document.addEventListener("DOMContentLoaded", process);
515
+ function updateFlagText(flag2) {
516
+ let text = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
517
+ if (lnaHint) {
518
+ text = sv === "debug" ? "STAGEPASS DEBUG \xB7 LNA" : "STAGEPASS \xB7 ALLOW LOCAL NETWORK";
519
+ }
520
+ flag2.textContent = text;
521
+ if (lnaHint) {
522
+ flag2.title = lnaHint;
523
+ }
181
524
  }
182
525
  function flag() {
183
526
  if (!dev) return;
184
- const f = document.createElement("div");
185
- f.id = "stagepass-flag";
186
- f.textContent = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
187
- f.style.cssText = 'font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;';
188
- f.addEventListener("click", () => {
189
- localStorage.removeItem(K);
190
- splog("\u{1F50C} Stagepass disconnected.");
191
- window.location.reload();
192
- });
193
- if (document.body) {
194
- document.body.appendChild(f);
195
- } else {
196
- document.addEventListener("DOMContentLoaded", () => {
197
- if (document.body) document.body.appendChild(f);
527
+ try {
528
+ const f = document.createElement("div");
529
+ f.id = "stagepass-flag";
530
+ updateFlagText(f);
531
+ f.style.cssText = 'font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;';
532
+ f.addEventListener("click", () => {
533
+ clearSession();
534
+ hasActiveSession = true;
535
+ log("log", "\u{1F50C} Stagepass disconnected.");
536
+ window.location.reload();
198
537
  });
538
+ const mount = () => {
539
+ if (document.body) document.body.appendChild(f);
540
+ };
541
+ if (document.body) mount();
542
+ else document.addEventListener("DOMContentLoaded", mount);
543
+ stagepassObj.__flagEl = f;
544
+ } catch (_) {
199
545
  }
200
546
  }
547
+ async function maybeCheckLnaAndProcess() {
548
+ if (swap) {
549
+ try {
550
+ lnaState = await queryLoopbackPermission();
551
+ lnaHint = lnaHintMessage(lnaState);
552
+ if (lnaHint) {
553
+ spWarn(lnaHint);
554
+ const flagEl = stagepassObj.__flagEl;
555
+ if (flagEl) updateFlagText(flagEl);
556
+ }
557
+ } catch (_) {
558
+ lnaState = "unknown";
559
+ lnaHint = null;
560
+ }
561
+ }
562
+ process();
563
+ }
564
+ void maybeCheckLnaAndProcess();
565
+ if (document.readyState === "loading") {
566
+ document.addEventListener("DOMContentLoaded", () => {
567
+ void maybeCheckLnaAndProcess();
568
+ });
569
+ }
201
570
  if (document.readyState === "loading") {
202
571
  document.addEventListener("DOMContentLoaded", flag);
203
572
  } else {
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{(function(){let p="stagepass_domain",S="stagepass",v=t=>t==="debug"||t.endsWith(".sp")||t==="localhost"||t.startsWith("localhost:"),m=new URLSearchParams(window.location.search);function W(){var t;try{let e=(t=new Error().stack)==null?void 0:t.split(`
2
- `);if(!e)return"";let n=/loader(?:\.min)?\.js/i;for(let c=3;c<e.length;c++){let s=e[c].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(s){let i=s[1];if(!n.test(i))return` ${i}:${s[2]}`}}}catch{}return""}function g(t,...e){if(!localStorage.getItem(p))return;let c=new Date().toTimeString().split(" ")[0],f=W(),s=`[\u{1F3AB} ${c}${f?" |"+f:""}]`;t==="error"?console.log(`%c${s}`,"color: red; font-weight: bold;",...e):console[t]?console[t](s,...e):console.log(s,t,...e)}let b=(...t)=>g("log",...t),E=(...t)=>g("warn",...t),$=(...t)=>g("error",...t);window.splog=b,window.spwarn=E,window.sperror=$;function j(...t){let e="log";t.length>0&&(t[0]==="warn"||t[0]==="error")&&(e=t[0],t=t.slice(1)),g(e,...t)}let M=(...t)=>g("warn",...t),P=(...t)=>g("error",...t),A=t=>t?t.replace(/^https?:\/\//,"").replace(/\/$/,""):null,k=!1,o=localStorage.getItem(p);if(m.has(S)){let t=m.get(S);if(t==="off"||t==="0"||t==="false")localStorage.removeItem(p),o=null,b("\u{1F50C} Stagepass disconnected.");else if(t){let n=t==="debug"?"debug":A(t);n&&v(n)?(localStorage.setItem(p,n),o=n,b(n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`),k=!0):n&&E(`Invalid domain: ${n}. Only .sp domains are allowed.`)}m.delete(S);let e=m.toString();window.history.replaceState({},"",window.location.pathname+(e?`?${e}`:"")+window.location.hash)}o&&!v(o)&&(localStorage.removeItem(p),o=null),o&&!k&&o!=="debug"&&b(`\u{1F50C} Stagepass connected to: ${o}`);let U=!!o,w=!!o&&o!=="debug",L=w?A(o):null,T=w?Date.now():0,_=T,B=T,u=window.location.hostname,V=u==="localhost"||u==="127.0.0.1"||u.startsWith("localhost:")||u.startsWith("127.0.0.1:"),C=w||V,D=C?"local":u.endsWith(".webflow.io")?"staging":"production";!(o&&v(o))&&!m.has(S)&&D==="production"&&(console.log=console.warn=console.error=console.info=console.debug=()=>{});let r=window.stagepass||{};r.vars=Object.freeze({isLocal:C,env:D,domain:L||u,timestamp:B,version:"1.1.4"}),r.log=j,r.warn=M,r.error=P,r.resolveLocalUrl=t=>{let e=r.vars;if(!e.isLocal||!e.domain)return"";let n=t.startsWith("/")?t.substring(1):t;return n?`https://${e.domain}/${n}?_cb=${e.timestamp}`:""},window.stagepass=r,globalThis.stagepass=r,window.sp=r,globalThis.sp=r;function I(t,e,n,c,f){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(s=>{s.setAttribute("data-stagepass-processed","true");let i=s.getAttribute(e),l=s.getAttribute(n);if(!l)return;if(!i&&l&&w&&L)try{let a=new URL(l).pathname.split("/");i=a[a.length-1]||a[a.length-2]}catch{let a=l.match(/\/([^\/\?#]+)(?:\?|#|$)/);a&&(i=a[1])}let h;if(w&&i&&L?h=`https://${L}/${i.startsWith("/")?i.substring(1):i}?_cb=${_}`:s.getAttribute("data-stagepass-cachebust")==="true"?h=l+(l.includes("?")?"&":"?")+"_cb="+Date.now():h=l,!h)return;let d=document.createElement(c);c==="script"?(d.src=h,Array.from(s.attributes).forEach(y=>{let a=y;f.includes(a.name)||d.setAttribute(a.name,a.value)}),!s.hasAttribute("async")&&!s.hasAttribute("defer")&&d.setAttribute("defer","")):(d.rel="stylesheet",d.href=h,Array.from(s.attributes).forEach(y=>{let a=y;f.includes(a.name)||d.setAttribute(a.name,a.value)})),s.parentNode?(s.parentNode.insertBefore(d,s),s.remove()):$(`${c} injection failed: No parent node`)})}let x=()=>{I("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path","data-stagepass-cachebust"]),I('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path","data-stagepass-cachebust"])};x(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",x);function O(){if(!U)return;let t=document.createElement("div");t.id="stagepass-flag",t.textContent=o==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",t.style.cssText='font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;',t.addEventListener("click",()=>{localStorage.removeItem(p),b("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(t):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O()})();})();
1
+ var Stagepass=(()=>{function E(n){if(typeof n!="string"||!n)return!1;if(n==="debug"||n==="localhost")return!0;if(n.startsWith("localhost:")){let o=n.slice(10);return/^[0-9]{1,5}$/.test(o)&&Number(o)<=65535}return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.sp$/i.test(n)}function N(n){return n?n.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var q="stagepass_domain",x=12;function B(n,o=Date.now()){if(!n||!n.startsWith("{"))return null;try{let a=JSON.parse(n);return typeof a.domain!="string"||typeof a.expires!="number"||!Number.isFinite(a.expires)||!E(a.domain)||a.expires<=o?null:{domain:a.domain,expires:a.expires}}catch{return null}}function K(n,o=x,a=Date.now()){let p=Number.isFinite(o)&&o>0?o:x;return{domain:n,expires:a+p*60*60*1e3}}function J(n){return JSON.stringify(n)}function Q(n){if(n==null||n==="")return x;let o=Number(n);return!Number.isFinite(o)||o<=0?x:o}function Y(n,o,a){if(!n||typeof n!="string")return n;let p=encodeURIComponent(a),c=n.indexOf("#"),T=c>=0?n.slice(c):"",A=c>=0?n.slice(0,c):n,I=A.includes("?")?"&":"?";return`${A}${I}${encodeURIComponent(o)}=${p}${T}`}function $(n,o,a){let p=o.startsWith("/")?o.substring(1):o;return`https://${n}/${p}?_cb=${encodeURIComponent(String(a))}`}async function X(){let n=typeof navigator<"u"?navigator.permissions:void 0;if(!n||typeof n.query!="function")return"unknown";let o=["loopback-network","local-network-access"];for(let a of o)try{let p=await n.query({name:a}),c=p&&p.state;if(c==="granted"||c==="prompt"||c==="denied")return c}catch{}return"unknown"}function Z(n){return n==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":n==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function ee(n,o){let a=o.hasAttribute("async"),p=o.hasAttribute("defer");a?n.async=!0:(n.async=!1,p||(n.defer=!0))}(function(){let n=q,o="stagepass",a="2.0.0";function p(){try{if(document.currentScript instanceof HTMLScriptElement)return document.currentScript}catch{}try{let e=document.querySelectorAll('script[src*="loader"]');for(let t=e.length-1;t>=0;t--){let s=e[t];if(/loader(?:\.min)?\.js/i.test(s.src||""))return s}}catch{}return null}let c=p(),T=(c==null?void 0:c.getAttribute("data-stagepass-mute-console"))==="true",A=Q(c==null?void 0:c.getAttribute("data-stagepass-session-hours")),I=c==null?void 0:c.getAttribute("data-stagepass-version"),_=new URLSearchParams(window.location.search);function te(){var e;try{let t=(e=new Error().stack)==null?void 0:e.split(`
2
+ `);if(!t)return"";let s=/loader(?:\.min)?\.js/i;for(let i=3;i<t.length;i++){let d=t[i].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(d){let g=d[1];if(!s.test(g))return` ${g}:${d[2]}`}}}catch{}return""}let m=!1;function h(e,...t){if(m)try{let s=new Date().toTimeString().split(" ")[0],i=te(),f=`[\u{1F3AB} ${s}${i?" |"+i:""}]`;e==="error"?console.log(`%c${f}`,"color: red; font-weight: bold;",...t):console[e]?console[e](f,...t):console.log(f,e,...t)}catch{}}function ne(...e){let t="log";e.length>0&&(e[0]==="warn"||e[0]==="error")&&(t=e[0],e=e.slice(1)),h(t,...e)}let C=(...e)=>h("warn",...e),R=(...e)=>h("error",...e);function se(){try{let e=localStorage.getItem(n),t=B(e);return t?t.domain:(e&&localStorage.removeItem(n),null)}catch{return null}}function oe(e){try{let t=K(e,A);localStorage.setItem(n,J(t))}catch{}}function M(){try{localStorage.removeItem(n)}catch{}}let D=!1,l=se();if(_.has(o)){let e=_.get(o);if(e==="off"||e==="0"||e==="false")M(),l=null,m=!0,h("log","\u{1F50C} Stagepass disconnected."),m=!1;else if(e){let t=e==="debug"?"debug":N(e);t&&E(t)?(oe(t),l=t,m=!0,h("log",t==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${t}`),D=!0):t&&(m=!0,C(`Invalid domain: ${t}. Only .sp domains are allowed.`),m=!1)}try{_.delete(o);let t=_.toString();window.history.replaceState({},"",window.location.pathname+(t?`?${t}`:"")+window.location.hash)}catch{}}l&&!E(l)&&(M(),l=null),m=!!(l&&E(l)),l&&!D&&l!=="debug"&&m&&h("log",`\u{1F50C} Stagepass connected to: ${l}`);let re=!!l,w=!!l&&l!=="debug",y=w?N(l):null,H=w?Date.now():0,ie=H,ae=H,v=window.location.hostname,ce=v==="localhost"||v==="127.0.0.1"||v.startsWith("localhost:")||v.startsWith("127.0.0.1:"),U=w||ce,V=U?"local":v.endsWith(".webflow.io")?"staging":"production";if(T&&V==="production"&&!m)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}function le(e){let t="unknown",s=null,i=null;return/Edg\/(\d+)/.test(e)?(t="edge",i=e.match(/Edg\/(\d+)/)):/OPR\/(\d+)/.test(e)?(t="opera",i=e.match(/OPR\/(\d+)/)):/Firefox\/(\d+)/.test(e)?(t="firefox",i=e.match(/Firefox\/(\d+)/)):/Chrome\/(\d+)/.test(e)?(t="chrome",i=e.match(/Chrome\/(\d+)/)):/Version\/(\d+).+Safari\//.test(e)&&(t="safari",i=e.match(/Version\/(\d+)/)),i&&i[1]&&(s=Number(i[1])),{family:t,major:Number.isFinite(s)?s:null,userAgent:e}}function de(e){return/Android/i.test(e)?{family:"android"}:/iPhone|iPad|iPod/i.test(e)?{family:"ios"}:/Mac OS X|Macintosh/i.test(e)?{family:"macos"}:/Windows NT/i.test(e)?{family:"windows"}:/Linux/i.test(e)?{family:"linux"}:{family:"unknown"}}function ue(e){let t="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,s="desktop";return/iPad|Tablet/i.test(e)?s="tablet":/Mobi|Android.+Mobile|iPhone/i.test(e)?s="mobile":/Android/i.test(e)&&t&&(s="tablet"),{type:s,touch:t}}function fe(){let e="no-preference",t="unknown";try{window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").matches?(e="dark",t="dark"):window.matchMedia("(prefers-color-scheme: light)").matches&&(e="light",t="light"))}catch{}return{preferred:e,current:t}}function z(e){try{let t=window[e],s="__stagepass_test__";return t.setItem(s,"1"),t.removeItem(s),!0}catch{return!1}}function pe(){let e=navigator.userAgent||"",t=null;try{t=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:fe(),browser:le(e),os:de(e),device:ue(e),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:t},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:z("localStorage"),sessionStorage:z("sessionStorage")}}}let r=window.stagepass||{},me=pe();r.vars=Object.freeze({isLocal:U,env:V,domain:y||v,timestamp:ae,version:a,client:me}),r.log=ne,r.warn=C,r.error=R,r.resolveLocalUrl=e=>{let t=r.vars;return!w||!y||!e?"":$(y,e,t.timestamp||Date.now())},window.stagepass=r,globalThis.stagepass=r,window.sp=r,globalThis.sp=r;try{if(window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),t=window.matchMedia("(prefers-color-scheme: light)"),s=()=>{var i,f;(f=(i=r.vars)==null?void 0:i.client)!=null&&f.theme&&(e.matches?(r.vars.client.theme.current="dark",r.vars.client.theme.preferred="dark"):t.matches?(r.vars.client.theme.current="light",r.vars.client.theme.preferred="light"):(r.vars.client.theme.current="unknown",r.vars.client.theme.preferred="no-preference"))};typeof e.addEventListener=="function"?(e.addEventListener("change",s),t.addEventListener("change",s)):typeof e.addListener=="function"&&(e.addListener(s),t.addListener(s))}}catch{}let ge=()=>{var e,t;(t=(e=r.vars)==null?void 0:e.client)!=null&&t.viewport&&(r.vars.client.viewport.width=window.innerWidth||0,r.vars.client.viewport.height=window.innerHeight||0,r.vars.client.viewport.dpr=window.devicePixelRatio||1)};window.addEventListener("resize",ge);let O="unknown",S=null;function he(e,t,s){if(w&&s&&y)return $(y,s,ie);let f=e.getAttribute("data-stagepass-v")||I;return f?Y(t,"v",f):t}function W(e,t,s,i,f){document.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(d=>{try{d.setAttribute("data-stagepass-processed","true");let g=d.getAttribute(t),k=d.getAttribute(s);if(!k)return;if(!g&&k&&w&&y)try{let u=new URL(k).pathname.split("/");g=u[u.length-1]||u[u.length-2]}catch{let u=k.match(/\/([^\/\?#]+)(?:\?|#|$)/);u&&(g=u[1])}let P=he(d,k,g);if(!P)return;let b=document.createElement(i);i==="script"?(b.src=P,Array.from(d.attributes).forEach(L=>{let u=L;f.includes(u.name)||b.setAttribute(u.name,u.value)}),ee(b,d)):(b.rel="stylesheet",b.href=P,Array.from(d.attributes).forEach(L=>{let u=L;f.includes(u.name)||b.setAttribute(u.name,u.value)})),d.parentNode?(d.parentNode.insertBefore(b,d),d.remove()):R(`${i} injection failed: No parent node`)}catch{}})}let we=()=>{try{W("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"]),W('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"])}catch{}};function j(e){let t=l==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE";S&&(t=l==="debug"?"STAGEPASS DEBUG \xB7 LNA":"STAGEPASS \xB7 ALLOW LOCAL NETWORK"),e.textContent=t,S&&(e.title=S)}function F(){if(re)try{let e=document.createElement("div");e.id="stagepass-flag",j(e),e.style.cssText='font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;',e.addEventListener("click",()=>{M(),m=!0,h("log","\u{1F50C} Stagepass disconnected."),window.location.reload()});let t=()=>{document.body&&document.body.appendChild(e)};document.body?t():document.addEventListener("DOMContentLoaded",t),r.__flagEl=e}catch{}}async function G(){if(w)try{if(O=await X(),S=Z(O),S){C(S);let e=r.__flagEl;e&&j(e)}}catch{O="unknown",S=null}we()}G(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",()=>{G()}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",F):F()})();})();
package/global.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Runtime client theme preference.
3
+ */
4
+ export interface StagepassClientTheme {
5
+ preferred: 'light' | 'dark' | 'no-preference';
6
+ current: 'light' | 'dark' | 'unknown';
7
+ }
8
+
9
+ /**
10
+ * Best-effort browser / device info exposed on `stagepass.vars.client`.
11
+ */
12
+ export interface StagepassClientInfo {
13
+ theme: StagepassClientTheme;
14
+ browser: {
15
+ family: 'chrome' | 'safari' | 'firefox' | 'edge' | 'opera' | 'unknown';
16
+ major: number | null;
17
+ userAgent: string;
18
+ };
19
+ os: {
20
+ family: 'macos' | 'windows' | 'ios' | 'android' | 'linux' | 'unknown';
21
+ };
22
+ device: {
23
+ type: 'mobile' | 'tablet' | 'desktop' | 'unknown';
24
+ touch: boolean;
25
+ };
26
+ viewport: {
27
+ width: number;
28
+ height: number;
29
+ dpr: number;
30
+ };
31
+ locale: {
32
+ language: string;
33
+ timezone: string | null;
34
+ };
35
+ capabilities: {
36
+ cookiesEnabled: boolean;
37
+ localStorage: boolean;
38
+ sessionStorage: boolean;
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Read-only runtime variables set by the Stagepass loader.
44
+ */
45
+ export interface StagepassVars {
46
+ /** True when a local session is active or the page is on localhost. */
47
+ isLocal: boolean;
48
+ env: 'local' | 'staging' | 'production';
49
+ /** Active .sp domain, or the page hostname when no session. */
50
+ domain: string;
51
+ /** Session start timestamp (ms) when swapping; otherwise 0. */
52
+ timestamp: number;
53
+ /** Package version injected at build time. */
54
+ version: string;
55
+ client: StagepassClientInfo;
56
+ }
57
+
58
+ /**
59
+ * Core Stagepass runtime API (loader). Modules extend this via declaration merging.
60
+ */
61
+ export interface StagepassAPI {
62
+ vars: StagepassVars;
63
+ /** Structured log (only when a session is active). */
64
+ log: (...args: unknown[]) => void;
65
+ warn: (...args: unknown[]) => void;
66
+ error: (...args: unknown[]) => void;
67
+ /**
68
+ * Build a local HTTPS asset URL when a session is active.
69
+ * @param relativePath - Path under the linked project root
70
+ * @returns Local URL, or empty string when no session
71
+ */
72
+ resolveLocalUrl: (relativePath: string) => string;
73
+ }
74
+
75
+ declare global {
76
+ interface Window {
77
+ stagepass: StagepassAPI;
78
+ sp: StagepassAPI;
79
+ }
80
+
81
+ // Global aliases (same object as window.stagepass)
82
+ // eslint-disable-next-line no-var
83
+ var stagepass: StagepassAPI;
84
+ // eslint-disable-next-line no-var
85
+ var sp: StagepassAPI;
86
+ }
87
+
88
+ export {};
package/package.json CHANGED
@@ -1,17 +1,22 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "1.1.4",
3
+ "version": "2.0.0",
4
4
  "description": "Universal loader for Stagepass - injects local files into Webflow projects",
5
5
  "main": "dist/loader.min.js",
6
+ "types": "global.d.ts",
6
7
  "type": "module",
7
8
  "files": [
8
- "dist"
9
+ "dist",
10
+ "global.d.ts",
11
+ "README.md",
12
+ "LICENSE"
9
13
  ],
10
14
  "scripts": {
11
15
  "build": "tsup",
12
16
  "dev": "tsup --watch",
13
- "test": "vitest run",
14
- "test:watch": "vitest"
17
+ "test": "vitest run && npm run typecheck",
18
+ "test:watch": "vitest",
19
+ "typecheck": "tsc --noEmit -p fixtures/tsconfig.json"
15
20
  },
16
21
  "keywords": [
17
22
  "webflow",
@@ -27,10 +32,9 @@
27
32
  },
28
33
  "license": "MIT",
29
34
  "devDependencies": {
35
+ "jsdom": "^24.0.0",
30
36
  "tsup": "^8.0.1",
31
37
  "typescript": "^5.3.3",
32
- "vitest": "^2.1.0",
33
- "jsdom": "^24.0.0",
34
- "@vitest/ui": "^2.1.0"
38
+ "vitest": "^5.0.5"
35
39
  }
36
40
  }