@stagepass/loader 2.4.0 → 2.5.1

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/README.md CHANGED
@@ -12,18 +12,18 @@ npm install @stagepass/loader@2
12
12
 
13
13
  ## CDN Usage
14
14
 
15
- Prefer the major pin `@2` in production on jsDelivr. Stagepass follows strict semver: no breaking changes within v2; breaking changes only in a new major (v3). Exact pins (e.g. `@2.4.0`) are optional for maximum control. jsDelivr may cache `@2` for a while; purge with `https://purge.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js`. See [Version pinning](https://github.com/arobertherz/stagepass/blob/master/docs/loader.md#version-pinning) in the docs.
15
+ Prefer an exact pin on the Stagepass CDN in production. Stagepass follows strict semver: no breaking changes within v2; breaking changes only in a new major (v3). Use the full file path (this host has no `/dist/` segment). See [Version pinning](https://github.com/stagepass-one/os/blob/master/docs/loader.md#version-pinning) in the docs.
16
16
 
17
17
  ```html
18
18
  <script
19
- src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js"
20
- data-stagepass-version="2.4.0"
19
+ src="https://cdn.stagepass.one/loader@2.5.0/loader.min.js"
20
+ data-stagepass-version="2.5.0"
21
21
  ></script>
22
22
  ```
23
23
 
24
- unpkg serves the same paths if you need an alternative CDN. Always embed the full `/dist/loader.min.js` path (not a short package URL that redirects); otherwise session chunks resolve from the wrong folder. Or set `data-stagepass-flag-base`.
24
+ Always embed the full file path; the short form `https://cdn.stagepass.one/loader@2.5.0` serves the same loader bytes, but a script tag at that URL resolves session chunks from the CDN root and they 404. Or set `data-stagepass-flag-base`.
25
25
 
26
- See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
26
+ jsDelivr is the documented alternative: `https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js`. That host may cache `@2` for a while; purge with `https://purge.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js`.
27
27
 
28
28
  ## Known limits (scoped acceptance)
29
29
 
@@ -31,7 +31,9 @@ Acceptance for `live.min.js` / live reload is **scoped localhost only**. It is n
31
31
 
32
32
  A `localhost` / `localhost:<port>` session still reports `sp.env() === 'production'` (unchanged since 2.3.1 / 2.3.3). Only an active `*.sp` swap session is `local`. That is expected behaviour, not a live-reload failure.
33
33
 
34
- This scoped OSS exception does **not** close GitHub issue #8 or mark P1 overall PASS.
34
+ `live.min.js` ships since loader **2.4.0** (lazy-loaded during an active swap session; not in **2.3.3**). `@2` is a major range alias, not the npm `latest` tag; after a publish the CDN can briefly serve the previous 2.x build. Pin an exact version (e.g. `@2.5.0`) when a specific build must load.
35
+
36
+ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
35
37
 
36
38
  ## What it does
37
39
 
@@ -41,6 +43,7 @@ This scoped OSS exception does **not** close GitHub issue #8 or mark P1 overall
41
43
  - Inserts the new element before the original, then removes the original (`data-stagepass-processed` prevents double work).
42
44
  - Local session: cache-bust with a single `?_cb=<timestamp>` per page load.
43
45
  - Production: version bust with `data-stagepass-version` (loader tag) and/or `data-stagepass-v` (per asset) → `?v=<version>` (URL-encoded; existing query/hash preserved).
46
+ - Production, per asset: `data-stagepass-nocache` on a `data-src` / `data-href` asset sets exactly one fresh `?_cb=<timestamp>` on **every** page view, for every visitor (not just during a Stagepass session). An existing `_cb` in that URL is replaced, so there is never a second `_cb`. `?v=` is applied first when present. Order: original query (without `_cb`), then `v`, then `_cb`. Other query parameters and the hash stay preserved.
44
47
  - `data-stagepass-cachebust="true"` is legacy and **does not** timestamp every production view in v2.
45
48
  - Session expiry (default **12 h**): `data-stagepass-session-hours` on the loader tag.
46
49
  - Optional legacy global console mute: `data-stagepass-mute-console="true"` (production, no session only).
@@ -67,6 +70,7 @@ This scoped OSS exception does **not** close GitHub issue #8 or mark P1 overall
67
70
  | `data-src` / `data-href` | Production URL for legacy mode (default). Required unless live-src opt-in uses native `src` / `href`. |
68
71
  | `data-stagepass-path` | Local path under the linked project root (optional). |
69
72
  | `data-stagepass-v` | Per-asset production `?v=<version>` (overrides loader `data-stagepass-version`). |
73
+ | `data-stagepass-nocache` | Available in published loader **2.5.0** (npm `latest`). Requires loader **2.5.0** or later (older loaders ignore the attribute; the asset then loads cached as before). Boolean (present, or `="true"`; `="false"` turns it off). Production only: sets exactly one fresh `?_cb=<timestamp>` on **this asset's** URL on every page view, for every visitor. An existing `_cb` is replaced (never a second one). Combines with `data-stagepass-v` / `data-stagepass-version` as original query (without `_cb`), then `?v=<version>`, then `_cb`. No effect during an active local/dev swap session (local assets already get a per-page-load `_cb` stamp). Not applied to `data-stagepass-live-src="true"` assets, which stay untouched in production by design. |
70
74
  | `data-stagepass-cachebust` | Legacy; ignored for production timestamps in v2. |
71
75
  | `data-stagepass-processed` | Internal; set after processing. |
72
76
 
@@ -82,6 +86,10 @@ After handling, `?stagepass=` is removed with `history.replaceState` (other quer
82
86
 
83
87
  Storage key: `localStorage.stagepass_domain` → JSON `{ "domain": "…", "expires": <ms> }`. Legacy plain-string values are cleared.
84
88
 
89
+ ## Privacy / storage
90
+
91
+ The loader sets no cookies. On each load it reads the `localStorage` key `stagepass_domain` and removes that key only when the value is stale or invalid. It writes `stagepass_domain` only when a preview session is started via `?stagepass=` (`off`, `0`, and `false` remove the key). While a session is active, the flag UI may write `stagepass:expand`, `stagepass:prev`, and `stagepass:flash`. Storage capability is probed lazily, only when `sp.can('localStorage')`, `sp.can('sessionStorage')`, or `sp.vars.client.capabilities.localStorage` / `.sessionStorage` is used.
92
+
85
93
  ## Dev flag
86
94
 
87
95
  Shown only while a session is active (including debug).
@@ -100,19 +108,44 @@ Shown only while a session is active (including debug).
100
108
  - Errors: `sp.error`, `sp.log('error', …)`, `console.error`, uncaught errors (with stack), failed resource loads, unhandled rejections (with stack). Local files report "Local file not found (404)" or "Local server not reachable … Run stagepass doctor". Sanitized errors from other origins show as "Error in a cross-origin script (details only in DevTools console)".
101
109
  - Accessibility: the pill is a button with `aria-expanded`, the card a `role="dialog"`; focus moves into the card and back to the pill; reduced motion makes all changes instant.
102
110
  - Rendered in an open Shadow DOM (`#stagepass-flag`) with DOM APIs only (no `innerHTML`, no `eval`, constructable stylesheet with a `<style>` fallback). No shadows, glow or filters.
103
- - The UI lives in `dist/flag.min.js` (about 3.2 KB gzip) and `dist/flag-card.min.js` (about 4.8 KB gzip, fetched on first expand). The flag chunk also bootstraps `live.min.js` during a swap session. All three are fetched only during a session, from the folder of the loader's script URL under any file name (self-hosted or copied from `node_modules`: keep the three files together). Inlined or bundled: set `data-stagepass-flag-base`; without a script URL and without the option they come from jsDelivr at the same version (debug sessions warn). Allow that origin in `script-src` if the site uses a strict CSP.
111
+ - The UI lives in `dist/flag.min.js` (about 3.2 KB gzip) and `dist/flag-card.min.js` (about 4.8 KB gzip, fetched on first expand). Both are fetched only during a session, from the folder of the loader's script URL under any file name (self-hosted or copied from `node_modules`: keep the flag files together). Inlined or bundled: set `data-stagepass-flag-base`; without a script URL and without the option they come from jsDelivr at the same version (debug sessions warn). Allow that origin in `script-src` if the site uses a strict CSP.
112
+ - Loader **2.4.0** and later: during a swap session the flag chunk also bootstraps `live.min.js` (lazy EventSource client). Published **2.3.3** does not ship that chunk.
104
113
 
105
114
  ## Zero-cost production mode
106
115
 
107
- Opt-in with `data-stagepass-live-src="true"` on the loader tag. Put a normal `src` / `href` (optional `integrity` + `crossorigin`) on `data-stagepass` assets instead of `data-src` / `data-href`. Without a session the browser loads those URLs directly; with a session Stagepass rewrites them to the local `.sp` host before classic scripts run (loader must be a sync script in `<head>` before the assets). Legacy `data-src` / `data-href` stays the default and keeps working. See the root README section “Zero-cost production mode” for migration, SRI, and limitations.
116
+ Opt-in with `data-stagepass-live-src="true"` on the loader tag (loader **2.4.0** and later). Put a normal `src` / `href` (optional `integrity` + `crossorigin`) on `data-stagepass` assets instead of `data-src` / `data-href`. Without a session the browser loads those URLs directly; with a session Stagepass rewrites them to the local `.sp` host before classic scripts run (loader must be a sync script in `<head>` before the assets). Legacy `data-src` / `data-href` stays the default and keeps working. See [Zero-cost production mode](https://github.com/arobertherz/stagepass/blob/master/docs/loader.md#zero-cost-production-mode) for migration, SRI, and limitations.
117
+
118
+ ## Permanent per-asset cache busting
119
+
120
+ `data-stagepass-nocache` is available in published loader **2.5.0** (npm `latest`). It requires loader **2.5.0** or later (older loaders ignore the attribute; the asset then loads cached as before). It is for the rare asset that must be fetched fresh on every page view, for every production visitor, not just during a Stagepass session. Typical case: a script that embeds third-party forms via iframes, where a stale cached copy breaks the embed.
121
+
122
+ ```html
123
+ <script
124
+ data-stagepass
125
+ data-src="https://cdn.example.com/js/forms-embed.js"
126
+ data-stagepass-nocache
127
+ ></script>
128
+ ```
129
+
130
+ - Boolean attribute: present (any value, including empty) or `="true"` turns it on; `="false"` turns it off (same as omitting it).
131
+ - Scoped to exactly that asset. All other `data-stagepass` assets keep the existing version-only cache strategy.
132
+ - Sets exactly one `?_cb=<Date.now()>`, replacing any `_cb` already in the URL (a page-supplied `_cb` does not survive, and a second `_cb` is not appended). Any `?v=<version>` from `data-stagepass-v` / `data-stagepass-version` is applied first, so the order is original query (without `_cb`), then `v`, then `_cb`. Other query parameters and the hash stay preserved.
133
+ - Production only. During an active local/dev swap session the asset resolves to the local `.sp` URL as usual (single `?_cb=<timestamp>` per page load, same as every other swapped file). `data-stagepass-nocache` has no extra effect there.
134
+ - Not applied to `data-stagepass-live-src="true"` assets: that mode is intentionally zero-cost (untouched by the loader in production), so pair an asset that needs permanent busting with the default `data-src` / `data-href` mode instead.
135
+ - `data-stagepass-cachebust` remains legacy and unrelated: it no longer timestamps every production view (see above) and is not a per-asset opt-in.
108
136
 
109
137
  ## Runtime API
110
138
 
111
139
  Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`; both always assigned in 2.x). Optional custom alias via `data-stagepass-alias` when free. Types ship in `global.d.ts` (complete `sp` API with JSDoc and examples, typed `sp.on(...)` events). Add `"@stagepass/loader"` to `compilerOptions.types` (or `/// <reference types="@stagepass/loader" />`). In debug mode, after the flag chunk loads, reading `sp.vars` once hints toward the flat helpers (reads before the chunk has loaded do not hint).
112
140
 
141
+ Two layers (do not conflate):
142
+
143
+ 1. **Endpoint / session choice:** `*.sp` vs `localhost` / `localhost:<port>` vs `debug`.
144
+ 2. **`sp.env()`:** `local` only for an active `*.sp` swap session; a `localhost` / `localhost:<port>` session is `production` (since 2.3.1 / 2.3.3). `sp.vars.isLocal` remains “swap active **or** page on localhost” and is not the same question as `sp.env()`.
145
+
113
146
  ```js
114
- sp.vars.isLocal // boolean: session swap active or page on localhost
115
- sp.vars.env // 'local' | 'staging' | 'production' (localhost counts as local)
147
+ sp.vars.isLocal // boolean: session swap active or page on localhost (≠ sp.env())
148
+ sp.vars.env // 'local' | 'staging' | 'production' (page/host heuristic; not sp.env())
116
149
  sp.vars.domain // active .sp domain, or page hostname when no swap
117
150
  sp.vars.timestamp // session start ms while swapping; otherwise 0
118
151
  sp.vars.version // package version (build-time)
@@ -120,8 +153,9 @@ sp.vars.client // theme / browser / os / device / viewport / locale / capab
120
153
 
121
154
  // Flat helpers (additive)
122
155
  sp.env() // 'local' | 'staging' | 'production'
123
- // local = active swap to a .sp domain
156
+ // local = active swap to a .sp domain only
124
157
  // staging = *.webflow.io or data-stagepass-staging-hosts
158
+ // else production (a localhost session is production)
125
159
  sp.is('staging')
126
160
  sp.can('localStorage') // also: sessionStorage, cookies, serviceWorker
127
161
  sp.client('theme') // or sp.client() for the whole object
package/dist/loader.js CHANGED
@@ -57,13 +57,19 @@ var Stagepass = (() => {
57
57
  const encoded = encodeURIComponent(value);
58
58
  const hashIdx = url.indexOf("#");
59
59
  const hash = hashIdx >= 0 ? url.slice(hashIdx) : "";
60
- const base = hashIdx >= 0 ? url.slice(0, hashIdx) : url;
60
+ let base = hashIdx >= 0 ? url.slice(0, hashIdx) : url;
61
+ if (key === "_cb") {
62
+ base = base.replace(
63
+ /\?.*/,
64
+ (query) => query.replace(/[&?]_cb(=[^&]*)?(?=&|$)/g, "").replace(/^&/, "?")
65
+ );
66
+ }
61
67
  const sep = base.includes("?") ? "&" : "?";
62
68
  return `${base}${sep}${encodeURIComponent(key)}=${encoded}${hash}`;
63
69
  }
64
70
  function buildLocalAssetUrl(domain, relativePath, cacheBust) {
65
- const clean = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
66
- return `https://${domain}/${clean}?_cb=${encodeURIComponent(String(cacheBust))}`;
71
+ const clean = relativePath.startsWith("/") ? relativePath.slice(1) : relativePath;
72
+ return `https://${domain}/${clean}?_cb=${cacheBust}`;
67
73
  }
68
74
 
69
75
  // src/lna.ts
@@ -108,6 +114,11 @@ var Stagepass = (() => {
108
114
  }
109
115
  }
110
116
  }
117
+ var NOCACHE_ATTR = "data-stagepass-nocache";
118
+ function isNoCacheEnabled(el) {
119
+ if (!el.hasAttribute(NOCACHE_ATTR)) return false;
120
+ return el.getAttribute(NOCACHE_ATTR) !== "false";
121
+ }
111
122
 
112
123
  // src/env.ts
113
124
  function parseStagingHosts(value) {
@@ -179,14 +190,16 @@ var Stagepass = (() => {
179
190
  return { preferred: v || "no-preference", current: v || "unknown" };
180
191
  }
181
192
  function hasStorage(type) {
193
+ const cache = hasStorage;
194
+ if (type in cache) return cache[type];
182
195
  try {
183
196
  const storage = window[type];
184
197
  const key = "__stagepass_test__";
185
198
  storage.setItem(key, "1");
186
199
  storage.removeItem(key);
187
- return true;
200
+ return cache[type] = true;
188
201
  } catch (_) {
189
- return false;
202
+ return cache[type] = false;
190
203
  }
191
204
  }
192
205
  function hasServiceWorker() {
@@ -219,8 +232,13 @@ var Stagepass = (() => {
219
232
  },
220
233
  capabilities: {
221
234
  cookiesEnabled: navigator.cookieEnabled === true,
222
- localStorage: hasStorage("localStorage"),
223
- sessionStorage: hasStorage("sessionStorage")
235
+ // First read probes. `can()` hits the same getter, so the result is shared.
236
+ get localStorage() {
237
+ return hasStorage("localStorage");
238
+ },
239
+ get sessionStorage() {
240
+ return hasStorage("sessionStorage");
241
+ }
224
242
  }
225
243
  };
226
244
  }
@@ -286,7 +304,7 @@ var Stagepass = (() => {
286
304
  const W = window;
287
305
  const d = document;
288
306
  const loc = location;
289
- const PKG_VERSION = true ? "2.4.0" : "0.0.0";
307
+ const PKG_VERSION = true ? "2.5.1" : "0.0.0";
290
308
  const LOADER_RE = /loader(?:\.min)?\.js/i;
291
309
  function flagBase(v, file) {
292
310
  if (typeof v !== "string" || !(v = v.trim())) return null;
@@ -630,7 +648,9 @@ var Stagepass = (() => {
630
648
  function resolveAssetUrl(el, productionSrc, localPath) {
631
649
  if (swap && localPath && dom) return buildLocalAssetUrl(dom, localPath, now);
632
650
  const version = el.getAttribute("data-stagepass-v") || loaderVersionAttr;
633
- return version ? appendQueryParam(productionSrc, "v", version) : productionSrc;
651
+ let url = version ? appendQueryParam(productionSrc, "v", version) : productionSrc;
652
+ if (isNoCacheEnabled(el)) url = appendQueryParam(url, "_cb", Date.now());
653
+ return url;
634
654
  }
635
655
  function extractLocalFilename(ps) {
636
656
  try {
@@ -679,7 +699,8 @@ var Stagepass = (() => {
679
699
  "data-stagepass",
680
700
  "data-stagepass-path",
681
701
  "data-stagepass-cachebust",
682
- "data-stagepass-v"
702
+ "data-stagepass-v",
703
+ NOCACHE_ATTR
683
704
  ];
684
705
  const LS = 'script[data-stagepass][src]:not([data-src]):not([data-stagepass-processed]),link[rel="stylesheet" i][data-stagepass][href]:not([data-href]):not([data-stagepass-processed])';
685
706
  const ff = "onbeforescriptexecute" in d;
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{function C(t){return typeof t!="string"||!t?!1:t==="debug"||t==="localhost"?!0:t.startsWith("localhost:")?(t=t.slice(10),/^[1-9]\d{0,4}$/.test(t)&&+t<65536):/^[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(t)}function se(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var Le="stagepass_domain",U=12;function _e(t,r=Date.now()){if(!t||!t.startsWith("{"))return null;try{let o=JSON.parse(t);return typeof o.domain!="string"||typeof o.expires!="number"||!Number.isFinite(o.expires)||!C(o.domain)||o.expires<=r?null:{domain:o.domain,expires:o.expires}}catch{return null}}function Ae(t,r=U,o=Date.now()){let c=Number.isFinite(r)&&r>0?r:U;return{domain:t,expires:o+c*60*60*1e3}}function $e(t){return JSON.stringify(t)}function Ie(t){if(t==null||t==="")return U;let r=Number(t);return!Number.isFinite(r)||r<=0?U:r}function Oe(t,r,o){if(!t||typeof t!="string")return t;let c=encodeURIComponent(o),g=t.indexOf("#"),b=g>=0?t.slice(g):"",E=g>=0?t.slice(0,g):t,$=E.includes("?")?"&":"?";return`${E}${$}${encodeURIComponent(r)}=${c}${b}`}function V(t,r,o){let c=r.startsWith("/")?r.substring(1):r;return`https://${t}/${c}?_cb=${encodeURIComponent(String(o))}`}async function Re(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let r=["loopback-network","local-network-access"];for(let o of r)try{let c=await t.query({name:o}),g=c&&c.state;if(g==="granted"||g==="prompt"||g==="denied")return g}catch{}return"unknown"}function re(t){return t==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":t==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function Ne(t,r){let o=r.hasAttribute("async"),c=r.hasAttribute("defer");o?t.async=!0:(t.async=!1,c||(t.defer=!0))}function Ce(t){return!t||typeof t!="string"?[]:t.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean)}function je(t,r,o=[]){if(r&&r.endsWith(".sp"))return"local";let c=(t||"").toLowerCase();return c.endsWith(".webflow.io")||o.some(g=>g===c)?"staging":"production"}function Fe(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function Te(t,r){try{return typeof t[r]>"u"}catch{return!1}}var tt=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],nt=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function st(t){for(let[r,o]of tt){let c=t.match(o);if(c)return{family:r,major:Number(c[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function rt(t){let r=nt.find(([,o])=>o.test(t));return{family:r?r[0]:"unknown"}}function ot(t){let r="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,o="desktop";return/iPad|Tablet/i.test(t)?o="tablet":/Mobi|Android.+Mobile|iPhone/i.test(t)?o="mobile":/Android/i.test(t)&&r&&(o="tablet"),{type:o,touch:r}}function oe(){let t=null;try{let r=o=>matchMedia(`(prefers-color-scheme: ${o})`).matches;t=r("dark")?"dark":r("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function Me(t){try{let r=window[t],o="__stagepass_test__";return r.setItem(o,"1"),r.removeItem(o),!0}catch{return!1}}function it(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function Pe(){let t=navigator.userAgent||"",r=null;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:oe(),browser:st(t),os:rt(t),device:ot(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:r},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:Me("localStorage"),sessionStorage:Me("sessionStorage")}}}function De(t,r){let o=t.capabilities;switch(r){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return it();default:return!1}}function He(t){if(!t||typeof t!="string")return null;let r=t.trim().match(/^(\d+)/);if(!r)return null;let o=Number(r[1]);return Number.isFinite(o)?o:null}function We(t,r){let o=He(t),c=new Map;function g(b,E,$,q){if(!b||typeof b!="string")return r("stagepass.use: invalid module name"),!1;let x=He(E);if(o==null||x==null)return r(`stagepass.use: cannot parse version for module "${b}"`),!1;if(x!==o)return r(`Module "${b}" major ${x} does not match loader major ${o}. Skipping.`),!1;try{return $(q),c.set(b,E),!0}catch(v){return r(`Module "${b}" failed to register:`,v),!1}}return{use:g,registered:c}}(function(){let t=Le,r="stagepass",o=window,c=document,g=location,b="2.4.0",E=/loader(?:\.min)?\.js/i;function $(e,n){if(typeof e!="string"||!(e=e.trim()))return null;try{let s=new URL(e,c.baseURI);return!/^https?:$/.test(s.protocol)||s.username||s.password?null:(s.search=s.hash="",n?new URL("./",s).href:s.href.replace(/\/?$/,"/"))}catch{return null}}function q(){try{if(c.currentScript instanceof HTMLScriptElement)return c.currentScript}catch{}try{let e=c.querySelectorAll('script[src*="loader"]');for(let n=e.length-1;n>=0;n--)if(E.test(e[n].src||""))return e[n]}catch{}return null}let x=q(),v=e=>x?x.getAttribute("data-stagepass-"+e):null,ze=v("mute-console")==="true",Ue=Ie(v("session-hours")),Ve=v("version"),ie=Ce(v("staging-hosts")),I=v("alias"),ae=v("live-src")==="true",D=new URLSearchParams(g.search),L=!1,_={n:[0,0],m:[],f:[],swapped:0,v:b,vd:C},j=null,ce=()=>j&&j(),le=()=>new Date().toTimeString().slice(0,8),H=e=>(e||"").split(/[?#]/)[0].split("/").pop()||"",W=(e,n)=>e.length>n?e.slice(0,n)+"\u2026":e,ue=(e,n=0)=>{try{if(typeof e=="string")return n?JSON.stringify(e):e;if(e instanceof Error)return e.name+": "+e.message;if(!e||typeof e!="object")return String(e);if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";let s=Array.isArray(e);if(n>2)return s?"[\u2026]":"{\u2026}";let i=Object.keys(e),a=i.slice(0,20).map(l=>(s?"":l+": ")+ue(e[l],n+1));return i.length>20&&a.push("\u2026"),W(s?"["+a.join(", ")+"]":"{"+a.join(", ")+"}",1e3)}catch{return"[unserializable]"}},B=(e,n=0)=>{let s=(e||"").split(`
2
- `);for(let i=n;i<s.length;i++){let a=s[i].match(/([a-z][\w+.-]*:\/\/[^\s()]+?):(\d+):(\d+)/i);if(a&&!E.test(H(a[1])))return[a[1],a[2],a[3]]}return null},h=null,qe=e=>e?h&&!e.indexOf(`https://${h}/`)?"local":"live":"external",O=(e,n,s="",i="",a="",l="",u)=>{_.n[e]++;let d=_.m,m={type:e?"error":"warn",time:le(),src:u||(s?qe(s):""),file:H(s),url:s.split(/[?#]/)[0],line:i?String(i):"",col:a?String(a):"",text:W(n,500),stack:W(l,2e3),c:1},S=f=>f.type+f.text+f.url+f.line+f.col;for(let f=d.length-1;f>=0;f--)if(S(d[f])===S(m)){m.c=d[f].c+1,d.splice(f,1);break}d.push(m),d.length>50&&d.shift(),ce()},G=(e,n,s,i)=>{let a=s.find(d=>d instanceof Error),l=a&&a.stack||"",u=B(l)||i;O(e,n+s.map(d=>ue(d)).join(" "),u?u[0]:"",u?u[1]:"",u?u[2]:"",l)},F=!1,Be=e=>{F=!0;try{e()}catch{}F=!1};function R(e,...n){if(!L)return;let s=B(new Error().stack||"",3);(e==="warn"||e==="error")&&G(e==="warn"?0:1,"",n,s),Be(()=>{let i=`[\u{1F3AB} ${le()}${s?" | "+H(s[0])+":"+s[1]:""}]`,a=console;e==="error"?a.log(`%c${i}`,"color:red;font-weight:bold",...n):a[e]?a[e](i,...n):a.log(i,e,...n)})}function Ge(...e){let n=e[0]==="warn"||e[0]==="error"?e.shift():"log";R(n,...e)}let T=(...e)=>R("warn",...e),de=(...e)=>R("error",...e),J=(e,n)=>{let s=L;L=!0,R(e,n),L=s};function Je(){try{let e=localStorage.getItem(t),n=_e(e);return!n&&e&&localStorage.removeItem(t),n?n.domain:null}catch{return null}}function K(){try{localStorage.removeItem(t)}catch{}}let fe=!1,y=Je();if(D.has(r)){let e=D.get(r);if(e==="off"||e==="0"||e==="false")K(),y=null,J("log","\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":se(e);if(n&&C(n)){try{localStorage.setItem(t,$e(Ae(n,Ue)))}catch{}y=n,fe=!0,J("log",n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`)}else n&&J("warn",`Invalid domain: ${n}. Only .sp domains are allowed.`)}try{D.delete(r);let n=D.toString();history.replaceState({},"",g.pathname+(n?`?${n}`:"")+g.hash)}catch{}}y&&!C(y)&&(K(),y=null);let M=y==="debug";L=!!y,y&&!fe&&!M&&R("log",`\u{1F50C} Stagepass connected to: ${y}`);let ge=!!y,w=ge&&!M;h=w?se(y):null;let Z=w?Date.now():0,A=g.hostname,Ke=A==="localhost"||A==="127.0.0.1"||A.startsWith("localhost:")||A.startsWith("127.0.0.1:"),pe=w||Ke,me=pe?"local":A.endsWith(".webflow.io")||ie.includes(A.toLowerCase())?"staging":"production";if(ze&&me==="production"&&!L)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let he={theme:new Set,session:new Set},Q=(e,n)=>he[e].forEach(s=>{try{s(n)}catch{}}),N=Pe();try{let e=()=>Q("theme",{...Object.assign(N.theme,oe())});["dark","light"].forEach(n=>{let s=matchMedia(`(prefers-color-scheme: ${n})`);s.addEventListener?s.addEventListener("change",e):s.addListener&&s.addListener(e)})}catch{}o.addEventListener("resize",()=>{let e=N.viewport;e.width=o.innerWidth||0,e.height=o.innerHeight||0,e.dpr=o.devicePixelRatio||1});let p=o.stagepass||{},Ze=We(b,T),be=Object.freeze({isLocal:pe,env:me,domain:h||A,timestamp:Z,version:b,client:N});if(p.vars=be,p.log=Ge,p.warn=T,p.error=de,p.resolveLocalUrl=e=>w&&h&&e?V(h,e,be.timestamp||Date.now()):"",p.env=()=>je(A,h,ie),p.is=e=>p.env()===e,p.can=e=>De(N,e),p.client=e=>e==null||e===""?N:N[e],p.on=(e,n)=>{let s=he[e];return!s||e!=="theme"&&e!=="session"?()=>{}:(s.add(n),()=>{s.delete(n)})},p.use=(e,n,s)=>Ze.use(e,n,s,p),o.stagepass=o.sp=p,globalThis.stagepass=globalThis.sp=p,I&&Fe(I)&&I!=="sp"&&I!=="stagepass"&&[o,globalThis].forEach(e=>{Te(e,I)&&(e[I]=p)}),ge)try{let e=Symbol.for("stagepass.flag.v2"),n=v("flag-base")??o.stagepassFlagBase,s=$(n,!1);n!=null&&!s&&T("Ignored flag base (http(s) or relative only): "+W(String(n),99)),s=s||$(x&&x.src||"",!0),s||(s=`https://cdn.jsdelivr.net/npm/@stagepass/loader@${b}/dist/`,M&&T("Loader URL unknown, flag loads from "+s+". Set data-stagepass-flag-base")),Object.assign(_,{debug:M,domain:h,card:s+"flag-card.min.js",end:()=>{K(),L=!0,R("log","\u{1F50C} Stagepass disconnected."),Q("session",{active:!1,domain:null,swap:!1,debug:!1}),g.reload()}}),Object.defineProperty(p,e,{configurable:!0,value:l=>{delete p[e];try{j=l(_)}catch{}}}),o.addEventListener("error",l=>{let u=l.target,d=u&&u!==o&&(u.src||u.href);typeof d=="string"?Se.has(u)||O(1,"Failed to load "+d.split(/[?#]/)[0],d):/^Script error\.?$/.test(l.message||"")&&!l.filename?O(1,"Error in a cross-origin script (details only in DevTools console)","","","","","external"):O(1,l.message||"Script error",l.filename||"",l.lineno,l.colno,l.error&&l.error.stack||"")},!0),o.addEventListener("unhandledrejection",l=>G(1,"Unhandled rejection: ",[l.reason],null));let i=console;["warn","error"].forEach((l,u)=>{let d=i[l];typeof d=="function"&&(i[l]=function(...m){if(!F){F=!0;try{G(u,"",m,B(new Error().stack||"",2))}catch{}F=!1}return d.apply(this,m)})});let a=c.createElement("script");a.src=s+"flag.min.js",a.async=!0,a.onerror=()=>T("Stagepass flag could not be loaded: "+a.src),(c.head||c.documentElement).appendChild(a)}catch{}Q("session",{active:L,domain:y,swap:w,debug:M});function Qe(e,n,s){if(w&&s&&h)return V(h,s,Z);let i=e.getAttribute("data-stagepass-v")||Ve;return i?Oe(n,"v",i):n}function ye(e){try{let n=new URL(e).pathname.split("/");return n[n.length-1]||n[n.length-2]||null}catch{let s=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return s?s[1]:null}}let Se=new WeakSet,Y="";function we(e,n,s,i,a,l){let u={live:n,local:s,type:i?"js":"css",st:""};l&&(u.x=!0);let d=H(s);Se.add(e),_.f.push(u),e.addEventListener("load",()=>{u.st="ok",_.swapped++,ce()}),e.addEventListener("error",()=>{let m=(f,ne,z)=>{u.st=f,O(ne,z,s)},S=o.fetch;if(typeof S!="function")return m("failed",1,`Failed to load ${d}`);S(s,{method:"HEAD",cache:"no-store"}).then(f=>m(f.ok?"failed":String(f.status),1,f.ok?`Failed to load ${d}`:`Local file not found (${f.status}): ${d}`),()=>S(s,{method:"HEAD",mode:"no-cors",cache:"no-store"}).then(()=>{if(!a)return m("failed",1,`Failed to load ${d}`);_.f.splice(_.f.indexOf(u),1),e.replaceWith(a(!1)),O(0,`Local server sends no CORS header for ${d}. Loaded without crossorigin, error details are limited`,s)},()=>m("failed",1,`Local server not reachable: ${d}. Run stagepass doctor`+(re(Y)?". "+re(Y):""))))})}let Ye=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"],X='script[data-stagepass][src]:not([data-src]):not([data-stagepass-processed]),link[rel="stylesheet" i][data-stagepass][href]:not([data-href]):not([data-stagepass-processed])',ve="onbeforescriptexecute"in c;function ke(e){try{let n=e.tagName==="SCRIPT";if(n&&(ve||c.currentScript===e))return;let s=n?"src":"href",i=e.getAttribute(s);if(!i)return;e.setAttribute("data-stagepass-processed","true");let a=e.getAttribute("data-stagepass-path"),l=a||ye(i);if(!l)return;let u=V(h,l,Z);e.removeAttribute("integrity"),e.hasAttribute("crossorigin")||e.setAttribute("crossorigin","anonymous"),e[s]=u,we(e,i,u,n,null,!!a)}catch{}}let ee=e=>{try{e.matches&&e.matches(X)&&ke(e),e.querySelectorAll(X).forEach(ke)}catch{}};function te(e,n,s){c.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(i=>{try{let a=i.getAttribute("data-stagepass-path"),l=!!a,u=i.getAttribute(n);if(!u)return;i.setAttribute("data-stagepass-processed","true"),!a&&w&&h&&(a=ye(u));let d=Qe(i,u,a);if(!d)return;let m=w&&a&&h,S=s==="script",f=z=>{let k=c.createElement(s);z&&(k.crossOrigin="anonymous"),S?k.src=d:(k.rel="stylesheet",k.href=d);for(let P of Array.from(i.attributes))P.name!==n&&!Ye.includes(P.name)&&P.name!==(S?"src":"href")&&k.setAttribute(P.name,P.value);return m&&k.removeAttribute("integrity"),S&&Ne(k,i),m&&we(k,u,d,S,z?f:null,l),k},ne=f(!!m&&!i.hasAttribute("crossorigin"));i.parentNode?(i.parentNode.insertBefore(ne,i),i.remove()):de(`${s} injection failed: No parent node`)}catch{}})}if(w&&ae)try{new MutationObserver(e=>{for(let n of e)for(let s of n.addedNodes)s.nodeType===1&&ee(s)}).observe(c.documentElement,{childList:!0,subtree:!0}),ve&&c.addEventListener("beforescriptexecute",e=>{let n=e.target;if(!n||!n.matches||!n.matches(X))return;let s=n.getAttribute("src");!s||s.indexOf("https://"+h+"/")===0||(e.preventDefault(),n.setAttribute("data-src",s),n.removeAttribute("src"),te("script[data-stagepass]","data-src","script"))},!0),ee(c)}catch{}let Xe=()=>{try{te("script[data-stagepass]","data-src","script"),te('link[rel="stylesheet"][data-stagepass]',"data-href","link"),w&&ae&&ee(c),j&&j()}catch{}},Ee=null,et=()=>Ee=Ee||(w?Re().then(e=>{Y=e}).catch(()=>{}):Promise.resolve()),xe=()=>{et().then(Xe)};xe(),c.readyState==="loading"&&c.addEventListener("DOMContentLoaded",xe)})();})();
1
+ var Stagepass=(()=>{function N(t){return typeof t!="string"||!t?!1:t==="debug"||t==="localhost"?!0:t.startsWith("localhost:")?(t=t.slice(10),/^[1-9]\d{0,4}$/.test(t)&&+t<65536):/^[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(t)}function se(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var $e="stagepass_domain",V=12;function Oe(t,s=Date.now()){if(!t||!t.startsWith("{"))return null;try{let o=JSON.parse(t);return typeof o.domain!="string"||typeof o.expires!="number"||!Number.isFinite(o.expires)||!N(o.domain)||o.expires<=s?null:{domain:o.domain,expires:o.expires}}catch{return null}}function Ce(t,s=V,o=Date.now()){let i=Number.isFinite(s)&&s>0?s:V;return{domain:t,expires:o+i*60*60*1e3}}function Ie(t){return JSON.stringify(t)}function Re(t){if(t==null||t==="")return V;let s=Number(t);return!Number.isFinite(s)||s<=0?V:s}function oe(t,s,o){if(!t||typeof t!="string")return t;let i=encodeURIComponent(o),g=t.indexOf("#"),b=g>=0?t.slice(g):"",v=g>=0?t.slice(0,g):t;s==="_cb"&&(v=v.replace(/\?.*/,j=>j.replace(/[&?]_cb(=[^&]*)?(?=&|$)/g,"").replace(/^&/,"?")));let $=v.includes("?")?"&":"?";return`${v}${$}${encodeURIComponent(s)}=${i}${b}`}function q(t,s,o){let i=s.startsWith("/")?s.slice(1):s;return`https://${t}/${i}?_cb=${o}`}async function Ne(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let s=["loopback-network","local-network-access"];for(let o of s)try{let i=await t.query({name:o}),g=i&&i.state;if(g==="granted"||g==="prompt"||g==="denied")return g}catch{}return"unknown"}function ae(t){return t==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":t==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function je(t,s){let o=s.hasAttribute("async"),i=s.hasAttribute("defer");o?t.async=!0:(t.async=!1,i||(t.defer=!0))}var B="data-stagepass-nocache";function Fe(t){return t.hasAttribute(B)?t.getAttribute(B)!=="false":!1}function Te(t){return!t||typeof t!="string"?[]:t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}function Pe(t,s,o=[]){if(s&&s.endsWith(".sp"))return"local";let i=(t||"").toLowerCase();return i.endsWith(".webflow.io")||o.some(g=>g===i)?"staging":"production"}function Me(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function De(t,s){try{return typeof t[s]>"u"}catch{return!1}}var rt=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],st=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function ot(t){for(let[s,o]of rt){let i=t.match(o);if(i)return{family:s,major:Number(i[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function at(t){let s=st.find(([,o])=>o.test(t));return{family:s?s[0]:"unknown"}}function it(t){let s="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,o="desktop";return/iPad|Tablet/i.test(t)?o="tablet":/Mobi|Android.+Mobile|iPhone/i.test(t)?o="mobile":/Android/i.test(t)&&s&&(o="tablet"),{type:o,touch:s}}function ce(){let t=null;try{let s=o=>matchMedia(`(prefers-color-scheme: ${o})`).matches;t=s("dark")?"dark":s("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function ie(t){let s=ie;if(t in s)return s[t];try{let o=window[t],i="__stagepass_test__";return o.setItem(i,"1"),o.removeItem(i),s[t]=!0}catch{return s[t]=!1}}function ct(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function He(){let t=navigator.userAgent||"",s=null;try{s=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:ce(),browser:ot(t),os:at(t),device:it(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:s},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,get localStorage(){return ie("localStorage")},get sessionStorage(){return ie("sessionStorage")}}}}function We(t,s){let o=t.capabilities;switch(s){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return ct();default:return!1}}function ze(t){if(!t||typeof t!="string")return null;let s=t.trim().match(/^(\d+)/);if(!s)return null;let o=Number(s[1]);return Number.isFinite(o)?o:null}function Ue(t,s){let o=ze(t),i=new Map;function g(b,v,$,j){if(!b||typeof b!="string")return s("stagepass.use: invalid module name"),!1;let x=ze(v);if(o==null||x==null)return s(`stagepass.use: cannot parse version for module "${b}"`),!1;if(x!==o)return s(`Module "${b}" major ${x} does not match loader major ${o}. Skipping.`),!1;try{return $(j),i.set(b,v),!0}catch(k){return s(`Module "${b}" failed to register:`,k),!1}}return{use:g,registered:i}}(function(){let t=$e,s="stagepass",o=window,i=document,g=location,b="2.5.1",v=/loader(?:\.min)?\.js/i;function $(e,n){if(typeof e!="string"||!(e=e.trim()))return null;try{let r=new URL(e,i.baseURI);return!/^https?:$/.test(r.protocol)||r.username||r.password?null:(r.search=r.hash="",n?new URL("./",r).href:r.href.replace(/\/?$/,"/"))}catch{return null}}function j(){try{if(i.currentScript instanceof HTMLScriptElement)return i.currentScript}catch{}try{let e=i.querySelectorAll('script[src*="loader"]');for(let n=e.length-1;n>=0;n--)if(v.test(e[n].src||""))return e[n]}catch{}return null}let x=j(),k=e=>x?x.getAttribute("data-stagepass-"+e):null,Ve=k("mute-console")==="true",qe=Re(k("session-hours")),Be=k("version"),le=Te(k("staging-hosts")),O=k("alias"),ue=k("live-src")==="true",H=new URLSearchParams(g.search),_=!1,A={n:[0,0],m:[],f:[],swapped:0,v:b,vd:N},F=null,fe=()=>F&&F(),de=()=>new Date().toTimeString().slice(0,8),W=e=>(e||"").split(/[?#]/)[0].split("/").pop()||"",z=(e,n)=>e.length>n?e.slice(0,n)+"\u2026":e,ge=(e,n=0)=>{try{if(typeof e=="string")return n?JSON.stringify(e):e;if(e instanceof Error)return e.name+": "+e.message;if(!e||typeof e!="object")return String(e);if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";let r=Array.isArray(e);if(n>2)return r?"[\u2026]":"{\u2026}";let c=Object.keys(e),a=c.slice(0,20).map(l=>(r?"":l+": ")+ge(e[l],n+1));return c.length>20&&a.push("\u2026"),z(r?"["+a.join(", ")+"]":"{"+a.join(", ")+"}",1e3)}catch{return"[unserializable]"}},G=(e,n=0)=>{let r=(e||"").split(`
2
+ `);for(let c=n;c<r.length;c++){let a=r[c].match(/([a-z][\w+.-]*:\/\/[^\s()]+?):(\d+):(\d+)/i);if(a&&!v.test(W(a[1])))return[a[1],a[2],a[3]]}return null},h=null,Ge=e=>e?h&&!e.indexOf(`https://${h}/`)?"local":"live":"external",C=(e,n,r="",c="",a="",l="",u)=>{A.n[e]++;let f=A.m,m={type:e?"error":"warn",time:de(),src:u||(r?Ge(r):""),file:W(r),url:r.split(/[?#]/)[0],line:c?String(c):"",col:a?String(a):"",text:z(n,500),stack:z(l,2e3),c:1},y=d=>d.type+d.text+d.url+d.line+d.col;for(let d=f.length-1;d>=0;d--)if(y(f[d])===y(m)){m.c=f[d].c+1,f.splice(d,1);break}f.push(m),f.length>50&&f.shift(),fe()},J=(e,n,r,c)=>{let a=r.find(f=>f instanceof Error),l=a&&a.stack||"",u=G(l)||c;C(e,n+r.map(f=>ge(f)).join(" "),u?u[0]:"",u?u[1]:"",u?u[2]:"",l)},T=!1,Je=e=>{T=!0;try{e()}catch{}T=!1};function I(e,...n){if(!_)return;let r=G(new Error().stack||"",3);(e==="warn"||e==="error")&&J(e==="warn"?0:1,"",n,r),Je(()=>{let c=`[\u{1F3AB} ${de()}${r?" | "+W(r[0])+":"+r[1]:""}]`,a=console;e==="error"?a.log(`%c${c}`,"color:red;font-weight:bold",...n):a[e]?a[e](c,...n):a.log(c,e,...n)})}function Ke(...e){let n=e[0]==="warn"||e[0]==="error"?e.shift():"log";I(n,...e)}let P=(...e)=>I("warn",...e),pe=(...e)=>I("error",...e),K=(e,n)=>{let r=_;_=!0,I(e,n),_=r};function Ze(){try{let e=localStorage.getItem(t),n=Oe(e);return!n&&e&&localStorage.removeItem(t),n?n.domain:null}catch{return null}}function Z(){try{localStorage.removeItem(t)}catch{}}let me=!1,S=Ze();if(H.has(s)){let e=H.get(s);if(e==="off"||e==="0"||e==="false")Z(),S=null,K("log","\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":se(e);if(n&&N(n)){try{localStorage.setItem(t,Ie(Ce(n,qe)))}catch{}S=n,me=!0,K("log",n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`)}else n&&K("warn",`Invalid domain: ${n}. Only .sp domains are allowed.`)}try{H.delete(s);let n=H.toString();history.replaceState({},"",g.pathname+(n?`?${n}`:"")+g.hash)}catch{}}S&&!N(S)&&(Z(),S=null);let M=S==="debug";_=!!S,S&&!me&&!M&&I("log",`\u{1F50C} Stagepass connected to: ${S}`);let he=!!S,w=he&&!M;h=w?se(S):null;let Q=w?Date.now():0,L=g.hostname,Qe=L==="localhost"||L==="127.0.0.1"||L.startsWith("localhost:")||L.startsWith("127.0.0.1:"),be=w||Qe,Se=be?"local":L.endsWith(".webflow.io")||le.includes(L.toLowerCase())?"staging":"production";if(Ve&&Se==="production"&&!_)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let ye={theme:new Set,session:new Set},Y=(e,n)=>ye[e].forEach(r=>{try{r(n)}catch{}}),R=He();try{let e=()=>Y("theme",{...Object.assign(R.theme,ce())});["dark","light"].forEach(n=>{let r=matchMedia(`(prefers-color-scheme: ${n})`);r.addEventListener?r.addEventListener("change",e):r.addListener&&r.addListener(e)})}catch{}o.addEventListener("resize",()=>{let e=R.viewport;e.width=o.innerWidth||0,e.height=o.innerHeight||0,e.dpr=o.devicePixelRatio||1});let p=o.stagepass||{},Ye=Ue(b,P),we=Object.freeze({isLocal:be,env:Se,domain:h||L,timestamp:Q,version:b,client:R});if(p.vars=we,p.log=Ke,p.warn=P,p.error=pe,p.resolveLocalUrl=e=>w&&h&&e?q(h,e,we.timestamp||Date.now()):"",p.env=()=>Pe(L,h,le),p.is=e=>p.env()===e,p.can=e=>We(R,e),p.client=e=>e==null||e===""?R:R[e],p.on=(e,n)=>{let r=ye[e];return!r||e!=="theme"&&e!=="session"?()=>{}:(r.add(n),()=>{r.delete(n)})},p.use=(e,n,r)=>Ye.use(e,n,r,p),o.stagepass=o.sp=p,globalThis.stagepass=globalThis.sp=p,O&&Me(O)&&O!=="sp"&&O!=="stagepass"&&[o,globalThis].forEach(e=>{De(e,O)&&(e[O]=p)}),he)try{let e=Symbol.for("stagepass.flag.v2"),n=k("flag-base")??o.stagepassFlagBase,r=$(n,!1);n!=null&&!r&&P("Ignored flag base (http(s) or relative only): "+z(String(n),99)),r=r||$(x&&x.src||"",!0),r||(r=`https://cdn.jsdelivr.net/npm/@stagepass/loader@${b}/dist/`,M&&P("Loader URL unknown, flag loads from "+r+". Set data-stagepass-flag-base")),Object.assign(A,{debug:M,domain:h,card:r+"flag-card.min.js",end:()=>{Z(),_=!0,I("log","\u{1F50C} Stagepass disconnected."),Y("session",{active:!1,domain:null,swap:!1,debug:!1}),g.reload()}}),Object.defineProperty(p,e,{configurable:!0,value:l=>{delete p[e];try{F=l(A)}catch{}}}),o.addEventListener("error",l=>{let u=l.target,f=u&&u!==o&&(u.src||u.href);typeof f=="string"?ke.has(u)||C(1,"Failed to load "+f.split(/[?#]/)[0],f):/^Script error\.?$/.test(l.message||"")&&!l.filename?C(1,"Error in a cross-origin script (details only in DevTools console)","","","","","external"):C(1,l.message||"Script error",l.filename||"",l.lineno,l.colno,l.error&&l.error.stack||"")},!0),o.addEventListener("unhandledrejection",l=>J(1,"Unhandled rejection: ",[l.reason],null));let c=console;["warn","error"].forEach((l,u)=>{let f=c[l];typeof f=="function"&&(c[l]=function(...m){if(!T){T=!0;try{J(u,"",m,G(new Error().stack||"",2))}catch{}T=!1}return f.apply(this,m)})});let a=i.createElement("script");a.src=r+"flag.min.js",a.async=!0,a.onerror=()=>P("Stagepass flag could not be loaded: "+a.src),(i.head||i.documentElement).appendChild(a)}catch{}Y("session",{active:_,domain:S,swap:w,debug:M});function Xe(e,n,r){if(w&&r&&h)return q(h,r,Q);let c=e.getAttribute("data-stagepass-v")||Be,a=c?oe(n,"v",c):n;return Fe(e)&&(a=oe(a,"_cb",Date.now())),a}function ve(e){try{let n=new URL(e).pathname.split("/");return n[n.length-1]||n[n.length-2]||null}catch{let r=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return r?r[1]:null}}let ke=new WeakSet,X="";function Ee(e,n,r,c,a,l){let u={live:n,local:r,type:c?"js":"css",st:""};l&&(u.x=!0);let f=W(r);ke.add(e),A.f.push(u),e.addEventListener("load",()=>{u.st="ok",A.swapped++,fe()}),e.addEventListener("error",()=>{let m=(d,re,U)=>{u.st=d,C(re,U,r)},y=o.fetch;if(typeof y!="function")return m("failed",1,`Failed to load ${f}`);y(r,{method:"HEAD",cache:"no-store"}).then(d=>m(d.ok?"failed":String(d.status),1,d.ok?`Failed to load ${f}`:`Local file not found (${d.status}): ${f}`),()=>y(r,{method:"HEAD",mode:"no-cors",cache:"no-store"}).then(()=>{if(!a)return m("failed",1,`Failed to load ${f}`);A.f.splice(A.f.indexOf(u),1),e.replaceWith(a(!1)),C(0,`Local server sends no CORS header for ${f}. Loaded without crossorigin, error details are limited`,r)},()=>m("failed",1,`Local server not reachable: ${f}. Run stagepass doctor`+(ae(X)?". "+ae(X):""))))})}let et=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v",B],ee='script[data-stagepass][src]:not([data-src]):not([data-stagepass-processed]),link[rel="stylesheet" i][data-stagepass][href]:not([data-href]):not([data-stagepass-processed])',xe="onbeforescriptexecute"in i;function _e(e){try{let n=e.tagName==="SCRIPT";if(n&&(xe||i.currentScript===e))return;let r=n?"src":"href",c=e.getAttribute(r);if(!c)return;e.setAttribute("data-stagepass-processed","true");let a=e.getAttribute("data-stagepass-path"),l=a||ve(c);if(!l)return;let u=q(h,l,Q);e.removeAttribute("integrity"),e.hasAttribute("crossorigin")||e.setAttribute("crossorigin","anonymous"),e[r]=u,Ee(e,c,u,n,null,!!a)}catch{}}let te=e=>{try{e.matches&&e.matches(ee)&&_e(e),e.querySelectorAll(ee).forEach(_e)}catch{}};function ne(e,n,r){i.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(c=>{try{let a=c.getAttribute("data-stagepass-path"),l=!!a,u=c.getAttribute(n);if(!u)return;c.setAttribute("data-stagepass-processed","true"),!a&&w&&h&&(a=ve(u));let f=Xe(c,u,a);if(!f)return;let m=w&&a&&h,y=r==="script",d=U=>{let E=i.createElement(r);U&&(E.crossOrigin="anonymous"),y?E.src=f:(E.rel="stylesheet",E.href=f);for(let D of Array.from(c.attributes))D.name!==n&&!et.includes(D.name)&&D.name!==(y?"src":"href")&&E.setAttribute(D.name,D.value);return m&&E.removeAttribute("integrity"),y&&je(E,c),m&&Ee(E,u,f,y,U?d:null,l),E},re=d(!!m&&!c.hasAttribute("crossorigin"));c.parentNode?(c.parentNode.insertBefore(re,c),c.remove()):pe(`${r} injection failed: No parent node`)}catch{}})}if(w&&ue)try{new MutationObserver(e=>{for(let n of e)for(let r of n.addedNodes)r.nodeType===1&&te(r)}).observe(i.documentElement,{childList:!0,subtree:!0}),xe&&i.addEventListener("beforescriptexecute",e=>{let n=e.target;if(!n||!n.matches||!n.matches(ee))return;let r=n.getAttribute("src");!r||r.indexOf("https://"+h+"/")===0||(e.preventDefault(),n.setAttribute("data-src",r),n.removeAttribute("src"),ne("script[data-stagepass]","data-src","script"))},!0),te(i)}catch{}let tt=()=>{try{ne("script[data-stagepass]","data-src","script"),ne('link[rel="stylesheet"][data-stagepass]',"data-href","link"),w&&ue&&te(i),F&&F()}catch{}},Ae=null,nt=()=>Ae=Ae||(w?Ne().then(e=>{X=e}).catch(()=>{}):Promise.resolve()),Le=()=>{nt().then(tt)};Le(),i.readyState==="loading"&&i.addEventListener("DOMContentLoaded",Le)})();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "2.4.0",
3
+ "version": "2.5.1",
4
4
  "description": "Universal loader for Stagepass - injects local files into Webflow projects",
5
5
  "main": "dist/loader.min.js",
6
6
  "types": "global.d.ts",