@stagepass/loader 2.2.0 → 2.3.0-beta.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/README.md CHANGED
@@ -37,7 +37,7 @@ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
37
37
  - Session expiry (default **12 h**): `data-stagepass-session-hours` on the loader tag.
38
38
  - Optional legacy global console mute: `data-stagepass-mute-console="true"` (production, no session only).
39
39
  - Dynamically created scripts use `async=false` unless the original had `async`; `defer` is added when neither async nor defer was set (keeps classic order).
40
- - Chrome Local Network Access: best-effort permission query; badge/console hint when state is `prompt` or `denied`.
40
+ - Chrome Local Network Access: best-effort permission query; flag tooltip, warning counter and console hint when state is `prompt` or `denied`.
41
41
 
42
42
  ## Loader tag attributes
43
43
 
@@ -72,16 +72,21 @@ After handling, `?stagepass=` is removed with `history.replaceState` (other quer
72
72
 
73
73
  Storage key: `localStorage.stagepass_domain` → JSON `{ "domain": "…", "expires": <ms> }`. Legacy plain-string values are cleared.
74
74
 
75
- ## Badge
75
+ ## Dev flag
76
76
 
77
77
  Shown only while a session is active (including debug). Click clears the session and reloads.
78
78
 
79
- | State | Text |
79
+ | State | Flag |
80
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` |
81
+ | Active swap | `LOCAL` |
82
+ | Debug | `DEBUG` |
83
+ | Warnings / errors | icons with counters (`99+` above 99) |
84
+
85
+ - Warnings: `sp.warn`, `sp.log('warn', …)`, loader warnings (for example the LNA hint).
86
+ - Errors: `sp.error`, `sp.log('error', …)`, uncaught errors, failed resource loads, unhandled rejections.
87
+ - Tooltip: session domain, counts, LNA hint.
88
+ - Rendered in an open Shadow DOM (`#stagepass-flag`) with DOM APIs only (no `innerHTML`, no `eval`, constructable stylesheet with a `<style>` fallback). Respects `prefers-reduced-motion`.
89
+ - The UI lives in `dist/flag.min.js` (about 1.4 KB gzip) and is fetched only during a session, next to the loader URL (or from jsDelivr at the same version when the loader is served under another file name). Allow that origin in `script-src` if the site uses a strict CSP.
85
90
 
86
91
  ## Runtime API
87
92
 
@@ -0,0 +1,2 @@
1
+ (()=>{var b=':host{all:initial!important;position:fixed!important;top:10px!important;right:10px!important;z-index:2147483647!important;display:block!important}button{all:unset;box-sizing:border-box;display:flex;align-items:center;gap:6px;height:24px;padding:0 9px 0 8px;border-radius:99px;background:linear-gradient(90deg,#FF453A,#FF8A3D);color:#fff;font:700 11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.06em;white-space:nowrap;cursor:pointer;user-select:none;-webkit-user-select:none;box-shadow:0 0 14px 2px rgba(255,138,61,.55),0 0 36px 6px rgba(255,69,58,.28),inset 0 1px 0 rgba(255,255,255,.22)}button:focus-visible{outline:2px solid #fff;outline-offset:2px}i{position:relative;width:9px;height:13px;border-radius:2.5px;background:#fff}i:before,i:after{content:"";position:absolute;left:2px;border-radius:1px}i:before{top:2px;width:5px;height:2px;background:#FF453A;box-shadow:0 0 3px 1px #FF8A3D}i:after{bottom:2px;width:5px;height:1px;background:#121215;opacity:.45;box-shadow:0 -2px #121215}span{display:flex;align-items:center;gap:3px;height:16px;padding:0 5px 0 4px;border-radius:99px;background:rgba(18,18,21,.3)}span:before{content:"";width:9px;height:8px;background:#fff;clip-path:polygon(50% 0,100% 100%,0 100%)}.e:before{width:8px;clip-path:polygon(30% 0,70% 0,100% 30%,100% 70%,70% 100%,30% 100%,0 70%,0 30%)}[hidden]{display:none}@media (prefers-reduced-motion:no-preference){button{animation:a .45s cubic-bezier(.2,.9,.3,1.2)}i:before{animation:b 1s .15s both}}@keyframes a{from{opacity:0;transform:translateY(-30px)}}@keyframes b{0%{opacity:0}60%{opacity:1;transform:scale(1.4)}}';function u(a,c,s,y){let n=document,p=n.createElement("div");p.id="stagepass-flag";let r=p.attachShadow({mode:"open"});try{if(!("adoptedStyleSheets"in r))throw 0;let t=new CSSStyleSheet;t.replaceSync(b),r.adoptedStyleSheets=[t]}catch{let e=r.appendChild(n.createElement("style"));e.textContent=b}let i=(t,e)=>e.appendChild(n.createElement(t)),o=i("button",r);o.type="button",i("i",o),i("b",o).textContent=a;let l=[i("span",o),i("span",o)];l[1].className="e";let x=()=>{let t=s.n,e=["Stagepass "+a+(c?" \xB7 "+c:"")];t[0]&&e.push(t[0]+" warning"+(t[0]>1?"s":"")),t[1]&&e.push(t[1]+" error"+(t[1]>1?"s":"")),s.tip&&e.push(s.tip),e.push("Click to disconnect");let g=e.join(`
2
+ `);o.title=g,o.setAttribute("aria-label",g),l.forEach((h,d)=>{h.hidden=!t[d],h.textContent=t[d]>99?"99+":String(t[d])})};x(),o.addEventListener("click",y);let f=()=>{p.isConnected||(n.body||n.documentElement).appendChild(p)};return n.readyState==="loading"?n.addEventListener("DOMContentLoaded",f):f(),x}var m;try{let a=(m=window.stagepass)==null?void 0:m[Symbol.for("stagepass.flag")];typeof a=="function"&&a(u)}catch{}})();
package/dist/loader.js CHANGED
@@ -138,36 +138,30 @@ var Stagepass = (() => {
138
138
  }
139
139
 
140
140
  // src/client.ts
141
+ var BROWSERS = [
142
+ ["edge", /Edg\/(\d+)/],
143
+ ["opera", /OPR\/(\d+)/],
144
+ ["firefox", /Firefox\/(\d+)/],
145
+ ["chrome", /Chrome\/(\d+)/],
146
+ ["safari", /Version\/(\d+).+Safari\//]
147
+ ];
148
+ var OSES = [
149
+ ["android", /Android/i],
150
+ ["ios", /iPhone|iPad|iPod/i],
151
+ ["macos", /Mac OS X|Macintosh/i],
152
+ ["windows", /Windows NT/i],
153
+ ["linux", /Linux/i]
154
+ ];
141
155
  function getBrowserInfo(ua) {
142
- let family = "unknown";
143
- let major = null;
144
- let m = null;
145
- if (/Edg\/(\d+)/.test(ua)) {
146
- family = "edge";
147
- m = ua.match(/Edg\/(\d+)/);
148
- } else if (/OPR\/(\d+)/.test(ua)) {
149
- family = "opera";
150
- m = ua.match(/OPR\/(\d+)/);
151
- } else if (/Firefox\/(\d+)/.test(ua)) {
152
- family = "firefox";
153
- m = ua.match(/Firefox\/(\d+)/);
154
- } else if (/Chrome\/(\d+)/.test(ua)) {
155
- family = "chrome";
156
- m = ua.match(/Chrome\/(\d+)/);
157
- } else if (/Version\/(\d+).+Safari\//.test(ua)) {
158
- family = "safari";
159
- m = ua.match(/Version\/(\d+)/);
156
+ for (const [family, re] of BROWSERS) {
157
+ const m = ua.match(re);
158
+ if (m) return { family, major: Number(m[1]), userAgent: ua };
160
159
  }
161
- if (m && m[1]) major = Number(m[1]);
162
- return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
160
+ return { family: "unknown", major: null, userAgent: ua };
163
161
  }
164
162
  function getOsInfo(ua) {
165
- if (/Android/i.test(ua)) return { family: "android" };
166
- if (/iPhone|iPad|iPod/i.test(ua)) return { family: "ios" };
167
- if (/Mac OS X|Macintosh/i.test(ua)) return { family: "macos" };
168
- if (/Windows NT/i.test(ua)) return { family: "windows" };
169
- if (/Linux/i.test(ua)) return { family: "linux" };
170
- return { family: "unknown" };
163
+ const hit = OSES.find(([, re]) => re.test(ua));
164
+ return { family: hit ? hit[0] : "unknown" };
171
165
  }
172
166
  function getDeviceInfo(ua) {
173
167
  const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
@@ -178,21 +172,13 @@ var Stagepass = (() => {
178
172
  return { type, touch };
179
173
  }
180
174
  function getThemeInfo() {
181
- let preferred = "no-preference";
182
- let current = "unknown";
175
+ let v = null;
183
176
  try {
184
- if (window.matchMedia) {
185
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
186
- preferred = "dark";
187
- current = "dark";
188
- } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
189
- preferred = "light";
190
- current = "light";
191
- }
192
- }
177
+ const mq = (scheme) => matchMedia(`(prefers-color-scheme: ${scheme})`).matches;
178
+ v = mq("dark") ? "dark" : mq("light") ? "light" : null;
193
179
  } catch (_) {
194
180
  }
195
- return { preferred, current };
181
+ return { preferred: v || "no-preference", current: v || "unknown" };
196
182
  }
197
183
  function hasStorage(type) {
198
184
  try {
@@ -299,100 +285,86 @@ var Stagepass = (() => {
299
285
  (function() {
300
286
  const K = SESSION_KEY;
301
287
  const P = "stagepass";
302
- const PKG_VERSION = true ? "2.2.0" : "0.0.0";
288
+ const W = window;
289
+ const d = document;
290
+ const loc = location;
291
+ const PKG_VERSION = true ? "2.3.0-beta.0" : "0.0.0";
292
+ const LOADER_RE = /loader(?:\.min)?\.js/i;
303
293
  function getLoaderScript() {
304
294
  try {
305
- if (document.currentScript instanceof HTMLScriptElement) {
306
- return document.currentScript;
307
- }
295
+ if (d.currentScript instanceof HTMLScriptElement) return d.currentScript;
308
296
  } catch (_) {
309
297
  }
310
298
  try {
311
- const scripts = document.querySelectorAll('script[src*="loader"]');
299
+ const scripts = d.querySelectorAll('script[src*="loader"]');
312
300
  for (let i = scripts.length - 1; i >= 0; i--) {
313
- const s = scripts[i];
314
- if (/loader(?:\.min)?\.js/i.test(s.src || "")) return s;
301
+ if (LOADER_RE.test(scripts[i].src || "")) return scripts[i];
315
302
  }
316
303
  } catch (_) {
317
304
  }
318
305
  return null;
319
306
  }
320
307
  const loaderScript = getLoaderScript();
321
- const muteConsole = (loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-mute-console")) === "true";
322
- const sessionHours = parseSessionHours(
323
- loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-session-hours")
324
- );
325
- const loaderVersionAttr = loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-version");
326
- const stagingHosts = parseStagingHosts(
327
- loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-staging-hosts")
328
- );
329
- const aliasName = loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-alias");
330
- const p = new URLSearchParams(window.location.search);
308
+ const attr = (name) => loaderScript ? loaderScript.getAttribute("data-stagepass-" + name) : null;
309
+ const muteConsole = attr("mute-console") === "true";
310
+ const sessionHours = parseSessionHours(attr("session-hours"));
311
+ const loaderVersionAttr = attr("version");
312
+ const stagingHosts = parseStagingHosts(attr("staging-hosts"));
313
+ const aliasName = attr("alias");
314
+ const p = new URLSearchParams(loc.search);
331
315
  function getCallerLocation() {
332
- var _a;
333
316
  try {
334
- const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n");
335
- if (!stack) return "";
336
- const loaderPattern = /loader(?:\.min)?\.js/i;
317
+ const stack = (new Error().stack || "").split("\n");
337
318
  for (let i = 3; i < stack.length; i++) {
338
- const line = stack[i];
339
- const match = line.match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);
340
- if (match) {
341
- const file = match[1];
342
- if (!loaderPattern.test(file)) return ` ${file}:${match[2]}`;
343
- }
319
+ const m = stack[i].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);
320
+ if (m && !LOADER_RE.test(m[1])) return ` ${m[1]}:${m[2]}`;
344
321
  }
345
322
  } catch (_) {
346
323
  }
347
324
  return "";
348
325
  }
349
326
  let hasActiveSession = false;
327
+ const flagState = { n: [0, 0], tip: "" };
328
+ let renderFlag = null;
329
+ const bump = (i) => {
330
+ flagState.n[i]++;
331
+ if (renderFlag) renderFlag();
332
+ };
350
333
  function log(level, ...args) {
351
334
  if (!hasActiveSession) return;
335
+ if (level === "warn" || level === "error") bump(level === "warn" ? 0 : 1);
352
336
  try {
353
- const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
354
- const loc = getCallerLocation();
355
- const pre = `[\u{1F3AB} ${t}${loc ? " |" + loc : ""}]`;
356
- if (level === "error") {
357
- console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
358
- } else if (console[level]) {
359
- console[level](pre, ...args);
360
- } else {
361
- console.log(pre, level, ...args);
362
- }
337
+ const where = getCallerLocation();
338
+ const pre = `[\u{1F3AB} ${(/* @__PURE__ */ new Date()).toTimeString().split(" ")[0]}${where ? " |" + where : ""}]`;
339
+ const c = console;
340
+ if (level === "error") c.log(`%c${pre}`, "color:red;font-weight:bold", ...args);
341
+ else if (c[level]) c[level](pre, ...args);
342
+ else c.log(pre, level, ...args);
363
343
  } catch (_) {
364
344
  }
365
345
  }
366
346
  function spLog(...args) {
367
- let level = "log";
368
- if (args.length > 0 && (args[0] === "warn" || args[0] === "error")) {
369
- level = args[0];
370
- args = args.slice(1);
371
- }
347
+ const level = args[0] === "warn" || args[0] === "error" ? args.shift() : "log";
372
348
  log(level, ...args);
373
349
  }
374
350
  const spWarn = (...args) => log("warn", ...args);
375
351
  const spError = (...args) => log("error", ...args);
352
+ const logOnce = (level, msg) => {
353
+ const prev = hasActiveSession;
354
+ hasActiveSession = true;
355
+ log(level, msg);
356
+ hasActiveSession = prev;
357
+ };
376
358
  function readSessionDomain() {
377
359
  try {
378
360
  const raw = localStorage.getItem(K);
379
361
  const record = parseSession(raw);
380
- if (!record) {
381
- if (raw) localStorage.removeItem(K);
382
- return null;
383
- }
384
- return record.domain;
362
+ if (!record && raw) localStorage.removeItem(K);
363
+ return record ? record.domain : null;
385
364
  } catch (_) {
386
365
  return null;
387
366
  }
388
367
  }
389
- function writeSession(domain) {
390
- try {
391
- const record = createSession(domain, sessionHours);
392
- localStorage.setItem(K, serializeSession(record));
393
- } catch (_) {
394
- }
395
- }
396
368
  function clearSession() {
397
369
  try {
398
370
  localStorage.removeItem(K);
@@ -406,34 +378,28 @@ var Stagepass = (() => {
406
378
  if (v === "off" || v === "0" || v === "false") {
407
379
  clearSession();
408
380
  sv = null;
409
- hasActiveSession = true;
410
- log("log", "\u{1F50C} Stagepass disconnected.");
411
- hasActiveSession = false;
381
+ logOnce("log", "\u{1F50C} Stagepass disconnected.");
412
382
  } else if (v) {
413
383
  const c = v === "debug" ? "debug" : cleanDomain(v);
414
384
  if (c && isValidDomain(c)) {
415
- writeSession(c);
385
+ try {
386
+ localStorage.setItem(K, serializeSession(createSession(c, sessionHours)));
387
+ } catch (_) {
388
+ }
416
389
  sv = c;
417
- hasActiveSession = true;
418
- log(
390
+ paramProcessed = true;
391
+ logOnce(
419
392
  "log",
420
393
  c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`
421
394
  );
422
- paramProcessed = true;
423
395
  } else if (c) {
424
- hasActiveSession = true;
425
- spWarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
426
- hasActiveSession = false;
396
+ logOnce("warn", `Invalid domain: ${c}. Only .sp domains are allowed.`);
427
397
  }
428
398
  }
429
399
  try {
430
400
  p.delete(P);
431
401
  const s = p.toString();
432
- window.history.replaceState(
433
- {},
434
- "",
435
- window.location.pathname + (s ? `?${s}` : "") + window.location.hash
436
- );
402
+ history.replaceState({}, "", loc.pathname + (s ? `?${s}` : "") + loc.hash);
437
403
  } catch (_) {
438
404
  }
439
405
  }
@@ -441,17 +407,14 @@ var Stagepass = (() => {
441
407
  clearSession();
442
408
  sv = null;
443
409
  }
444
- hasActiveSession = !!(sv && isValidDomain(sv));
445
- if (sv && !paramProcessed && sv !== "debug" && hasActiveSession) {
446
- log("log", `\u{1F50C} Stagepass connected to: ${sv}`);
447
- }
410
+ const debug = sv === "debug";
411
+ hasActiveSession = !!sv;
412
+ if (sv && !paramProcessed && !debug) log("log", `\u{1F50C} Stagepass connected to: ${sv}`);
448
413
  const dev = !!sv;
449
- const swap = !!sv && sv !== "debug";
414
+ const swap = dev && !debug;
450
415
  const dom = swap ? cleanDomain(sv) : null;
451
416
  const now = swap ? Date.now() : 0;
452
- const cacheBust = now;
453
- const sessionStartTime = now;
454
- const hostname = window.location.hostname;
417
+ const hostname = loc.hostname;
455
418
  const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
456
419
  const isLocal = swap || isLocalhost;
457
420
  const env = isLocal ? "local" : hostname.endsWith(".webflow.io") || stagingHosts.includes(hostname.toLowerCase()) ? "staging" : "production";
@@ -467,173 +430,147 @@ var Stagepass = (() => {
467
430
  theme: /* @__PURE__ */ new Set(),
468
431
  session: /* @__PURE__ */ new Set()
469
432
  };
470
- function emit(event, payload) {
471
- listeners[event].forEach((fn) => {
472
- try {
473
- fn(payload);
474
- } catch (_) {
475
- }
476
- });
477
- }
478
- let clientInfo = getClientInfo();
479
- function ensureClient() {
480
- return clientInfo;
481
- }
482
- try {
483
- if (window.matchMedia) {
484
- const darkMq = window.matchMedia("(prefers-color-scheme: dark)");
485
- const lightMq = window.matchMedia("(prefers-color-scheme: light)");
486
- const updateTheme = () => {
487
- const c = clientInfo;
488
- if (!(c == null ? void 0 : c.theme)) return;
489
- if (darkMq.matches) {
490
- c.theme.current = "dark";
491
- c.theme.preferred = "dark";
492
- } else if (lightMq.matches) {
493
- c.theme.current = "light";
494
- c.theme.preferred = "light";
495
- } else {
496
- c.theme.current = "unknown";
497
- c.theme.preferred = "no-preference";
498
- }
499
- emit("theme", { ...c.theme });
500
- };
501
- if (typeof darkMq.addEventListener === "function") {
502
- darkMq.addEventListener("change", updateTheme);
503
- lightMq.addEventListener("change", updateTheme);
504
- } else if (typeof darkMq.addListener === "function") {
505
- darkMq.addListener(updateTheme);
506
- lightMq.addListener(updateTheme);
507
- }
433
+ const emit = (event, payload) => listeners[event].forEach((fn) => {
434
+ try {
435
+ fn(payload);
436
+ } catch (_) {
508
437
  }
438
+ });
439
+ const clientInfo = getClientInfo();
440
+ try {
441
+ const updateTheme = () => emit("theme", { ...Object.assign(clientInfo.theme, getThemeInfo()) });
442
+ ["dark", "light"].forEach((scheme) => {
443
+ const m = matchMedia(`(prefers-color-scheme: ${scheme})`);
444
+ if (m.addEventListener) m.addEventListener("change", updateTheme);
445
+ else if (m.addListener) m.addListener(updateTheme);
446
+ });
509
447
  } catch (_) {
510
448
  }
511
- const updateViewport = () => {
512
- const c = clientInfo;
513
- if (!(c == null ? void 0 : c.viewport)) return;
514
- c.viewport.width = window.innerWidth || 0;
515
- c.viewport.height = window.innerHeight || 0;
516
- c.viewport.dpr = window.devicePixelRatio || 1;
517
- };
518
- window.addEventListener("resize", updateViewport);
519
- const stagepassObj = window.stagepass || {};
449
+ W.addEventListener("resize", () => {
450
+ const v = clientInfo.viewport;
451
+ v.width = W.innerWidth || 0;
452
+ v.height = W.innerHeight || 0;
453
+ v.dpr = W.devicePixelRatio || 1;
454
+ });
455
+ const stagepassObj = W.stagepass || {};
520
456
  const registry = createModuleRegistry(PKG_VERSION, spWarn);
521
457
  stagepassObj.vars = Object.freeze({
522
458
  isLocal,
523
459
  env,
524
460
  domain: dom || hostname,
525
- timestamp: sessionStartTime,
461
+ timestamp: now,
526
462
  version: PKG_VERSION,
527
463
  client: clientInfo
528
464
  });
529
465
  stagepassObj.log = spLog;
530
466
  stagepassObj.warn = spWarn;
531
467
  stagepassObj.error = spError;
532
- stagepassObj.resolveLocalUrl = (relativePath) => {
533
- const v = stagepassObj.vars;
534
- if (!swap || !dom || !relativePath) return "";
535
- return buildLocalAssetUrl(dom, relativePath, v.timestamp || Date.now());
536
- };
468
+ stagepassObj.resolveLocalUrl = (relativePath) => swap && dom && relativePath ? buildLocalAssetUrl(dom, relativePath, stagepassObj.vars.timestamp || Date.now()) : "";
537
469
  stagepassObj.env = () => detectRuntimeEnv(hostname, dom, stagingHosts);
538
470
  stagepassObj.is = (name) => stagepassObj.env() === name;
539
- stagepassObj.can = (capability) => canCapability(ensureClient(), capability);
540
- stagepassObj.client = (key) => {
541
- const c = ensureClient();
542
- if (key == null || key === "") return c;
543
- return c[key];
544
- };
471
+ stagepassObj.can = (capability) => canCapability(clientInfo, capability);
472
+ stagepassObj.client = (key) => key == null || key === "" ? clientInfo : clientInfo[key];
545
473
  stagepassObj.on = (event, fn) => {
546
- if (event !== "theme" && event !== "session") {
547
- return () => {
548
- };
549
- }
550
474
  const set = listeners[event];
475
+ if (!set || event !== "theme" && event !== "session") return () => {
476
+ };
551
477
  set.add(fn);
552
478
  return () => {
553
479
  set.delete(fn);
554
480
  };
555
481
  };
556
482
  stagepassObj.use = (name, version, factory) => registry.use(name, version, factory, stagepassObj);
557
- window.stagepass = stagepassObj;
558
- globalThis.stagepass = stagepassObj;
559
- window.sp = stagepassObj;
560
- globalThis.sp = stagepassObj;
483
+ W.stagepass = W.sp = stagepassObj;
484
+ globalThis.stagepass = globalThis.sp = stagepassObj;
561
485
  if (aliasName && isValidJsIdentifier(aliasName) && aliasName !== "sp" && aliasName !== "stagepass") {
562
- if (isGlobalFree(window, aliasName)) {
563
- window[aliasName] = stagepassObj;
564
- }
565
- if (isGlobalFree(globalThis, aliasName)) {
566
- globalThis[aliasName] = stagepassObj;
486
+ [W, globalThis].forEach((g) => {
487
+ if (isGlobalFree(g, aliasName)) g[aliasName] = stagepassObj;
488
+ });
489
+ }
490
+ if (dev) {
491
+ try {
492
+ const FLAG = /* @__PURE__ */ Symbol.for("stagepass.flag");
493
+ Object.defineProperty(stagepassObj, FLAG, {
494
+ configurable: true,
495
+ value: (create) => {
496
+ delete stagepassObj[FLAG];
497
+ try {
498
+ renderFlag = create(debug ? "DEBUG" : "LOCAL", dom, flagState, () => {
499
+ clearSession();
500
+ hasActiveSession = true;
501
+ log("log", "\u{1F50C} Stagepass disconnected.");
502
+ emit("session", { active: false, domain: null, swap: false, debug: false });
503
+ loc.reload();
504
+ });
505
+ } catch (_) {
506
+ }
507
+ }
508
+ });
509
+ W.addEventListener("error", () => bump(1), true);
510
+ W.addEventListener("unhandledrejection", () => bump(1));
511
+ const src = loaderScript && loaderScript.src || "";
512
+ const s = d.createElement("script");
513
+ s.src = /\/loader(?:\.min)?\.js$/i.test(src.split(/[?#]/)[0]) ? new URL("flag.min.js", src).href : `https://cdn.jsdelivr.net/npm/@stagepass/loader@${PKG_VERSION}/dist/flag.min.js`;
514
+ s.async = true;
515
+ s.onerror = () => spWarn("Stagepass flag could not be loaded: " + s.src);
516
+ (d.head || d.documentElement).appendChild(s);
517
+ } catch (_) {
567
518
  }
568
519
  }
569
- emit("session", {
570
- active: hasActiveSession,
571
- domain: sv,
572
- swap,
573
- debug: sv === "debug"
574
- });
575
- let lnaState = "unknown";
576
- let lnaHint = null;
520
+ emit("session", { active: hasActiveSession, domain: sv, swap, debug });
577
521
  function resolveAssetUrl(el, productionSrc, localPath) {
578
- if (swap && localPath && dom) {
579
- return buildLocalAssetUrl(dom, localPath, cacheBust);
580
- }
581
- const perAssetVersion = el.getAttribute("data-stagepass-v");
582
- const version = perAssetVersion || loaderVersionAttr;
583
- if (version) {
584
- return appendQueryParam(productionSrc, "v", version);
585
- }
586
- return productionSrc;
522
+ if (swap && localPath && dom) return buildLocalAssetUrl(dom, localPath, now);
523
+ const version = el.getAttribute("data-stagepass-v") || loaderVersionAttr;
524
+ return version ? appendQueryParam(productionSrc, "v", version) : productionSrc;
587
525
  }
588
526
  function extractLocalFilename(ps) {
589
527
  try {
590
- const urlObj = new URL(ps);
591
- const pathParts = urlObj.pathname.split("/");
592
- return pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2] || null;
528
+ const parts = new URL(ps).pathname.split("/");
529
+ return parts[parts.length - 1] || parts[parts.length - 2] || null;
593
530
  } catch (e) {
594
- const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
595
- return match ? match[1] : null;
596
- }
597
- }
598
- function swapEl(sel, pathAttr, srcAttr, type, skipAttrs, seenLocalNames) {
599
- document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
531
+ const m = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
532
+ return m ? m[1] : null;
533
+ }
534
+ }
535
+ const SKIP = [
536
+ "data-stagepass",
537
+ "data-stagepass-path",
538
+ "data-stagepass-cachebust",
539
+ "data-stagepass-v"
540
+ ];
541
+ function swapEl(sel, srcAttr, type, seen) {
542
+ d.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
600
543
  try {
601
544
  el.setAttribute("data-stagepass-processed", "true");
602
- let lp = el.getAttribute(pathAttr);
545
+ let lp = el.getAttribute("data-stagepass-path");
603
546
  const hadExplicitPath = !!lp;
604
547
  const ps = el.getAttribute(srcAttr);
605
548
  if (!ps) return;
606
- if (!lp && ps && swap && dom) {
607
- lp = extractLocalFilename(ps);
608
- }
549
+ if (!lp && swap && dom) lp = extractLocalFilename(ps);
609
550
  if (swap && lp && !hadExplicitPath && hasActiveSession) {
610
- const key = lp;
611
- const count = (seenLocalNames.get(key) || 0) + 1;
612
- seenLocalNames.set(key, count);
551
+ const count = (seen.get(lp) || 0) + 1;
552
+ seen.set(lp, count);
613
553
  if (count === 2) {
614
554
  spWarn(
615
- `Multiple assets resolve to local file "${key}" without data-stagepass-path. Set unique paths to avoid collisions.`
555
+ `Multiple assets resolve to local file "${lp}" without data-stagepass-path. Set unique paths to avoid collisions.`
616
556
  );
617
557
  }
618
558
  }
619
559
  const url = resolveAssetUrl(el, ps, lp);
620
560
  if (!url) return;
621
- const n = document.createElement(type);
622
- if (type === "script") {
623
- n.src = url;
624
- Array.from(el.attributes).forEach((a) => {
625
- const attr = a;
626
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
627
- });
628
- applyScriptLoadOrder(n, el);
629
- } else {
561
+ const n = d.createElement(type);
562
+ const isScript = type === "script";
563
+ if (isScript) n.src = url;
564
+ else {
630
565
  n.rel = "stylesheet";
631
566
  n.href = url;
632
- Array.from(el.attributes).forEach((a) => {
633
- const attr = a;
634
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
635
- });
636
567
  }
568
+ for (const a of Array.from(el.attributes)) {
569
+ if (a.name !== srcAttr && !SKIP.includes(a.name) && (isScript || a.name !== "href")) {
570
+ n.setAttribute(a.name, a.value);
571
+ }
572
+ }
573
+ if (isScript) applyScriptLoadOrder(n, el);
637
574
  if (el.parentNode) {
638
575
  el.parentNode.insertBefore(n, el);
639
576
  el.remove();
@@ -646,99 +583,25 @@ var Stagepass = (() => {
646
583
  }
647
584
  const process = () => {
648
585
  try {
649
- const seenLocalNames = /* @__PURE__ */ new Map();
650
- swapEl(
651
- "script[data-stagepass]",
652
- "data-stagepass-path",
653
- "data-src",
654
- "script",
655
- [
656
- "data-src",
657
- "data-stagepass",
658
- "data-stagepass-path",
659
- "data-stagepass-cachebust",
660
- "data-stagepass-v"
661
- ],
662
- seenLocalNames
663
- );
664
- swapEl(
665
- 'link[rel="stylesheet"][data-stagepass]',
666
- "data-stagepass-path",
667
- "data-href",
668
- "link",
669
- [
670
- "href",
671
- "data-href",
672
- "data-stagepass",
673
- "data-stagepass-path",
674
- "data-stagepass-cachebust",
675
- "data-stagepass-v"
676
- ],
677
- seenLocalNames
678
- );
586
+ const seen = /* @__PURE__ */ new Map();
587
+ swapEl("script[data-stagepass]", "data-src", "script", seen);
588
+ swapEl('link[rel="stylesheet"][data-stagepass]', "data-href", "link", seen);
679
589
  } catch (_) {
680
590
  }
681
591
  };
682
- function updateFlagText(flag2) {
683
- let text = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
684
- if (lnaHint) {
685
- text = sv === "debug" ? "STAGEPASS DEBUG \xB7 LNA" : "STAGEPASS \xB7 ALLOW LOCAL NETWORK";
686
- }
687
- flag2.textContent = text;
688
- if (lnaHint) {
689
- flag2.title = lnaHint;
690
- }
691
- }
692
- function flag() {
693
- if (!dev) return;
694
- try {
695
- const f = document.createElement("div");
696
- f.id = "stagepass-flag";
697
- updateFlagText(f);
698
- 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;';
699
- f.addEventListener("click", () => {
700
- clearSession();
701
- hasActiveSession = true;
702
- log("log", "\u{1F50C} Stagepass disconnected.");
703
- emit("session", { active: false, domain: null, swap: false, debug: false });
704
- window.location.reload();
705
- });
706
- const mount = () => {
707
- if (document.body) document.body.appendChild(f);
708
- };
709
- if (document.body) mount();
710
- else document.addEventListener("DOMContentLoaded", mount);
711
- stagepassObj.__flagEl = f;
712
- } catch (_) {
713
- }
714
- }
715
- async function maybeCheckLnaAndProcess() {
716
- if (swap) {
717
- try {
718
- lnaState = await queryLoopbackPermission();
719
- lnaHint = lnaHintMessage(lnaState);
720
- if (lnaHint) {
721
- spWarn(lnaHint);
722
- const flagEl = stagepassObj.__flagEl;
723
- if (flagEl) updateFlagText(flagEl);
724
- }
725
- } catch (_) {
726
- lnaState = "unknown";
727
- lnaHint = null;
728
- }
729
- }
730
- process();
731
- }
732
- void maybeCheckLnaAndProcess();
733
- if (document.readyState === "loading") {
734
- document.addEventListener("DOMContentLoaded", () => {
735
- void maybeCheckLnaAndProcess();
736
- });
737
- }
738
- if (document.readyState === "loading") {
739
- document.addEventListener("DOMContentLoaded", flag);
740
- } else {
741
- flag();
742
- }
592
+ let lnaCheck = null;
593
+ const checkLna = () => lnaCheck = lnaCheck || (swap ? queryLoopbackPermission().then((state) => {
594
+ const hint = lnaHintMessage(state);
595
+ if (hint) {
596
+ flagState.tip = hint;
597
+ spWarn(hint);
598
+ }
599
+ }).catch(() => {
600
+ }) : Promise.resolve());
601
+ const run = () => {
602
+ void checkLna().then(process);
603
+ };
604
+ run();
605
+ if (d.readyState === "loading") d.addEventListener("DOMContentLoaded", run);
743
606
  })();
744
607
  })();
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{function C(e){if(typeof e!="string"||!e)return!1;if(e==="debug"||e==="localhost")return!0;if(e.startsWith("localhost:")){let n=e.slice(10);return/^[0-9]{1,5}$/.test(n)&&Number(n)<=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(e)}function F(e){return e?e.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var X="stagepass_domain",$=12;function ee(e,n=Date.now()){if(!e||!e.startsWith("{"))return null;try{let o=JSON.parse(e);return typeof o.domain!="string"||typeof o.expires!="number"||!Number.isFinite(o.expires)||!C(o.domain)||o.expires<=n?null:{domain:o.domain,expires:o.expires}}catch{return null}}function te(e,n=$,o=Date.now()){let a=Number.isFinite(n)&&n>0?n:$;return{domain:e,expires:o+a*60*60*1e3}}function ne(e){return JSON.stringify(e)}function se(e){if(e==null||e==="")return $;let n=Number(e);return!Number.isFinite(n)||n<=0?$:n}function oe(e,n,o){if(!e||typeof e!="string")return e;let a=encodeURIComponent(o),i=e.indexOf("#"),p=i>=0?e.slice(i):"",S=i>=0?e.slice(0,i):e,I=S.includes("?")?"&":"?";return`${S}${I}${encodeURIComponent(n)}=${a}${p}`}function j(e,n,o){let a=n.startsWith("/")?n.substring(1):n;return`https://${e}/${a}?_cb=${encodeURIComponent(String(o))}`}async function re(){let e=typeof navigator<"u"?navigator.permissions:void 0;if(!e||typeof e.query!="function")return"unknown";let n=["loopback-network","local-network-access"];for(let o of n)try{let a=await e.query({name:o}),i=a&&a.state;if(i==="granted"||i==="prompt"||i==="denied")return i}catch{}return"unknown"}function ie(e){return e==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":e==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function ae(e,n){let o=n.hasAttribute("async"),a=n.hasAttribute("defer");o?e.async=!0:(e.async=!1,a||(e.defer=!0))}function ce(e){return!e||typeof e!="string"?[]:e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)}function le(e,n,o=[]){if(n&&n.endsWith(".sp"))return"local";let a=(e||"").toLowerCase();return a.endsWith(".webflow.io")||o.some(i=>i===a)?"staging":"production"}function ue(e){return!e||typeof e!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function V(e,n){try{return typeof e[n]>"u"}catch{return!1}}function Me(e){let n="unknown",o=null,a=null;return/Edg\/(\d+)/.test(e)?(n="edge",a=e.match(/Edg\/(\d+)/)):/OPR\/(\d+)/.test(e)?(n="opera",a=e.match(/OPR\/(\d+)/)):/Firefox\/(\d+)/.test(e)?(n="firefox",a=e.match(/Firefox\/(\d+)/)):/Chrome\/(\d+)/.test(e)?(n="chrome",a=e.match(/Chrome\/(\d+)/)):/Version\/(\d+).+Safari\//.test(e)&&(n="safari",a=e.match(/Version\/(\d+)/)),a&&a[1]&&(o=Number(a[1])),{family:n,major:Number.isFinite(o)?o:null,userAgent:e}}function Te(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 Ne(e){let n="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,o="desktop";return/iPad|Tablet/i.test(e)?o="tablet":/Mobi|Android.+Mobile|iPhone/i.test(e)?o="mobile":/Android/i.test(e)&&n&&(o="tablet"),{type:o,touch:n}}function Re(){let e="no-preference",n="unknown";try{window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").matches?(e="dark",n="dark"):window.matchMedia("(prefers-color-scheme: light)").matches&&(e="light",n="light"))}catch{}return{preferred:e,current:n}}function de(e){try{let n=window[e],o="__stagepass_test__";return n.setItem(o,"1"),n.removeItem(o),!0}catch{return!1}}function $e(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function fe(){let e=navigator.userAgent||"",n=null;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:Re(),browser:Me(e),os:Te(e),device:Ne(e),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:n},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:de("localStorage"),sessionStorage:de("sessionStorage")}}}function ge(e,n){let o=e.capabilities;switch(n){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return $e();default:return!1}}function pe(e){if(!e||typeof e!="string")return null;let n=e.trim().match(/^(\d+)/);if(!n)return null;let o=Number(n[1]);return Number.isFinite(o)?o:null}function me(e,n){let o=pe(e),a=new Map;function i(p,S,I,T){if(!p||typeof p!="string")return n("stagepass.use: invalid module name"),!1;let f=pe(S);if(o==null||f==null)return n(`stagepass.use: cannot parse version for module "${p}"`),!1;if(f!==o)return n(`Module "${p}" major ${f} does not match loader major ${o}. Skipping.`),!1;try{return I(T),a.set(p,S),!0}catch(A){return n(`Module "${p}" failed to register:`,A),!1}}return{use:i,registered:a}}(function(){let e=X,n="stagepass",o="2.2.0";function a(){try{if(document.currentScript instanceof HTMLScriptElement)return document.currentScript}catch{}try{let t=document.querySelectorAll('script[src*="loader"]');for(let s=t.length-1;s>=0;s--){let r=t[s];if(/loader(?:\.min)?\.js/i.test(r.src||""))return r}}catch{}return null}let i=a(),p=(i==null?void 0:i.getAttribute("data-stagepass-mute-console"))==="true",S=se(i==null?void 0:i.getAttribute("data-stagepass-session-hours")),I=i==null?void 0:i.getAttribute("data-stagepass-version"),T=ce(i==null?void 0:i.getAttribute("data-stagepass-staging-hosts")),f=i==null?void 0:i.getAttribute("data-stagepass-alias"),A=new URLSearchParams(window.location.search);function he(){var t;try{let s=(t=new Error().stack)==null?void 0:t.split(`
2
- `);if(!s)return"";let r=/loader(?:\.min)?\.js/i;for(let c=3;c<s.length;c++){let _=s[c].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(_){let d=_[1];if(!r.test(d))return` ${d}:${_[2]}`}}}catch{}return""}let g=!1;function y(t,...s){if(g)try{let r=new Date().toTimeString().split(" ")[0],c=he(),m=`[\u{1F3AB} ${r}${c?" |"+c:""}]`;t==="error"?console.log(`%c${m}`,"color: red; font-weight: bold;",...s):console[t]?console[t](m,...s):console.log(m,t,...s)}catch{}}function we(...t){let s="log";t.length>0&&(t[0]==="warn"||t[0]==="error")&&(s=t[0],t=t.slice(1)),y(s,...t)}let M=(...t)=>y("warn",...t),W=(...t)=>y("error",...t);function be(){try{let t=localStorage.getItem(e),s=ee(t);return s?s.domain:(t&&localStorage.removeItem(e),null)}catch{return null}}function Se(t){try{let s=te(t,S);localStorage.setItem(e,ne(s))}catch{}}function O(){try{localStorage.removeItem(e)}catch{}}let z=!1,u=be();if(A.has(n)){let t=A.get(n);if(t==="off"||t==="0"||t==="false")O(),u=null,g=!0,y("log","\u{1F50C} Stagepass disconnected."),g=!1;else if(t){let s=t==="debug"?"debug":F(t);s&&C(s)?(Se(s),u=s,g=!0,y("log",s==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${s}`),z=!0):s&&(g=!0,M(`Invalid domain: ${s}. Only .sp domains are allowed.`),g=!1)}try{A.delete(n);let s=A.toString();window.history.replaceState({},"",window.location.pathname+(s?`?${s}`:"")+window.location.hash)}catch{}}u&&!C(u)&&(O(),u=null),g=!!(u&&C(u)),u&&!z&&u!=="debug"&&g&&y("log",`\u{1F50C} Stagepass connected to: ${u}`);let ye=!!u,w=!!u&&u!=="debug",k=w?F(u):null,U=w?Date.now():0,ke=U,ve=U,b=window.location.hostname,Ee=b==="localhost"||b==="127.0.0.1"||b.startsWith("localhost:")||b.startsWith("127.0.0.1:"),G=w||Ee,q=G?"local":b.endsWith(".webflow.io")||T.includes(b.toLowerCase())?"staging":"production";if(p&&q==="production"&&!g)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let B={theme:new Set,session:new Set};function P(t,s){B[t].forEach(r=>{try{r(s)}catch{}})}let N=fe();function K(){return N}try{if(window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),s=window.matchMedia("(prefers-color-scheme: light)"),r=()=>{let c=N;c!=null&&c.theme&&(t.matches?(c.theme.current="dark",c.theme.preferred="dark"):s.matches?(c.theme.current="light",c.theme.preferred="light"):(c.theme.current="unknown",c.theme.preferred="no-preference"),P("theme",{...c.theme}))};typeof t.addEventListener=="function"?(t.addEventListener("change",r),s.addEventListener("change",r)):typeof t.addListener=="function"&&(t.addListener(r),s.addListener(r))}}catch{}let xe=()=>{let t=N;t!=null&&t.viewport&&(t.viewport.width=window.innerWidth||0,t.viewport.height=window.innerHeight||0,t.viewport.dpr=window.devicePixelRatio||1)};window.addEventListener("resize",xe);let l=window.stagepass||{},Le=me(o,M);l.vars=Object.freeze({isLocal:G,env:q,domain:k||b,timestamp:ve,version:o,client:N}),l.log=we,l.warn=M,l.error=W,l.resolveLocalUrl=t=>{let s=l.vars;return!w||!k||!t?"":j(k,t,s.timestamp||Date.now())},l.env=()=>le(b,k,T),l.is=t=>l.env()===t,l.can=t=>ge(K(),t),l.client=t=>{let s=K();return t==null||t===""?s:s[t]},l.on=(t,s)=>{if(t!=="theme"&&t!=="session")return()=>{};let r=B[t];return r.add(s),()=>{r.delete(s)}},l.use=(t,s,r)=>Le.use(t,s,r,l),window.stagepass=l,globalThis.stagepass=l,window.sp=l,globalThis.sp=l,f&&ue(f)&&f!=="sp"&&f!=="stagepass"&&(V(window,f)&&(window[f]=l),V(globalThis,f)&&(globalThis[f]=l)),P("session",{active:g,domain:u,swap:w,debug:u==="debug"});let H="unknown",v=null;function Ae(t,s,r){if(w&&r&&k)return j(k,r,ke);let m=t.getAttribute("data-stagepass-v")||I;return m?oe(s,"v",m):s}function _e(t){try{let r=new URL(t).pathname.split("/");return r[r.length-1]||r[r.length-2]||null}catch{let r=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return r?r[1]:null}}function J(t,s,r,c,m,_){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(d=>{try{d.setAttribute("data-stagepass-processed","true");let E=d.getAttribute(s),Ie=!!E,R=d.getAttribute(r);if(!R)return;if(!E&&R&&w&&k&&(E=_e(R)),w&&E&&!Ie&&g){let L=E,h=(_.get(L)||0)+1;_.set(L,h),h===2&&M(`Multiple assets resolve to local file "${L}" without data-stagepass-path. Set unique paths to avoid collisions.`)}let D=Ae(d,R,E);if(!D)return;let x=document.createElement(c);c==="script"?(x.src=D,Array.from(d.attributes).forEach(L=>{let h=L;m.includes(h.name)||x.setAttribute(h.name,h.value)}),ae(x,d)):(x.rel="stylesheet",x.href=D,Array.from(d.attributes).forEach(L=>{let h=L;m.includes(h.name)||x.setAttribute(h.name,h.value)})),d.parentNode?(d.parentNode.insertBefore(x,d),d.remove()):W(`${c} injection failed: No parent node`)}catch{}})}let Ce=()=>{try{let t=new Map;J("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"],t),J('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"],t)}catch{}};function Z(t){let s=u==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE";v&&(s=u==="debug"?"STAGEPASS DEBUG \xB7 LNA":"STAGEPASS \xB7 ALLOW LOCAL NETWORK"),t.textContent=s,v&&(t.title=v)}function Q(){if(ye)try{let t=document.createElement("div");t.id="stagepass-flag",Z(t),t.style.cssText='font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;',t.addEventListener("click",()=>{O(),g=!0,y("log","\u{1F50C} Stagepass disconnected."),P("session",{active:!1,domain:null,swap:!1,debug:!1}),window.location.reload()});let s=()=>{document.body&&document.body.appendChild(t)};document.body?s():document.addEventListener("DOMContentLoaded",s),l.__flagEl=t}catch{}}async function Y(){if(w)try{if(H=await re(),v=ie(H),v){M(v);let t=l.__flagEl;t&&Z(t)}}catch{H="unknown",v=null}Ce()}Y(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",()=>{Y()}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Q):Q()})();})();
1
+ var Stagepass=(()=>{function A(t){if(typeof t!="string"||!t)return!1;if(t==="debug"||t==="localhost")return!0;if(t.startsWith("localhost:")){let n=t.slice(10);return/^[0-9]{1,5}$/.test(n)&&Number(n)<=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(t)}function z(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var ne="stagepass_domain",C=12;function se(t,n=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)||!A(o.domain)||o.expires<=n?null:{domain:o.domain,expires:o.expires}}catch{return null}}function oe(t,n=C,o=Date.now()){let i=Number.isFinite(n)&&n>0?n:C;return{domain:t,expires:o+i*60*60*1e3}}function re(t){return JSON.stringify(t)}function ie(t){if(t==null||t==="")return C;let n=Number(t);return!Number.isFinite(n)||n<=0?C:n}function ae(t,n,o){if(!t||typeof t!="string")return t;let i=encodeURIComponent(o),a=t.indexOf("#"),u=a>=0?t.slice(a):"",S=a>=0?t.slice(0,a):t,L=S.includes("?")?"&":"?";return`${S}${L}${encodeURIComponent(n)}=${i}${u}`}function U(t,n,o){let i=n.startsWith("/")?n.substring(1):n;return`https://${t}/${i}?_cb=${encodeURIComponent(String(o))}`}async function ce(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let n=["loopback-network","local-network-access"];for(let o of n)try{let i=await t.query({name:o}),a=i&&i.state;if(a==="granted"||a==="prompt"||a==="denied")return a}catch{}return"unknown"}function le(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 ue(t,n){let o=n.hasAttribute("async"),i=n.hasAttribute("defer");o?t.async=!0:(t.async=!1,i||(t.defer=!0))}function de(t){return!t||typeof t!="string"?[]:t.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)}function pe(t,n,o=[]){if(n&&n.endsWith(".sp"))return"local";let i=(t||"").toLowerCase();return i.endsWith(".webflow.io")||o.some(a=>a===i)?"staging":"production"}function ge(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function fe(t,n){try{return typeof t[n]>"u"}catch{return!1}}var Oe=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],Me=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function Pe(t){for(let[n,o]of Oe){let i=t.match(o);if(i)return{family:n,major:Number(i[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function je(t){let n=Me.find(([,o])=>o.test(t));return{family:n?n[0]:"unknown"}}function Te(t){let n="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)&&n&&(o="tablet"),{type:o,touch:n}}function V(){let t=null;try{let n=o=>matchMedia(`(prefers-color-scheme: ${o})`).matches;t=n("dark")?"dark":n("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function me(t){try{let n=window[t],o="__stagepass_test__";return n.setItem(o,"1"),n.removeItem(o),!0}catch{return!1}}function Fe(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function he(){let t=navigator.userAgent||"",n=null;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:V(),browser:Pe(t),os:je(t),device:Te(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:n},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:me("localStorage"),sessionStorage:me("sessionStorage")}}}function Se(t,n){let o=t.capabilities;switch(n){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return Fe();default:return!1}}function be(t){if(!t||typeof t!="string")return null;let n=t.trim().match(/^(\d+)/);if(!n)return null;let o=Number(n[1]);return Number.isFinite(o)?o:null}function ye(t,n){let o=be(t),i=new Map;function a(u,S,L,v){if(!u||typeof u!="string")return n("stagepass.use: invalid module name"),!1;let g=be(S);if(o==null||g==null)return n(`stagepass.use: cannot parse version for module "${u}"`),!1;if(g!==o)return n(`Module "${u}" major ${g} does not match loader major ${o}. Skipping.`),!1;try{return L(v),i.set(u,S),!0}catch(N){return n(`Module "${u}" failed to register:`,N),!1}}return{use:a,registered:i}}(function(){let t=ne,n="stagepass",o=window,i=document,a=location,u="2.3.0-beta.0",S=/loader(?:\.min)?\.js/i;function L(){try{if(i.currentScript instanceof HTMLScriptElement)return i.currentScript}catch{}try{let e=i.querySelectorAll('script[src*="loader"]');for(let s=e.length-1;s>=0;s--)if(S.test(e[s].src||""))return e[s]}catch{}return null}let v=L(),g=e=>v?v.getAttribute("data-stagepass-"+e):null,N=g("mute-console")==="true",we=ie(g("session-hours")),ve=g("version"),q=de(g("staging-hosts")),k=g("alias"),$=new URLSearchParams(a.search);function ke(){try{let e=(new Error().stack||"").split(`
2
+ `);for(let s=3;s<e.length;s++){let r=e[s].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(r&&!S.test(r[1]))return` ${r[1]}:${r[2]}`}}catch{}return""}let f=!1,O={n:[0,0],tip:""},M=null,P=e=>{O.n[e]++,M&&M()};function E(e,...s){if(f){(e==="warn"||e==="error")&&P(e==="warn"?0:1);try{let r=ke(),p=`[\u{1F3AB} ${new Date().toTimeString().split(" ")[0]}${r?" |"+r:""}]`,l=console;e==="error"?l.log(`%c${p}`,"color:red;font-weight:bold",...s):l[e]?l[e](p,...s):l.log(p,e,...s)}catch{}}}function Ee(...e){let s=e[0]==="warn"||e[0]==="error"?e.shift():"log";E(s,...e)}let I=(...e)=>E("warn",...e),G=(...e)=>E("error",...e),j=(e,s)=>{let r=f;f=!0,E(e,s),f=r};function xe(){try{let e=localStorage.getItem(t),s=se(e);return!s&&e&&localStorage.removeItem(t),s?s.domain:null}catch{return null}}function T(){try{localStorage.removeItem(t)}catch{}}let B=!1,d=xe();if($.has(n)){let e=$.get(n);if(e==="off"||e==="0"||e==="false")T(),d=null,j("log","\u{1F50C} Stagepass disconnected.");else if(e){let s=e==="debug"?"debug":z(e);if(s&&A(s)){try{localStorage.setItem(t,re(oe(s,we)))}catch{}d=s,B=!0,j("log",s==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${s}`)}else s&&j("warn",`Invalid domain: ${s}. Only .sp domains are allowed.`)}try{$.delete(n);let s=$.toString();history.replaceState({},"",a.pathname+(s?`?${s}`:"")+a.hash)}catch{}}d&&!A(d)&&(T(),d=null);let R=d==="debug";f=!!d,d&&!B&&!R&&E("log",`\u{1F50C} Stagepass connected to: ${d}`);let K=!!d,m=K&&!R,b=m?z(d):null,J=m?Date.now():0,y=a.hostname,_e=y==="localhost"||y==="127.0.0.1"||y.startsWith("localhost:")||y.startsWith("127.0.0.1:"),Z=m||_e,Q=Z?"local":y.endsWith(".webflow.io")||q.includes(y.toLowerCase())?"staging":"production";if(N&&Q==="production"&&!f)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let Y={theme:new Set,session:new Set},F=(e,s)=>Y[e].forEach(r=>{try{r(s)}catch{}}),x=he();try{let e=()=>F("theme",{...Object.assign(x.theme,V())});["dark","light"].forEach(s=>{let r=matchMedia(`(prefers-color-scheme: ${s})`);r.addEventListener?r.addEventListener("change",e):r.addListener&&r.addListener(e)})}catch{}o.addEventListener("resize",()=>{let e=x.viewport;e.width=o.innerWidth||0,e.height=o.innerHeight||0,e.dpr=o.devicePixelRatio||1});let c=o.stagepass||{},Le=ye(u,I);if(c.vars=Object.freeze({isLocal:Z,env:Q,domain:b||y,timestamp:J,version:u,client:x}),c.log=Ee,c.warn=I,c.error=G,c.resolveLocalUrl=e=>m&&b&&e?U(b,e,c.vars.timestamp||Date.now()):"",c.env=()=>pe(y,b,q),c.is=e=>c.env()===e,c.can=e=>Se(x,e),c.client=e=>e==null||e===""?x:x[e],c.on=(e,s)=>{let r=Y[e];return!r||e!=="theme"&&e!=="session"?()=>{}:(r.add(s),()=>{r.delete(s)})},c.use=(e,s,r)=>Le.use(e,s,r,c),o.stagepass=o.sp=c,globalThis.stagepass=globalThis.sp=c,k&&ge(k)&&k!=="sp"&&k!=="stagepass"&&[o,globalThis].forEach(e=>{fe(e,k)&&(e[k]=c)}),K)try{let e=Symbol.for("stagepass.flag");Object.defineProperty(c,e,{configurable:!0,value:p=>{delete c[e];try{M=p(R?"DEBUG":"LOCAL",b,O,()=>{T(),f=!0,E("log","\u{1F50C} Stagepass disconnected."),F("session",{active:!1,domain:null,swap:!1,debug:!1}),a.reload()})}catch{}}}),o.addEventListener("error",()=>P(1),!0),o.addEventListener("unhandledrejection",()=>P(1));let s=v&&v.src||"",r=i.createElement("script");r.src=/\/loader(?:\.min)?\.js$/i.test(s.split(/[?#]/)[0])?new URL("flag.min.js",s).href:`https://cdn.jsdelivr.net/npm/@stagepass/loader@${u}/dist/flag.min.js`,r.async=!0,r.onerror=()=>I("Stagepass flag could not be loaded: "+r.src),(i.head||i.documentElement).appendChild(r)}catch{}F("session",{active:f,domain:d,swap:m,debug:R});function Ie(e,s,r){if(m&&r&&b)return U(b,r,J);let p=e.getAttribute("data-stagepass-v")||ve;return p?ae(s,"v",p):s}function Ae(e){try{let s=new URL(e).pathname.split("/");return s[s.length-1]||s[s.length-2]||null}catch{let r=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return r?r[1]:null}}let $e=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"];function X(e,s,r,p){i.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(l=>{try{l.setAttribute("data-stagepass-processed","true");let h=l.getAttribute("data-stagepass-path"),Ne=!!h,D=l.getAttribute(s);if(!D)return;if(!h&&m&&b&&(h=Ae(D)),m&&h&&!Ne&&f){let w=(p.get(h)||0)+1;p.set(h,w),w===2&&I(`Multiple assets resolve to local file "${h}" without data-stagepass-path. Set unique paths to avoid collisions.`)}let W=Ie(l,D,h);if(!W)return;let _=i.createElement(r),H=r==="script";H?_.src=W:(_.rel="stylesheet",_.href=W);for(let w of Array.from(l.attributes))w.name!==s&&!$e.includes(w.name)&&(H||w.name!=="href")&&_.setAttribute(w.name,w.value);H&&ue(_,l),l.parentNode?(l.parentNode.insertBefore(_,l),l.remove()):G(`${r} injection failed: No parent node`)}catch{}})}let Re=()=>{try{let e=new Map;X("script[data-stagepass]","data-src","script",e),X('link[rel="stylesheet"][data-stagepass]',"data-href","link",e)}catch{}},ee=null,Ce=()=>ee=ee||(m?ce().then(e=>{let s=le(e);s&&(O.tip=s,I(s))}).catch(()=>{}):Promise.resolve()),te=()=>{Ce().then(Re)};te(),i.readyState==="loading"&&i.addEventListener("DOMContentLoaded",te)})();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "2.2.0",
3
+ "version": "2.3.0-beta.0",
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",