@stagepass/loader 1.2.0 → 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 CHANGED
@@ -7,48 +7,106 @@ The loader reads Stagepass session state and swaps tagged production assets with
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- npm install @stagepass/loader
10
+ npm install @stagepass/loader@2.0.0
11
11
  ```
12
12
 
13
13
  ## CDN Usage
14
14
 
15
+ Pin exact versions in production (jsDelivr preferred; unpkg alternative):
16
+
15
17
  ```html
16
- <script src="https://cdn.jsdelivr.net/npm/@stagepass/loader@1/dist/loader.min.js"></script>
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>
17
22
  ```
18
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
+
19
30
  ## What it does
20
31
 
21
- - Processes `script[data-stagepass]` and `link[rel="stylesheet"][data-stagepass]`.
22
- - Uses `data-src` / `data-href` as source URL.
23
- - Uses `data-stagepass-path` as optional local path override.
24
- - Adds cache busting in local mode via `?_cb=<timestamp>`.
25
- - Optional production cache busting with `data-stagepass-cachebust="true"`.
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. |
26
62
 
27
- ## Runtime API
63
+ ## URL Modes
28
64
 
29
- Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`).
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.
30
68
 
31
- - `sp.vars.isLocal`
32
- - `sp.vars.env`
33
- - `sp.vars.domain`
34
- - `sp.vars.timestamp`
35
- - `sp.vars.version`
36
- - `sp.vars.client.*` (theme/browser/os/device/viewport/locale/capabilities)
37
- - `sp.resolveLocalUrl(relativePath)`
38
- - `sp.log(...)`, `sp.warn(...)`, `sp.error(...)`
69
+ Allowed session values: `*.sp`, `localhost`, `localhost:<port>`, `debug`. Invalid values are rejected/cleared.
39
70
 
40
- Deprecated aliases (still available): `splog`, `spwarn`, `sperror`.
71
+ After handling, `?stagepass=` is removed with `history.replaceState` (other query params and the hash are kept).
41
72
 
42
- ## URL Modes
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
+ ```
43
103
 
44
- - `?stagepass=my-project.sp` - activate local swapping.
45
- - `?stagepass=debug` - logging only.
46
- - `?stagepass=off` - deactivate session.
104
+ Logging helpers only print while a Stagepass session is active. Deprecated globals `splog` / `spwarn` / `sperror` were removed in v2.
47
105
 
48
106
  ## Related Packages
49
107
 
50
- - `@stagepass/cli` - creates and manages `.sp` infrastructure.
51
- - `@stagepass/modules` - optional modules that extend the loader.
108
+ - `@stagepass/cli`: creates and manages `.sp` infrastructure.
109
+ - `@stagepass/modules`: optional modules that extend the loader (`inject`, `cookies`).
52
110
 
53
111
  ## Repository
54
112
 
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);
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 (_) {
38
176
  }
39
177
  }
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;
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,12 +267,13 @@ 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 = () => {
101
- };
102
- console.log = console.warn = console.error = console.info = console.debug = 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
+ }
103
277
  }
104
278
  function getBrowserInfo(ua) {
105
279
  let family = "unknown";
@@ -203,7 +377,7 @@ var Stagepass = (() => {
203
377
  env,
204
378
  domain: dom || hostname,
205
379
  timestamp: sessionStartTime,
206
- version: "1.2.0",
380
+ version: PKG_VERSION,
207
381
  client: clientInfo
208
382
  });
209
383
  stagepassObj.log = spLog;
@@ -211,9 +385,8 @@ var Stagepass = (() => {
211
385
  stagepassObj.error = spError;
212
386
  stagepassObj.resolveLocalUrl = (relativePath) => {
213
387
  const v = stagepassObj.vars;
214
- if (!v.isLocal || !v.domain) return "";
215
- const clean2 = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
216
- return clean2 ? `https://${v.domain}/${clean2}?_cb=${v.timestamp}` : "";
388
+ if (!swap || !dom || !relativePath) return "";
389
+ return buildLocalAssetUrl(dom, relativePath, v.timestamp || Date.now());
217
390
  };
218
391
  window.stagepass = stagepassObj;
219
392
  globalThis.stagepass = stagepassObj;
@@ -255,81 +428,144 @@ var Stagepass = (() => {
255
428
  stagepassObj.vars.client.viewport.dpr = window.devicePixelRatio || 1;
256
429
  };
257
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
+ }
258
444
  function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
259
445
  document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
260
- el.setAttribute("data-stagepass-processed", "true");
261
- let lp = el.getAttribute(pathAttr);
262
- const ps = el.getAttribute(srcAttr);
263
- if (!ps) return;
264
- if (!lp && ps && swap && dom) {
265
- try {
266
- const urlObj = new URL(ps);
267
- const pathParts = urlObj.pathname.split("/");
268
- lp = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
269
- } catch (e) {
270
- const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
271
- 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
+ }
272
460
  }
273
- }
274
- let url;
275
- if (swap && lp && dom) {
276
- url = `https://${dom}/${lp.startsWith("/") ? lp.substring(1) : lp}?_cb=${cacheBust}`;
277
- } else if (el.getAttribute("data-stagepass-cachebust") === "true") {
278
- url = ps + (ps.includes("?") ? "&" : "?") + "_cb=" + Date.now();
279
- } else {
280
- url = ps;
281
- }
282
- if (!url) return;
283
- const n = document.createElement(type);
284
- if (type === "script") {
285
- n.src = url;
286
- Array.from(el.attributes).forEach((a) => {
287
- const attr = a;
288
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
289
- });
290
- if (!el.hasAttribute("async") && !el.hasAttribute("defer")) n.setAttribute("defer", "");
291
- } else {
292
- n.rel = "stylesheet";
293
- n.href = url;
294
- Array.from(el.attributes).forEach((a) => {
295
- const attr = a;
296
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
297
- });
298
- }
299
- if (el.parentNode) {
300
- el.parentNode.insertBefore(n, el);
301
- el.remove();
302
- } else {
303
- 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 (_) {
304
486
  }
305
487
  });
306
488
  }
307
489
  const process = () => {
308
- swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", ["data-src", "data-stagepass", "data-stagepass-path", "data-stagepass-cachebust"]);
309
- 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
+ }
310
514
  };
311
- process();
312
- if (document.readyState === "loading") {
313
- 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
+ }
314
524
  }
315
525
  function flag() {
316
526
  if (!dev) return;
317
- const f = document.createElement("div");
318
- f.id = "stagepass-flag";
319
- f.textContent = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
320
- 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;';
321
- f.addEventListener("click", () => {
322
- localStorage.removeItem(K);
323
- splog("\u{1F50C} Stagepass disconnected.");
324
- window.location.reload();
325
- });
326
- if (document.body) {
327
- document.body.appendChild(f);
328
- } else {
329
- document.addEventListener("DOMContentLoaded", () => {
330
- 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();
331
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 (_) {
545
+ }
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
+ }
332
561
  }
562
+ process();
563
+ }
564
+ void maybeCheckLnaAndProcess();
565
+ if (document.readyState === "loading") {
566
+ document.addEventListener("DOMContentLoaded", () => {
567
+ void maybeCheckLnaAndProcess();
568
+ });
333
569
  }
334
570
  if (document.readyState === "loading") {
335
571
  document.addEventListener("DOMContentLoaded", flag);
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{(function(){let f="stagepass_domain",S="stagepass",k=e=>e==="debug"||e.endsWith(".sp")||e==="localhost"||e.startsWith("localhost:"),m=new URLSearchParams(window.location.search);function O(){var e;try{let t=(e=new Error().stack)==null?void 0:e.split(`
2
- `);if(!t)return"";let n=/loader(?:\.min)?\.js/i;for(let o=3;o<t.length;o++){let a=t[o].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(a){let c=a[1];if(!n.test(c))return` ${c}:${a[2]}`}}}catch{}return""}function p(e,...t){if(!localStorage.getItem(f))return;let o=new Date().toTimeString().split(" ")[0],l=O(),a=`[\u{1F3AB} ${o}${l?" |"+l:""}]`;e==="error"?console.log(`%c${a}`,"color: red; font-weight: bold;",...t):console[e]?console[e](a,...t):console.log(a,e,...t)}let w=(...e)=>p("log",...e),E=(...e)=>p("warn",...e),L=(...e)=>p("error",...e);window.splog=w,window.spwarn=E,window.sperror=L;function D(...e){let t="log";e.length>0&&(e[0]==="warn"||e[0]==="error")&&(t=e[0],e=e.slice(1)),p(t,...e)}let W=(...e)=>p("warn",...e),j=(...e)=>p("error",...e),A=e=>e?e.replace(/^https?:\/\//,"").replace(/\/$/,""):null,C=!1,i=localStorage.getItem(f);if(m.has(S)){let e=m.get(S);if(e==="off"||e==="0"||e==="false")localStorage.removeItem(f),i=null,w("\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":A(e);n&&k(n)?(localStorage.setItem(f,n),i=n,w(n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`),C=!0):n&&E(`Invalid domain: ${n}. Only .sp domains are allowed.`)}m.delete(S);let t=m.toString();window.history.replaceState({},"",window.location.pathname+(t?`?${t}`:"")+window.location.hash)}i&&!k(i)&&(localStorage.removeItem(f),i=null),i&&!C&&i!=="debug"&&w(`\u{1F50C} Stagepass connected to: ${i}`);let R=!!i,b=!!i&&i!=="debug",v=b?A(i):null,I=b?Date.now():0,V=I,F=I,h=window.location.hostname,N=h==="localhost"||h==="127.0.0.1"||h.startsWith("localhost:")||h.startsWith("127.0.0.1:"),T=b||N,M=T?"local":h.endsWith(".webflow.io")?"staging":"production";!(i&&k(i))&&!m.has(S)&&M==="production"&&(console.log=console.warn=console.error=console.info=console.debug=()=>{});function z(e){let t="unknown",n=null,o=null;return/Edg\/(\d+)/.test(e)?(t="edge",o=e.match(/Edg\/(\d+)/)):/OPR\/(\d+)/.test(e)?(t="opera",o=e.match(/OPR\/(\d+)/)):/Firefox\/(\d+)/.test(e)?(t="firefox",o=e.match(/Firefox\/(\d+)/)):/Chrome\/(\d+)/.test(e)?(t="chrome",o=e.match(/Chrome\/(\d+)/)):/Version\/(\d+).+Safari\//.test(e)&&(t="safari",o=e.match(/Version\/(\d+)/)),o&&o[1]&&(n=Number(o[1])),{family:t,major:Number.isFinite(n)?n:null,userAgent:e}}function B(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 H(e){let t="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,n="desktop";return/iPad|Tablet/i.test(e)?n="tablet":/Mobi|Android.+Mobile|iPhone/i.test(e)?n="mobile":/Android/i.test(e)&&t&&(n="tablet"),{type:n,touch:t}}function U(){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 x(e){try{let t=window[e],n="__stagepass_test__";return t.setItem(n,"1"),t.removeItem(n),!0}catch{return!1}}function q(){let e=navigator.userAgent||"",t=null;try{t=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:U(),browser:z(e),os:B(e),device:H(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:x("localStorage"),sessionStorage:x("sessionStorage")}}}let s=window.stagepass||{},G=q();s.vars=Object.freeze({isLocal:T,env:M,domain:v||h,timestamp:F,version:"1.2.0",client:G}),s.log=D,s.warn=W,s.error=j,s.resolveLocalUrl=e=>{let t=s.vars;if(!t.isLocal||!t.domain)return"";let n=e.startsWith("/")?e.substring(1):e;return n?`https://${t.domain}/${n}?_cb=${t.timestamp}`:""},window.stagepass=s,globalThis.stagepass=s,window.sp=s,globalThis.sp=s;try{if(window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),t=window.matchMedia("(prefers-color-scheme: light)"),n=()=>{var o,l;(l=(o=s.vars)==null?void 0:o.client)!=null&&l.theme&&(e.matches?(s.vars.client.theme.current="dark",s.vars.client.theme.preferred="dark"):t.matches?(s.vars.client.theme.current="light",s.vars.client.theme.preferred="light"):(s.vars.client.theme.current="unknown",s.vars.client.theme.preferred="no-preference"))};typeof e.addEventListener=="function"?(e.addEventListener("change",n),t.addEventListener("change",n)):typeof e.addListener=="function"&&(e.addListener(n),t.addListener(n))}}catch{}let K=()=>{var e,t;(t=(e=s.vars)==null?void 0:e.client)!=null&&t.viewport&&(s.vars.client.viewport.width=window.innerWidth||0,s.vars.client.viewport.height=window.innerHeight||0,s.vars.client.viewport.dpr=window.devicePixelRatio||1)};window.addEventListener("resize",K);function $(e,t,n,o,l){document.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(a=>{a.setAttribute("data-stagepass-processed","true");let c=a.getAttribute(t),d=a.getAttribute(n);if(!d)return;if(!c&&d&&b&&v)try{let r=new URL(d).pathname.split("/");c=r[r.length-1]||r[r.length-2]}catch{let r=d.match(/\/([^\/\?#]+)(?:\?|#|$)/);r&&(c=r[1])}let u;if(b&&c&&v?u=`https://${v}/${c.startsWith("/")?c.substring(1):c}?_cb=${V}`:a.getAttribute("data-stagepass-cachebust")==="true"?u=d+(d.includes("?")?"&":"?")+"_cb="+Date.now():u=d,!u)return;let g=document.createElement(o);o==="script"?(g.src=u,Array.from(a.attributes).forEach(y=>{let r=y;l.includes(r.name)||g.setAttribute(r.name,r.value)}),!a.hasAttribute("async")&&!a.hasAttribute("defer")&&g.setAttribute("defer","")):(g.rel="stylesheet",g.href=u,Array.from(a.attributes).forEach(y=>{let r=y;l.includes(r.name)||g.setAttribute(r.name,r.value)})),a.parentNode?(a.parentNode.insertBefore(g,a),a.remove()):L(`${o} injection failed: No parent node`)})}let P=()=>{$("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path","data-stagepass-cachebust"]),$('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path","data-stagepass-cachebust"])};P(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",P);function _(){if(!R)return;let e=document.createElement("div");e.id="stagepass-flag",e.textContent=i==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",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",()=>{localStorage.removeItem(f),w("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(e):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(e)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",_):_()})();})();
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.2.0",
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
  }