@stagepass/loader 2.0.0 → 2.2.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
@@ -7,23 +7,21 @@ The loader reads Stagepass session state and swaps tagged production assets with
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- npm install @stagepass/loader@2.0.0
10
+ npm install @stagepass/loader@2
11
11
  ```
12
12
 
13
13
  ## CDN Usage
14
14
 
15
- Pin exact versions in production (jsDelivr preferred; unpkg alternative):
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.2.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 the root README [Version pinning](../../README.md#-version-pinning) section.
16
16
 
17
17
  ```html
18
18
  <script
19
- src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2.0.0/dist/loader.min.js"
20
- data-stagepass-version="2.0.0"
19
+ src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js"
20
+ data-stagepass-version="2.2.0"
21
21
  ></script>
22
22
  ```
23
23
 
24
- ```html
25
- <script src="https://unpkg.com/@stagepass/loader@2.0.0/dist/loader.min.js"></script>
26
- ```
24
+ unpkg serves the same paths if you need an alternative CDN.
27
25
 
28
26
  See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
29
27
 
@@ -48,6 +46,8 @@ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
48
46
  | `data-stagepass-version` | Production default `?v=<version>` for swapped/tagged assets without a per-asset override. |
49
47
  | `data-stagepass-session-hours` | Session lifetime in hours (positive number; default `12`). |
50
48
  | `data-stagepass-mute-console="true"` | Opt-in legacy mute of `console.log/warn/error/info/debug` in production when no session. |
49
+ | `data-stagepass-staging-hosts` | Comma-separated hostnames treated as staging (in addition to `*.webflow.io`). |
50
+ | `data-stagepass-alias` | Optional custom global name (valid JS identifier). Assigned only when that global is free. |
51
51
 
52
52
  ## Asset attributes
53
53
 
@@ -85,28 +85,41 @@ Shown only while a session is active (including debug). Click clears the session
85
85
 
86
86
  ## Runtime API
87
87
 
88
- Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`). Types ship in `global.d.ts`. There are **no** custom DOM events.
88
+ Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`). 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" />`).
89
89
 
90
90
  ```js
91
91
  sp.vars.isLocal // boolean: session swap active or page on localhost
92
- sp.vars.env // 'local' | 'staging' | 'production'
92
+ sp.vars.env // 'local' | 'staging' | 'production' (localhost counts as local)
93
93
  sp.vars.domain // active .sp domain, or page hostname when no swap
94
94
  sp.vars.timestamp // session start ms while swapping; otherwise 0
95
95
  sp.vars.version // package version (build-time)
96
96
  sp.vars.client // theme / browser / os / device / viewport / locale / capabilities
97
97
 
98
+ // Flat helpers (additive)
99
+ sp.env() // 'local' | 'staging' | 'production'
100
+ // local = active swap to a .sp domain
101
+ // staging = *.webflow.io or data-stagepass-staging-hosts
102
+ sp.is('staging')
103
+ sp.can('localStorage') // also: sessionStorage, cookies, serviceWorker
104
+ sp.client('theme') // or sp.client() for the whole object
105
+ const off = sp.on('theme', (t) => { /* prefers-color-scheme change */ })
106
+ off()
107
+ sp.use('my-module', '2.1.0', (api) => { /* register */ })
108
+
98
109
  sp.resolveLocalUrl('js/app.js') // local HTTPS URL while swapping; '' otherwise
99
- sp.log('…') / sp.log('warn', '…') / sp.log('error', '…')
100
- sp.warn('…')
101
- sp.error('…')
110
+ sp.log('...') / sp.log('warn', '...') / sp.log('error', '...')
111
+ sp.warn('...')
112
+ sp.error('...')
102
113
  ```
103
114
 
104
115
  Logging helpers only print while a Stagepass session is active. Deprecated globals `splog` / `spwarn` / `sperror` were removed in v2.
105
116
 
117
+ With an active session (or debug), the loader warns when two tagged assets resolve to the same local filename without `data-stagepass-path`.
118
+
106
119
  ## Related Packages
107
120
 
108
121
  - `@stagepass/cli`: creates and manages `.sp` infrastructure.
109
- - `@stagepass/modules`: optional modules that extend the loader (`inject`, `cookies`).
122
+ - `@stagepass/modules`: optional modules that extend the loader (`inject`, `cookies`, `maintenance`).
110
123
 
111
124
  ## Repository
112
125
 
package/dist/loader.js CHANGED
@@ -111,11 +111,195 @@ var Stagepass = (() => {
111
111
  }
112
112
  }
113
113
 
114
+ // src/env.ts
115
+ function parseStagingHosts(value) {
116
+ if (!value || typeof value !== "string") return [];
117
+ return value.split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
118
+ }
119
+ function detectRuntimeEnv(hostname, swapDomain, stagingHosts = []) {
120
+ if (swapDomain && swapDomain.endsWith(".sp")) return "local";
121
+ const host = (hostname || "").toLowerCase();
122
+ if (host.endsWith(".webflow.io")) return "staging";
123
+ if (stagingHosts.some((h) => h === host)) return "staging";
124
+ return "production";
125
+ }
126
+
127
+ // src/alias.ts
128
+ function isValidJsIdentifier(name) {
129
+ if (!name || typeof name !== "string") return false;
130
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
131
+ }
132
+ function isGlobalFree(target, name) {
133
+ try {
134
+ return typeof target[name] === "undefined";
135
+ } catch (_) {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ // src/client.ts
141
+ 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+)/);
160
+ }
161
+ if (m && m[1]) major = Number(m[1]);
162
+ return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
163
+ }
164
+ 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" };
171
+ }
172
+ function getDeviceInfo(ua) {
173
+ const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
174
+ let type = "desktop";
175
+ if (/iPad|Tablet/i.test(ua)) type = "tablet";
176
+ else if (/Mobi|Android.+Mobile|iPhone/i.test(ua)) type = "mobile";
177
+ else if (/Android/i.test(ua) && touch) type = "tablet";
178
+ return { type, touch };
179
+ }
180
+ function getThemeInfo() {
181
+ let preferred = "no-preference";
182
+ let current = "unknown";
183
+ 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
+ }
193
+ } catch (_) {
194
+ }
195
+ return { preferred, current };
196
+ }
197
+ function hasStorage(type) {
198
+ try {
199
+ const storage = window[type];
200
+ const key = "__stagepass_test__";
201
+ storage.setItem(key, "1");
202
+ storage.removeItem(key);
203
+ return true;
204
+ } catch (_) {
205
+ return false;
206
+ }
207
+ }
208
+ function hasServiceWorker() {
209
+ try {
210
+ return typeof navigator !== "undefined" && "serviceWorker" in navigator;
211
+ } catch (_) {
212
+ return false;
213
+ }
214
+ }
215
+ function getClientInfo() {
216
+ const ua = navigator.userAgent || "";
217
+ let timezone = null;
218
+ try {
219
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
220
+ } catch (_) {
221
+ }
222
+ return {
223
+ theme: getThemeInfo(),
224
+ browser: getBrowserInfo(ua),
225
+ os: getOsInfo(ua),
226
+ device: getDeviceInfo(ua),
227
+ viewport: {
228
+ width: window.innerWidth || 0,
229
+ height: window.innerHeight || 0,
230
+ dpr: window.devicePixelRatio || 1
231
+ },
232
+ locale: {
233
+ language: navigator.language || "unknown",
234
+ timezone
235
+ },
236
+ capabilities: {
237
+ cookiesEnabled: navigator.cookieEnabled === true,
238
+ localStorage: hasStorage("localStorage"),
239
+ sessionStorage: hasStorage("sessionStorage")
240
+ }
241
+ };
242
+ }
243
+ function canCapability(client, capability) {
244
+ const caps = client.capabilities;
245
+ switch (capability) {
246
+ case "localStorage":
247
+ return caps.localStorage === true;
248
+ case "sessionStorage":
249
+ return caps.sessionStorage === true;
250
+ case "cookies":
251
+ return caps.cookiesEnabled === true;
252
+ case "serviceWorker":
253
+ return hasServiceWorker();
254
+ default:
255
+ return false;
256
+ }
257
+ }
258
+
259
+ // src/registry.ts
260
+ function majorFromVersion(version) {
261
+ if (!version || typeof version !== "string") return null;
262
+ const m = version.trim().match(/^(\d+)/);
263
+ if (!m) return null;
264
+ const n = Number(m[1]);
265
+ return Number.isFinite(n) ? n : null;
266
+ }
267
+ function createModuleRegistry(loaderVersion, warn) {
268
+ const loaderMajor = majorFromVersion(loaderVersion);
269
+ const registered = /* @__PURE__ */ new Map();
270
+ function use(name, version, factory, api) {
271
+ if (!name || typeof name !== "string") {
272
+ warn("stagepass.use: invalid module name");
273
+ return false;
274
+ }
275
+ const modMajor = majorFromVersion(version);
276
+ if (loaderMajor == null || modMajor == null) {
277
+ warn(`stagepass.use: cannot parse version for module "${name}"`);
278
+ return false;
279
+ }
280
+ if (modMajor !== loaderMajor) {
281
+ warn(
282
+ `Module "${name}" major ${modMajor} does not match loader major ${loaderMajor}. Skipping.`
283
+ );
284
+ return false;
285
+ }
286
+ try {
287
+ factory(api);
288
+ registered.set(name, version);
289
+ return true;
290
+ } catch (err) {
291
+ warn(`Module "${name}" failed to register:`, err);
292
+ return false;
293
+ }
294
+ }
295
+ return { use, registered };
296
+ }
297
+
114
298
  // src/index.ts
115
299
  (function() {
116
300
  const K = SESSION_KEY;
117
301
  const P = "stagepass";
118
- const PKG_VERSION = true ? "2.0.0" : "0.0.0";
302
+ const PKG_VERSION = true ? "2.2.0" : "0.0.0";
119
303
  function getLoaderScript() {
120
304
  try {
121
305
  if (document.currentScript instanceof HTMLScriptElement) {
@@ -139,6 +323,10 @@ var Stagepass = (() => {
139
323
  loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-session-hours")
140
324
  );
141
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");
142
330
  const p = new URLSearchParams(window.location.search);
143
331
  function getCallerLocation() {
144
332
  var _a;
@@ -266,7 +454,7 @@ var Stagepass = (() => {
266
454
  const hostname = window.location.hostname;
267
455
  const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
268
456
  const isLocal = swap || isLocalhost;
269
- const env = isLocal ? "local" : hostname.endsWith(".webflow.io") ? "staging" : "production";
457
+ const env = isLocal ? "local" : hostname.endsWith(".webflow.io") || stagingHosts.includes(hostname.toLowerCase()) ? "staging" : "production";
270
458
  if (muteConsole && env === "production" && !hasActiveSession) {
271
459
  try {
272
460
  const noop = () => {
@@ -275,103 +463,61 @@ var Stagepass = (() => {
275
463
  } catch (_) {
276
464
  }
277
465
  }
278
- function getBrowserInfo(ua) {
279
- let family = "unknown";
280
- let major = null;
281
- let m = null;
282
- if (/Edg\/(\d+)/.test(ua)) {
283
- family = "edge";
284
- m = ua.match(/Edg\/(\d+)/);
285
- } else if (/OPR\/(\d+)/.test(ua)) {
286
- family = "opera";
287
- m = ua.match(/OPR\/(\d+)/);
288
- } else if (/Firefox\/(\d+)/.test(ua)) {
289
- family = "firefox";
290
- m = ua.match(/Firefox\/(\d+)/);
291
- } else if (/Chrome\/(\d+)/.test(ua)) {
292
- family = "chrome";
293
- m = ua.match(/Chrome\/(\d+)/);
294
- } else if (/Version\/(\d+).+Safari\//.test(ua)) {
295
- family = "safari";
296
- m = ua.match(/Version\/(\d+)/);
297
- }
298
- if (m && m[1]) major = Number(m[1]);
299
- return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
300
- }
301
- function getOsInfo(ua) {
302
- if (/Android/i.test(ua)) return { family: "android" };
303
- if (/iPhone|iPad|iPod/i.test(ua)) return { family: "ios" };
304
- if (/Mac OS X|Macintosh/i.test(ua)) return { family: "macos" };
305
- if (/Windows NT/i.test(ua)) return { family: "windows" };
306
- if (/Linux/i.test(ua)) return { family: "linux" };
307
- return { family: "unknown" };
308
- }
309
- function getDeviceInfo(ua) {
310
- const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
311
- let type = "desktop";
312
- if (/iPad|Tablet/i.test(ua)) type = "tablet";
313
- else if (/Mobi|Android.+Mobile|iPhone/i.test(ua)) type = "mobile";
314
- else if (/Android/i.test(ua) && touch) type = "tablet";
315
- return { type, touch };
316
- }
317
- function getThemeInfo() {
318
- let preferred = "no-preference";
319
- let current = "unknown";
320
- try {
321
- if (window.matchMedia) {
322
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
323
- preferred = "dark";
324
- current = "dark";
325
- } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
326
- preferred = "light";
327
- current = "light";
328
- }
466
+ const listeners = {
467
+ theme: /* @__PURE__ */ new Set(),
468
+ session: /* @__PURE__ */ new Set()
469
+ };
470
+ function emit(event, payload) {
471
+ listeners[event].forEach((fn) => {
472
+ try {
473
+ fn(payload);
474
+ } catch (_) {
329
475
  }
330
- } catch (_) {
331
- }
332
- return { preferred, current };
476
+ });
333
477
  }
334
- function hasStorage(type) {
335
- try {
336
- const storage = window[type];
337
- const key = "__stagepass_test__";
338
- storage.setItem(key, "1");
339
- storage.removeItem(key);
340
- return true;
341
- } catch (_) {
342
- return false;
343
- }
478
+ let clientInfo = getClientInfo();
479
+ function ensureClient() {
480
+ return clientInfo;
344
481
  }
345
- function getClientInfo() {
346
- const ua = navigator.userAgent || "";
347
- let timezone = null;
348
- try {
349
- timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
350
- } catch (_) {
351
- }
352
- return {
353
- theme: getThemeInfo(),
354
- browser: getBrowserInfo(ua),
355
- os: getOsInfo(ua),
356
- device: getDeviceInfo(ua),
357
- viewport: {
358
- width: window.innerWidth || 0,
359
- height: window.innerHeight || 0,
360
- dpr: window.devicePixelRatio || 1
361
- },
362
- locale: {
363
- language: navigator.language || "unknown",
364
- timezone
365
- },
366
- capabilities: {
367
- cookiesEnabled: navigator.cookieEnabled === true,
368
- localStorage: hasStorage("localStorage"),
369
- sessionStorage: hasStorage("sessionStorage")
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);
370
507
  }
371
- };
508
+ }
509
+ } catch (_) {
372
510
  }
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);
373
519
  const stagepassObj = window.stagepass || {};
374
- const clientInfo = getClientInfo();
520
+ const registry = createModuleRegistry(PKG_VERSION, spWarn);
375
521
  stagepassObj.vars = Object.freeze({
376
522
  isLocal,
377
523
  env,
@@ -388,46 +534,44 @@ var Stagepass = (() => {
388
534
  if (!swap || !dom || !relativePath) return "";
389
535
  return buildLocalAssetUrl(dom, relativePath, v.timestamp || Date.now());
390
536
  };
537
+ stagepassObj.env = () => detectRuntimeEnv(hostname, dom, stagingHosts);
538
+ 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
+ };
545
+ stagepassObj.on = (event, fn) => {
546
+ if (event !== "theme" && event !== "session") {
547
+ return () => {
548
+ };
549
+ }
550
+ const set = listeners[event];
551
+ set.add(fn);
552
+ return () => {
553
+ set.delete(fn);
554
+ };
555
+ };
556
+ stagepassObj.use = (name, version, factory) => registry.use(name, version, factory, stagepassObj);
391
557
  window.stagepass = stagepassObj;
392
558
  globalThis.stagepass = stagepassObj;
393
559
  window.sp = stagepassObj;
394
560
  globalThis.sp = stagepassObj;
395
- try {
396
- if (window.matchMedia) {
397
- const darkMq = window.matchMedia("(prefers-color-scheme: dark)");
398
- const lightMq = window.matchMedia("(prefers-color-scheme: light)");
399
- const updateTheme = () => {
400
- var _a, _b;
401
- if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.theme)) return;
402
- if (darkMq.matches) {
403
- stagepassObj.vars.client.theme.current = "dark";
404
- stagepassObj.vars.client.theme.preferred = "dark";
405
- } else if (lightMq.matches) {
406
- stagepassObj.vars.client.theme.current = "light";
407
- stagepassObj.vars.client.theme.preferred = "light";
408
- } else {
409
- stagepassObj.vars.client.theme.current = "unknown";
410
- stagepassObj.vars.client.theme.preferred = "no-preference";
411
- }
412
- };
413
- if (typeof darkMq.addEventListener === "function") {
414
- darkMq.addEventListener("change", updateTheme);
415
- lightMq.addEventListener("change", updateTheme);
416
- } else if (typeof darkMq.addListener === "function") {
417
- darkMq.addListener(updateTheme);
418
- lightMq.addListener(updateTheme);
419
- }
561
+ 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;
420
567
  }
421
- } catch (_) {
422
568
  }
423
- const updateViewport = () => {
424
- var _a, _b;
425
- if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.viewport)) return;
426
- stagepassObj.vars.client.viewport.width = window.innerWidth || 0;
427
- stagepassObj.vars.client.viewport.height = window.innerHeight || 0;
428
- stagepassObj.vars.client.viewport.dpr = window.devicePixelRatio || 1;
429
- };
430
- window.addEventListener("resize", updateViewport);
569
+ emit("session", {
570
+ active: hasActiveSession,
571
+ domain: sv,
572
+ swap,
573
+ debug: sv === "debug"
574
+ });
431
575
  let lnaState = "unknown";
432
576
  let lnaHint = null;
433
577
  function resolveAssetUrl(el, productionSrc, localPath) {
@@ -441,21 +585,35 @@ var Stagepass = (() => {
441
585
  }
442
586
  return productionSrc;
443
587
  }
444
- function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
588
+ function extractLocalFilename(ps) {
589
+ try {
590
+ const urlObj = new URL(ps);
591
+ const pathParts = urlObj.pathname.split("/");
592
+ return pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2] || null;
593
+ } catch (e) {
594
+ const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
595
+ return match ? match[1] : null;
596
+ }
597
+ }
598
+ function swapEl(sel, pathAttr, srcAttr, type, skipAttrs, seenLocalNames) {
445
599
  document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
446
600
  try {
447
601
  el.setAttribute("data-stagepass-processed", "true");
448
602
  let lp = el.getAttribute(pathAttr);
603
+ const hadExplicitPath = !!lp;
449
604
  const ps = el.getAttribute(srcAttr);
450
605
  if (!ps) return;
451
606
  if (!lp && ps && swap && dom) {
452
- try {
453
- const urlObj = new URL(ps);
454
- const pathParts = urlObj.pathname.split("/");
455
- lp = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
456
- } catch (e) {
457
- const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
458
- if (match) lp = match[1];
607
+ lp = extractLocalFilename(ps);
608
+ }
609
+ if (swap && lp && !hadExplicitPath && hasActiveSession) {
610
+ const key = lp;
611
+ const count = (seenLocalNames.get(key) || 0) + 1;
612
+ seenLocalNames.set(key, count);
613
+ if (count === 2) {
614
+ spWarn(
615
+ `Multiple assets resolve to local file "${key}" without data-stagepass-path. Set unique paths to avoid collisions.`
616
+ );
459
617
  }
460
618
  }
461
619
  const url = resolveAssetUrl(el, ps, lp);
@@ -488,13 +646,21 @@ var Stagepass = (() => {
488
646
  }
489
647
  const process = () => {
490
648
  try {
491
- swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", [
492
- "data-src",
493
- "data-stagepass",
649
+ const seenLocalNames = /* @__PURE__ */ new Map();
650
+ swapEl(
651
+ "script[data-stagepass]",
494
652
  "data-stagepass-path",
495
- "data-stagepass-cachebust",
496
- "data-stagepass-v"
497
- ]);
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
+ );
498
664
  swapEl(
499
665
  'link[rel="stylesheet"][data-stagepass]',
500
666
  "data-stagepass-path",
@@ -507,7 +673,8 @@ var Stagepass = (() => {
507
673
  "data-stagepass-path",
508
674
  "data-stagepass-cachebust",
509
675
  "data-stagepass-v"
510
- ]
676
+ ],
677
+ seenLocalNames
511
678
  );
512
679
  } catch (_) {
513
680
  }
@@ -533,6 +700,7 @@ var Stagepass = (() => {
533
700
  clearSession();
534
701
  hasActiveSession = true;
535
702
  log("log", "\u{1F50C} Stagepass disconnected.");
703
+ emit("session", { active: false, domain: null, swap: false, debug: false });
536
704
  window.location.reload();
537
705
  });
538
706
  const mount = () => {
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{function E(n){if(typeof n!="string"||!n)return!1;if(n==="debug"||n==="localhost")return!0;if(n.startsWith("localhost:")){let o=n.slice(10);return/^[0-9]{1,5}$/.test(o)&&Number(o)<=65535}return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.sp$/i.test(n)}function N(n){return n?n.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var q="stagepass_domain",x=12;function B(n,o=Date.now()){if(!n||!n.startsWith("{"))return null;try{let a=JSON.parse(n);return typeof a.domain!="string"||typeof a.expires!="number"||!Number.isFinite(a.expires)||!E(a.domain)||a.expires<=o?null:{domain:a.domain,expires:a.expires}}catch{return null}}function K(n,o=x,a=Date.now()){let p=Number.isFinite(o)&&o>0?o:x;return{domain:n,expires:a+p*60*60*1e3}}function J(n){return JSON.stringify(n)}function Q(n){if(n==null||n==="")return x;let o=Number(n);return!Number.isFinite(o)||o<=0?x:o}function Y(n,o,a){if(!n||typeof n!="string")return n;let p=encodeURIComponent(a),c=n.indexOf("#"),T=c>=0?n.slice(c):"",A=c>=0?n.slice(0,c):n,I=A.includes("?")?"&":"?";return`${A}${I}${encodeURIComponent(o)}=${p}${T}`}function $(n,o,a){let p=o.startsWith("/")?o.substring(1):o;return`https://${n}/${p}?_cb=${encodeURIComponent(String(a))}`}async function X(){let n=typeof navigator<"u"?navigator.permissions:void 0;if(!n||typeof n.query!="function")return"unknown";let o=["loopback-network","local-network-access"];for(let a of o)try{let p=await n.query({name:a}),c=p&&p.state;if(c==="granted"||c==="prompt"||c==="denied")return c}catch{}return"unknown"}function Z(n){return n==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":n==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function ee(n,o){let a=o.hasAttribute("async"),p=o.hasAttribute("defer");a?n.async=!0:(n.async=!1,p||(n.defer=!0))}(function(){let n=q,o="stagepass",a="2.0.0";function p(){try{if(document.currentScript instanceof HTMLScriptElement)return document.currentScript}catch{}try{let e=document.querySelectorAll('script[src*="loader"]');for(let t=e.length-1;t>=0;t--){let s=e[t];if(/loader(?:\.min)?\.js/i.test(s.src||""))return s}}catch{}return null}let c=p(),T=(c==null?void 0:c.getAttribute("data-stagepass-mute-console"))==="true",A=Q(c==null?void 0:c.getAttribute("data-stagepass-session-hours")),I=c==null?void 0:c.getAttribute("data-stagepass-version"),_=new URLSearchParams(window.location.search);function te(){var e;try{let t=(e=new Error().stack)==null?void 0:e.split(`
2
- `);if(!t)return"";let s=/loader(?:\.min)?\.js/i;for(let i=3;i<t.length;i++){let d=t[i].match(/([^/]+\.(?:js|ts))(?:[?#][^:]*)?:(\d+)/);if(d){let g=d[1];if(!s.test(g))return` ${g}:${d[2]}`}}}catch{}return""}let m=!1;function h(e,...t){if(m)try{let s=new Date().toTimeString().split(" ")[0],i=te(),f=`[\u{1F3AB} ${s}${i?" |"+i:""}]`;e==="error"?console.log(`%c${f}`,"color: red; font-weight: bold;",...t):console[e]?console[e](f,...t):console.log(f,e,...t)}catch{}}function ne(...e){let t="log";e.length>0&&(e[0]==="warn"||e[0]==="error")&&(t=e[0],e=e.slice(1)),h(t,...e)}let C=(...e)=>h("warn",...e),R=(...e)=>h("error",...e);function se(){try{let e=localStorage.getItem(n),t=B(e);return t?t.domain:(e&&localStorage.removeItem(n),null)}catch{return null}}function oe(e){try{let t=K(e,A);localStorage.setItem(n,J(t))}catch{}}function M(){try{localStorage.removeItem(n)}catch{}}let D=!1,l=se();if(_.has(o)){let e=_.get(o);if(e==="off"||e==="0"||e==="false")M(),l=null,m=!0,h("log","\u{1F50C} Stagepass disconnected."),m=!1;else if(e){let t=e==="debug"?"debug":N(e);t&&E(t)?(oe(t),l=t,m=!0,h("log",t==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${t}`),D=!0):t&&(m=!0,C(`Invalid domain: ${t}. Only .sp domains are allowed.`),m=!1)}try{_.delete(o);let t=_.toString();window.history.replaceState({},"",window.location.pathname+(t?`?${t}`:"")+window.location.hash)}catch{}}l&&!E(l)&&(M(),l=null),m=!!(l&&E(l)),l&&!D&&l!=="debug"&&m&&h("log",`\u{1F50C} Stagepass connected to: ${l}`);let re=!!l,w=!!l&&l!=="debug",y=w?N(l):null,H=w?Date.now():0,ie=H,ae=H,v=window.location.hostname,ce=v==="localhost"||v==="127.0.0.1"||v.startsWith("localhost:")||v.startsWith("127.0.0.1:"),U=w||ce,V=U?"local":v.endsWith(".webflow.io")?"staging":"production";if(T&&V==="production"&&!m)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}function le(e){let t="unknown",s=null,i=null;return/Edg\/(\d+)/.test(e)?(t="edge",i=e.match(/Edg\/(\d+)/)):/OPR\/(\d+)/.test(e)?(t="opera",i=e.match(/OPR\/(\d+)/)):/Firefox\/(\d+)/.test(e)?(t="firefox",i=e.match(/Firefox\/(\d+)/)):/Chrome\/(\d+)/.test(e)?(t="chrome",i=e.match(/Chrome\/(\d+)/)):/Version\/(\d+).+Safari\//.test(e)&&(t="safari",i=e.match(/Version\/(\d+)/)),i&&i[1]&&(s=Number(i[1])),{family:t,major:Number.isFinite(s)?s:null,userAgent:e}}function de(e){return/Android/i.test(e)?{family:"android"}:/iPhone|iPad|iPod/i.test(e)?{family:"ios"}:/Mac OS X|Macintosh/i.test(e)?{family:"macos"}:/Windows NT/i.test(e)?{family:"windows"}:/Linux/i.test(e)?{family:"linux"}:{family:"unknown"}}function ue(e){let t="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,s="desktop";return/iPad|Tablet/i.test(e)?s="tablet":/Mobi|Android.+Mobile|iPhone/i.test(e)?s="mobile":/Android/i.test(e)&&t&&(s="tablet"),{type:s,touch:t}}function fe(){let e="no-preference",t="unknown";try{window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").matches?(e="dark",t="dark"):window.matchMedia("(prefers-color-scheme: light)").matches&&(e="light",t="light"))}catch{}return{preferred:e,current:t}}function z(e){try{let t=window[e],s="__stagepass_test__";return t.setItem(s,"1"),t.removeItem(s),!0}catch{return!1}}function pe(){let e=navigator.userAgent||"",t=null;try{t=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:fe(),browser:le(e),os:de(e),device:ue(e),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:t},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:z("localStorage"),sessionStorage:z("sessionStorage")}}}let r=window.stagepass||{},me=pe();r.vars=Object.freeze({isLocal:U,env:V,domain:y||v,timestamp:ae,version:a,client:me}),r.log=ne,r.warn=C,r.error=R,r.resolveLocalUrl=e=>{let t=r.vars;return!w||!y||!e?"":$(y,e,t.timestamp||Date.now())},window.stagepass=r,globalThis.stagepass=r,window.sp=r,globalThis.sp=r;try{if(window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),t=window.matchMedia("(prefers-color-scheme: light)"),s=()=>{var i,f;(f=(i=r.vars)==null?void 0:i.client)!=null&&f.theme&&(e.matches?(r.vars.client.theme.current="dark",r.vars.client.theme.preferred="dark"):t.matches?(r.vars.client.theme.current="light",r.vars.client.theme.preferred="light"):(r.vars.client.theme.current="unknown",r.vars.client.theme.preferred="no-preference"))};typeof e.addEventListener=="function"?(e.addEventListener("change",s),t.addEventListener("change",s)):typeof e.addListener=="function"&&(e.addListener(s),t.addListener(s))}}catch{}let ge=()=>{var e,t;(t=(e=r.vars)==null?void 0:e.client)!=null&&t.viewport&&(r.vars.client.viewport.width=window.innerWidth||0,r.vars.client.viewport.height=window.innerHeight||0,r.vars.client.viewport.dpr=window.devicePixelRatio||1)};window.addEventListener("resize",ge);let O="unknown",S=null;function he(e,t,s){if(w&&s&&y)return $(y,s,ie);let f=e.getAttribute("data-stagepass-v")||I;return f?Y(t,"v",f):t}function W(e,t,s,i,f){document.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(d=>{try{d.setAttribute("data-stagepass-processed","true");let g=d.getAttribute(t),k=d.getAttribute(s);if(!k)return;if(!g&&k&&w&&y)try{let u=new URL(k).pathname.split("/");g=u[u.length-1]||u[u.length-2]}catch{let u=k.match(/\/([^\/\?#]+)(?:\?|#|$)/);u&&(g=u[1])}let P=he(d,k,g);if(!P)return;let b=document.createElement(i);i==="script"?(b.src=P,Array.from(d.attributes).forEach(L=>{let u=L;f.includes(u.name)||b.setAttribute(u.name,u.value)}),ee(b,d)):(b.rel="stylesheet",b.href=P,Array.from(d.attributes).forEach(L=>{let u=L;f.includes(u.name)||b.setAttribute(u.name,u.value)})),d.parentNode?(d.parentNode.insertBefore(b,d),d.remove()):R(`${i} injection failed: No parent node`)}catch{}})}let we=()=>{try{W("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"]),W('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"])}catch{}};function j(e){let t=l==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE";S&&(t=l==="debug"?"STAGEPASS DEBUG \xB7 LNA":"STAGEPASS \xB7 ALLOW LOCAL NETWORK"),e.textContent=t,S&&(e.title=S)}function F(){if(re)try{let e=document.createElement("div");e.id="stagepass-flag",j(e),e.style.cssText='font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;',e.addEventListener("click",()=>{M(),m=!0,h("log","\u{1F50C} Stagepass disconnected."),window.location.reload()});let t=()=>{document.body&&document.body.appendChild(e)};document.body?t():document.addEventListener("DOMContentLoaded",t),r.__flagEl=e}catch{}}async function G(){if(w)try{if(O=await X(),S=Z(O),S){C(S);let e=r.__flagEl;e&&j(e)}}catch{O="unknown",S=null}we()}G(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",()=>{G()}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",F):F()})();})();
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()})();})();
package/global.d.ts CHANGED
@@ -52,15 +52,69 @@ export interface StagepassVars {
52
52
  timestamp: number;
53
53
  /** Package version injected at build time. */
54
54
  version: string;
55
+ /** Client runtime info (theme listeners and viewport updates from boot). */
55
56
  client: StagepassClientInfo;
56
57
  }
57
58
 
59
+ export type StagepassEnvName = 'local' | 'staging' | 'production';
60
+
61
+ export type StagepassCapabilityName =
62
+ | 'localStorage'
63
+ | 'sessionStorage'
64
+ | 'cookies'
65
+ | 'serviceWorker'
66
+ | (string & {});
67
+
68
+ export type StagepassEventName = 'theme' | 'session' | (string & {});
69
+
70
+ /** Payload of `sp.on('session', fn)` (emitted once at boot). */
71
+ export interface StagepassSessionEvent {
72
+ /** True while a Stagepass session (or debug mode) is active. */
73
+ active: boolean;
74
+ /** Raw session value (`.sp` domain or `debug`), or null. */
75
+ domain: string | null;
76
+ /** True when assets are swapped to a local `.sp` domain. */
77
+ swap: boolean;
78
+ /** True in debug mode (`?stagepass=debug`). */
79
+ debug: boolean;
80
+ }
81
+
82
+ /** Subscribe helper with typed payloads for known events. */
83
+ export interface StagepassOn {
84
+ /**
85
+ * Color scheme changes. Payload equals `vars.client.theme`.
86
+ * @example
87
+ * const off = sp.on('theme', ({ current }) => { document.documentElement.dataset.theme = current; });
88
+ */
89
+ (event: 'theme', fn: (payload: StagepassClientTheme) => void): () => void;
90
+ /**
91
+ * Session state, emitted once at boot after globals are set.
92
+ * @example
93
+ * sp.on('session', ({ active, swap }) => { if (active && swap) sp.log('local assets'); });
94
+ */
95
+ (event: 'session', fn: (payload: StagepassSessionEvent) => void): () => void;
96
+ /** Unknown events are accepted and never fire. */
97
+ (event: StagepassEventName, fn: (payload: unknown) => void): () => void;
98
+ }
99
+
100
+ export type StagepassModuleFactory = (api: StagepassAPI) => void;
101
+
58
102
  /**
59
103
  * Core Stagepass runtime API (loader). Modules extend this via declaration merging.
60
104
  */
61
105
  export interface StagepassAPI {
106
+ /**
107
+ * Frozen runtime variables.
108
+ * @example
109
+ * if (sp.vars.isLocal) sp.log('local session on', sp.vars.domain);
110
+ */
62
111
  vars: StagepassVars;
63
- /** Structured log (only when a session is active). */
112
+ /**
113
+ * Structured log (only when a session is active). A first argument of
114
+ * `'warn'` or `'error'` selects the level.
115
+ * @example
116
+ * sp.log('menu ready');
117
+ */
64
118
  log: (...args: unknown[]) => void;
65
119
  warn: (...args: unknown[]) => void;
66
120
  error: (...args: unknown[]) => void;
@@ -70,6 +124,37 @@ export interface StagepassAPI {
70
124
  * @returns Local URL, or empty string when no session
71
125
  */
72
126
  resolveLocalUrl: (relativePath: string) => string;
127
+
128
+ /**
129
+ * Flat env helper. `local` means an active swap session to a `.sp` domain.
130
+ * Staging: hostname ends with `.webflow.io` or matches `data-stagepass-staging-hosts`.
131
+ */
132
+ env: () => StagepassEnvName;
133
+ /**
134
+ * `true` when `env()` equals `name`.
135
+ * @example
136
+ * if (sp.is('production')) initAnalytics();
137
+ */
138
+ is: (name: StagepassEnvName | string) => boolean;
139
+ /**
140
+ * Capability probe. Known: `localStorage`, `sessionStorage`, `cookies`, `serviceWorker`.
141
+ * Any other name returns `false`.
142
+ * @example
143
+ * if (sp.can('localStorage')) localStorage.setItem('seen', '1');
144
+ */
145
+ can: (capability: StagepassCapabilityName) => boolean;
146
+ /** Read a key from `vars.client`, or the whole client object when omitted. */
147
+ client: (key?: keyof StagepassClientInfo | string) => unknown;
148
+ /**
149
+ * Subscribe to runtime events. Returns an unsubscribe function.
150
+ * Supported: `theme` (prefers-color-scheme), `session` (boot).
151
+ */
152
+ on: StagepassOn;
153
+ /**
154
+ * Register a module after a major-version check against the loader.
155
+ * @returns whether registration succeeded
156
+ */
157
+ use: (name: string, version: string, factory: StagepassModuleFactory) => boolean;
73
158
  }
74
159
 
75
160
  declare global {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "2.0.0",
3
+ "version": "2.2.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",