@stagepass/loader 2.3.3 → 2.5.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 +50 -9
- package/dist/flag.min.js +1 -1
- package/dist/live.min.js +1 -0
- package/dist/loader.js +86 -26
- package/dist/loader.min.js +2 -2
- package/global.d.ts +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,16 +12,24 @@ npm install @stagepass/loader@2
|
|
|
12
12
|
|
|
13
13
|
## CDN Usage
|
|
14
14
|
|
|
15
|
-
Prefer the major pin `@2` in production on jsDelivr. Stagepass follows strict semver: no breaking changes within v2; breaking changes only in a new major (v3). Exact pins (e.g. `@2.
|
|
15
|
+
Prefer the major pin `@2` in production on jsDelivr. Stagepass follows strict semver: no breaking changes within v2; breaking changes only in a new major (v3). Exact pins (e.g. `@2.4.0`) are optional for maximum control. jsDelivr may cache `@2` for a while; purge with `https://purge.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js`. See [Version pinning](https://github.com/arobertherz/stagepass/blob/master/docs/loader.md#version-pinning) in the docs.
|
|
16
16
|
|
|
17
17
|
```html
|
|
18
18
|
<script
|
|
19
19
|
src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js"
|
|
20
|
-
data-stagepass-version="2.
|
|
20
|
+
data-stagepass-version="2.5.0"
|
|
21
21
|
></script>
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
unpkg serves the same paths if you need an alternative CDN.
|
|
24
|
+
unpkg serves the same paths if you need an alternative CDN. Always embed the full `/dist/loader.min.js` path (not a short package URL that redirects); otherwise session chunks resolve from the wrong folder. Or set `data-stagepass-flag-base`.
|
|
25
|
+
|
|
26
|
+
## Known limits (scoped acceptance)
|
|
27
|
+
|
|
28
|
+
Acceptance for `live.min.js` / live reload is **scoped localhost only**. It is not proof of the full default `setup` / `start` / `stop` path, System Trust / `certs renew`, autostart / login / boot / OS-crash recovery, or a real `.sp` resolver + production Webflow origin path.
|
|
29
|
+
|
|
30
|
+
A `localhost` / `localhost:<port>` session still reports `sp.env() === 'production'` (unchanged since 2.3.1 / 2.3.3). Only an active `*.sp` swap session is `local`. That is expected behaviour, not a live-reload failure.
|
|
31
|
+
|
|
32
|
+
`live.min.js` ships since loader **2.4.0** (lazy-loaded during an active swap session; not in **2.3.3**). `@2` is a major range alias, not the npm `latest` tag; after a publish the CDN can briefly serve the previous 2.x build. Pin an exact version (e.g. `@2.5.0`) when a specific build must load.
|
|
25
33
|
|
|
26
34
|
See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
|
|
27
35
|
|
|
@@ -33,6 +41,7 @@ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
|
|
|
33
41
|
- Inserts the new element before the original, then removes the original (`data-stagepass-processed` prevents double work).
|
|
34
42
|
- Local session: cache-bust with a single `?_cb=<timestamp>` per page load.
|
|
35
43
|
- Production: version bust with `data-stagepass-version` (loader tag) and/or `data-stagepass-v` (per asset) → `?v=<version>` (URL-encoded; existing query/hash preserved).
|
|
44
|
+
- Production, per asset: `data-stagepass-nocache` on a `data-src` / `data-href` asset sets exactly one fresh `?_cb=<timestamp>` on **every** page view, for every visitor (not just during a Stagepass session). An existing `_cb` in that URL is replaced, so there is never a second `_cb`. `?v=` is applied first when present. Order: original query (without `_cb`), then `v`, then `_cb`. Other query parameters and the hash stay preserved.
|
|
36
45
|
- `data-stagepass-cachebust="true"` is legacy and **does not** timestamp every production view in v2.
|
|
37
46
|
- Session expiry (default **12 h**): `data-stagepass-session-hours` on the loader tag.
|
|
38
47
|
- Optional legacy global console mute: `data-stagepass-mute-console="true"` (production, no session only).
|
|
@@ -49,15 +58,17 @@ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
|
|
|
49
58
|
| `data-stagepass-staging-hosts` | Comma-separated hostnames treated as staging (in addition to `*.webflow.io`). |
|
|
50
59
|
| `data-stagepass-alias` | Optional custom global name (valid JS identifier). Assigned only when that global is free. |
|
|
51
60
|
| `data-stagepass-flag-base` | Folder for `flag.min.js` / `flag-card.min.js` when the loader is inlined or bundled (2.3.1+). `http(s)` or relative only; also `window.stagepassFlagBase`. Read only during a session. |
|
|
61
|
+
| `data-stagepass-live-src="true"` | Opt-in zero-cost mode: tagged assets use native `src` / `href`; the loader rewrites them only while a swap session is active. |
|
|
52
62
|
|
|
53
63
|
## Asset attributes
|
|
54
64
|
|
|
55
65
|
| Attribute | Effect |
|
|
56
66
|
| :--- | :--- |
|
|
57
67
|
| `data-stagepass` | Marks the element for processing (any value). |
|
|
58
|
-
| `data-src` / `data-href` | Production URL
|
|
68
|
+
| `data-src` / `data-href` | Production URL for legacy mode (default). Required unless live-src opt-in uses native `src` / `href`. |
|
|
59
69
|
| `data-stagepass-path` | Local path under the linked project root (optional). |
|
|
60
70
|
| `data-stagepass-v` | Per-asset production `?v=<version>` (overrides loader `data-stagepass-version`). |
|
|
71
|
+
| `data-stagepass-nocache` | Requires loader **2.5.0** or later (older loaders ignore the attribute; the asset then loads cached as before). Boolean (present, or `="true"`; `="false"` turns it off). Production only: sets exactly one fresh `?_cb=<timestamp>` on **this asset's** URL on every page view, for every visitor. An existing `_cb` is replaced (never a second one). Combines with `data-stagepass-v` / `data-stagepass-version` as original query (without `_cb`), then `?v=<version>`, then `_cb`. No effect during an active local/dev swap session (local assets already get a per-page-load `_cb` stamp). Not applied to `data-stagepass-live-src="true"` assets, which stay untouched in production by design. |
|
|
61
72
|
| `data-stagepass-cachebust` | Legacy; ignored for production timestamps in v2. |
|
|
62
73
|
| `data-stagepass-processed` | Internal; set after processing. |
|
|
63
74
|
|
|
@@ -91,15 +102,44 @@ Shown only while a session is active (including debug).
|
|
|
91
102
|
- Errors: `sp.error`, `sp.log('error', …)`, `console.error`, uncaught errors (with stack), failed resource loads, unhandled rejections (with stack). Local files report "Local file not found (404)" or "Local server not reachable … Run stagepass doctor". Sanitized errors from other origins show as "Error in a cross-origin script (details only in DevTools console)".
|
|
92
103
|
- Accessibility: the pill is a button with `aria-expanded`, the card a `role="dialog"`; focus moves into the card and back to the pill; reduced motion makes all changes instant.
|
|
93
104
|
- Rendered in an open Shadow DOM (`#stagepass-flag`) with DOM APIs only (no `innerHTML`, no `eval`, constructable stylesheet with a `<style>` fallback). No shadows, glow or filters.
|
|
94
|
-
- The UI lives in `dist/flag.min.js` (about 2
|
|
105
|
+
- The UI lives in `dist/flag.min.js` (about 3.2 KB gzip) and `dist/flag-card.min.js` (about 4.8 KB gzip, fetched on first expand). Both are fetched only during a session, from the folder of the loader's script URL under any file name (self-hosted or copied from `node_modules`: keep the flag files together). Inlined or bundled: set `data-stagepass-flag-base`; without a script URL and without the option they come from jsDelivr at the same version (debug sessions warn). Allow that origin in `script-src` if the site uses a strict CSP.
|
|
106
|
+
- Loader **2.4.0** and later: during a swap session the flag chunk also bootstraps `live.min.js` (lazy EventSource client). Published **2.3.3** does not ship that chunk.
|
|
107
|
+
|
|
108
|
+
## Zero-cost production mode
|
|
109
|
+
|
|
110
|
+
Opt-in with `data-stagepass-live-src="true"` on the loader tag (loader **2.4.0** and later). Put a normal `src` / `href` (optional `integrity` + `crossorigin`) on `data-stagepass` assets instead of `data-src` / `data-href`. Without a session the browser loads those URLs directly; with a session Stagepass rewrites them to the local `.sp` host before classic scripts run (loader must be a sync script in `<head>` before the assets). Legacy `data-src` / `data-href` stays the default and keeps working. See [Zero-cost production mode](https://github.com/arobertherz/stagepass/blob/master/docs/loader.md#zero-cost-production-mode) for migration, SRI, and limitations.
|
|
111
|
+
|
|
112
|
+
## Permanent per-asset cache busting
|
|
113
|
+
|
|
114
|
+
`data-stagepass-nocache` requires loader **2.5.0** or later (older loaders ignore the attribute; the asset then loads cached as before). It is for the rare asset that must be fetched fresh on every page view, for every production visitor, not just during a Stagepass session. Typical case: a script that embeds third-party forms via iframes, where a stale cached copy breaks the embed.
|
|
115
|
+
|
|
116
|
+
```html
|
|
117
|
+
<script
|
|
118
|
+
data-stagepass
|
|
119
|
+
data-src="https://cdn.example.com/js/forms-embed.js"
|
|
120
|
+
data-stagepass-nocache
|
|
121
|
+
></script>
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
- Boolean attribute: present (any value, including empty) or `="true"` turns it on; `="false"` turns it off (same as omitting it).
|
|
125
|
+
- Scoped to exactly that asset. All other `data-stagepass` assets keep the existing version-only cache strategy.
|
|
126
|
+
- Sets exactly one `?_cb=<Date.now()>`, replacing any `_cb` already in the URL (a page-supplied `_cb` does not survive, and a second `_cb` is not appended). Any `?v=<version>` from `data-stagepass-v` / `data-stagepass-version` is applied first, so the order is original query (without `_cb`), then `v`, then `_cb`. Other query parameters and the hash stay preserved.
|
|
127
|
+
- Production only. During an active local/dev swap session the asset resolves to the local `.sp` URL as usual (single `?_cb=<timestamp>` per page load, same as every other swapped file). `data-stagepass-nocache` has no extra effect there.
|
|
128
|
+
- Not applied to `data-stagepass-live-src="true"` assets: that mode is intentionally zero-cost (untouched by the loader in production), so pair an asset that needs permanent busting with the default `data-src` / `data-href` mode instead.
|
|
129
|
+
- `data-stagepass-cachebust` remains legacy and unrelated: it no longer timestamps every production view (see above) and is not a per-asset opt-in.
|
|
95
130
|
|
|
96
131
|
## Runtime API
|
|
97
132
|
|
|
98
|
-
Preferred global is `sp` (aliases: `stagepass`, `window.stagepass
|
|
133
|
+
Preferred global is `sp` (aliases: `stagepass`, `window.stagepass`; both always assigned in 2.x). Optional custom alias via `data-stagepass-alias` when free. Types ship in `global.d.ts` (complete `sp` API with JSDoc and examples, typed `sp.on(...)` events). Add `"@stagepass/loader"` to `compilerOptions.types` (or `/// <reference types="@stagepass/loader" />`). In debug mode, after the flag chunk loads, reading `sp.vars` once hints toward the flat helpers (reads before the chunk has loaded do not hint).
|
|
134
|
+
|
|
135
|
+
Two layers (do not conflate):
|
|
136
|
+
|
|
137
|
+
1. **Endpoint / session choice:** `*.sp` vs `localhost` / `localhost:<port>` vs `debug`.
|
|
138
|
+
2. **`sp.env()`:** `local` only for an active `*.sp` swap session; a `localhost` / `localhost:<port>` session is `production` (since 2.3.1 / 2.3.3). `sp.vars.isLocal` remains “swap active **or** page on localhost” and is not the same question as `sp.env()`.
|
|
99
139
|
|
|
100
140
|
```js
|
|
101
|
-
sp.vars.isLocal // boolean: session swap active or page on localhost
|
|
102
|
-
sp.vars.env // 'local' | 'staging' | 'production' (
|
|
141
|
+
sp.vars.isLocal // boolean: session swap active or page on localhost (≠ sp.env())
|
|
142
|
+
sp.vars.env // 'local' | 'staging' | 'production' (page/host heuristic; not sp.env())
|
|
103
143
|
sp.vars.domain // active .sp domain, or page hostname when no swap
|
|
104
144
|
sp.vars.timestamp // session start ms while swapping; otherwise 0
|
|
105
145
|
sp.vars.version // package version (build-time)
|
|
@@ -107,8 +147,9 @@ sp.vars.client // theme / browser / os / device / viewport / locale / capab
|
|
|
107
147
|
|
|
108
148
|
// Flat helpers (additive)
|
|
109
149
|
sp.env() // 'local' | 'staging' | 'production'
|
|
110
|
-
// local = active swap to a .sp domain
|
|
150
|
+
// local = active swap to a .sp domain only
|
|
111
151
|
// staging = *.webflow.io or data-stagepass-staging-hosts
|
|
152
|
+
// else production (a localhost session is production)
|
|
112
153
|
sp.is('staging')
|
|
113
154
|
sp.can('localStorage') // also: sessionStorage, cookies, serviceWorker
|
|
114
155
|
sp.client('theme') // or sp.client() for the whole object
|
package/dist/flag.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var
|
|
1
|
+
(()=>{var V=":host{all:initial!important;position:fixed!important;top:12px!important;right:12px!important;z-index:2147483647!important;display:block!important}.w{--W:44px;--k:1;--fg:#17171B;--a:#FF453A;--z:#FF8A3D;--ring:#121215;--bd:rgba(18,18,21,.22);position:relative;display:block;font:700 12px/1 ui-monospace,Menlo,Consolas,monospace;letter-spacing:.04em;color:var(--fg)}.b{all:unset;box-sizing:border-box;position:relative;display:block;margin-left:auto;height:44px;width:var(--W);cursor:pointer;-webkit-tap-highlight-color:transparent;touch-action:manipulation}[data-st=rest] .b{width:44px}.bg,.t,.fr{position:absolute;right:0;top:8px;height:28px;box-sizing:border-box}.bg{width:var(--W);transform-origin:100% 50%}.bg i{position:absolute;top:0;height:28px;box-sizing:border-box;border:solid var(--bd);border-width:1px 0}.bg .l{left:0;width:14px;border-left-width:1px;border-radius:14px 0 0 14px;background:var(--a)}.bg .r{right:0;width:14px;border-right-width:1px;border-radius:0 14px 14px 0;background:var(--z)}.m{left:13px;right:13px;background:linear-gradient(90deg,var(--a),var(--z));transform-origin:100% 0}[data-st=rest] .l{transform:translateX(calc(var(--W) - 44px))}[data-st=rest] .m{transform:scaleX(var(--k))}.t{display:flex;align-items:center;gap:10px;padding:0 14px;white-space:nowrap;pointer-events:none}[data-st=rest] .t>b,[data-st=rest] .c{opacity:0}.c{display:flex;gap:10px}.c:empty{display:none}.c span{display:flex;align-items:center;gap:4px}svg{flex:none;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}.c svg{width:12px;height:12px}.k{width:16px;height:8px;stroke-width:2}.dot{position:absolute;right:-1px;top:3px;width:8px;height:8px;border-radius:50%;border:2px solid var(--ring);background:var(--d);opacity:0}[data-d=e] .dot{--d:#FF2E4D}[data-d=w] .dot{--d:#FFB224}[data-st=rest][data-d] .dot{opacity:1}.fr{right:-4px;top:4px;height:36px;width:calc(var(--W) + 8px);border-radius:18px;border:2px solid #fff;outline:2px solid var(--ring);opacity:0;pointer-events:none}.b:focus-visible .fr{opacity:1}[data-st=rest] .fr{width:52px}.b:active .bg{transform:scale(.96)}@media (prefers-reduced-motion:no-preference){.l,.m{transition:transform .22s cubic-bezier(.2,.8,.2,1)}.t>b,.c{transition:opacity .14s .06s}[data-st=rest] .l,[data-st=rest] .m{transition:transform .16s cubic-bezier(.4,0,.6,1)}[data-st=rest] .t>b,[data-st=rest] .c{transition:opacity .08s}.dot{transition:opacity .12s}[data-st=rest] .dot{transition-delay:.12s}.fr{transition:opacity .12s .12s}.bg{transition:transform .08s}}",S="http://www.w3.org/2000/svg",B=["M6 1.3 11 10.3H1zM6 4.8v2.2m0 1.6v.1","M4 1h4l3 3v4l-3 3H4L1 8V4zM6 3.8v2.6m0 1.6v.1"],N="stagepass.flag.v2",O="stagepass:flash",W="stagepass.card.v2";function _(r,t){try{if(!("adoptedStyleSheets"in r))throw 0;let n=new CSSStyleSheet;n.replaceSync(t),r.adoptedStyleSheets=[...r.adoptedStyleSheets,n]}catch{r.appendChild(document.createElement("style")).textContent=t}}function H(r){let t=document.createElementNS(S,"svg");return t.setAttribute("viewBox","0 0 12 12"),t.setAttribute("aria-hidden","true"),t.appendChild(document.createElementNS(S,"path")).setAttribute("d",B[r]),t}var T=(r,t)=>r+" "+t+(r==1?"":"s"),M=(r,t)=>{try{return r.matches(t)}catch{return!1}};function z(r){let t=document,n=t.createElement("div");n.id="stagepass-flag";let m=n.attachShadow({mode:"open"});_(m,V);let c=(e,g,d)=>{let f=g.appendChild(t.createElement(e));return d&&(f.className=d),f},p=c("div",m,"w");p.setAttribute("data-st","rest");let o=c("button",p,"b");o.type="button",o.setAttribute("aria-haspopup","dialog"),o.setAttribute("aria-expanded","false");let a=c("span",o,"bg");["l","m","r"].forEach(e=>c("i",a,e)),c("span",o,"fr");let s=c("span",o,"t");a.setAttribute("aria-hidden","true"),s.setAttribute("aria-hidden","true");let u=c("b",s),h=c("span",s,"c"),v=s.appendChild(t.createElementNS(S,"svg"));v.setAttribute("class","k"),v.setAttribute("viewBox","0 0 16 8"),v.appendChild(t.createElementNS(S,"path")).setAttribute("d","M4 1h8a3 3 0 0 1 0 6H4a3 3 0 0 1 0-6z"),c("i",o,"dot");let i="rest",b=null,F=!1,E,x=!1,k="rest",L=!1,y=()=>{let[e,g]=r.n,d=r.debug?"DEBUG":"LOCAL";u.textContent=d,h.textContent="",[e,g].forEach((w,D)=>{if(!w)return;let C=c("span",h);C.appendChild(H(D)),C.appendChild(t.createTextNode(w>99?"99+":String(w)))}),g||e?p.setAttribute("data-d",g?"e":"w"):p.removeAttribute("data-d"),o.setAttribute("aria-label","Stagepass "+d+", "+T(e,"warning")+", "+T(g,"error")+". "+(i=="card"?"Hide":"Show")+" session details");let f=s.offsetWidth;f&&(p.style.setProperty("--W",f+"px"),p.style.setProperty("--k",String(18/(f-26)))),b&&b.render()},I=()=>{if(!F){F=!0;try{let e=window.stagepass,g=Symbol.for(W);Object.defineProperty(e,g,{configurable:!0,value:f=>{delete e[g];try{b=f(P),i=="card"&&b.show()}catch{}}});let d=t.createElement("script");d.src=r.card,d.async=!0,(t.head||t.documentElement).appendChild(d)}catch{}}},l=e=>{e!=i&&(clearTimeout(E),i=e,p.setAttribute("data-st",e),o.setAttribute("aria-expanded",String(e=="card")),e!="rest"&&I(),b&&(e=="card"?b.show():b.hide()),y())},P={s:r,root:m,w:p,host:n,go:l,icon:H,css:_};o.addEventListener("pointerdown",e=>{x=e.pointerType=="touch",k=i}),o.addEventListener("pointerenter",e=>{e.pointerType=="mouse"&&i=="rest"&&l("exp")}),p.addEventListener("pointerleave",e=>{e.pointerType=="mouse"&&i=="exp"&&!M(o,":focus-visible")&&l("rest")}),o.addEventListener("focus",()=>{!x&&!L&&i=="rest"&&l("exp")}),o.addEventListener("blur",()=>{i=="exp"&&!M(o,":hover")&&l("rest")}),o.addEventListener("click",()=>{x&&k=="rest"?(l("exp"),E=setTimeout(()=>l("rest"),4e3)):l(i=="card"?"exp":"card"),x=!1}),t.addEventListener("keydown",e=>{e.key!="Escape"||i=="rest"||(i=="card"?(l("exp"),o.focus()):l("rest"))}),t.addEventListener("pointerdown",e=>{if(i=="rest"||e.composedPath().indexOf(n)>=0)return;let g=t.activeElement==n;l("rest"),g&&setTimeout(()=>{let d=t.activeElement;(!d||d==t.body||d==n)&&(L=!0,o.focus({preventScroll:!0}),L=!1)})},!0);let A=()=>{n.isConnected||(t.body||t.documentElement).appendChild(n),y();try{sessionStorage.getItem(O)&&(sessionStorage.removeItem(O),l("exp"),E=setTimeout(()=>l("rest"),3e3))}catch{}};return t.readyState==="loading"?t.addEventListener("DOMContentLoaded",A):A(),y(),y}var R="stagepass.live.v1";var U='Multiple assets resolve to local file "%s" without data-stagepass-path. Set unique paths to avoid collisions.',j="Prefer sp.env()/is()/can()/client()/on() over reading sp.vars directly.";try{let r=window.stagepass,t=r==null?void 0:r[Symbol.for(N)];if(typeof t!="function")throw 0;t(n=>{if(n.debug)try{let a=r.vars,s=!1;Object.defineProperty(r,"vars",{configurable:!0,enumerable:!0,get(){return s||(s=!0,r.warn(j)),a}})}catch{}if(!n.debug&&n.domain)try{let a=Symbol.for(R),s=n.domain;Object.defineProperty(r,a,{configurable:!0,value:h=>{delete r[a];try{h({url:"https://"+s+"/__stagepass/live",localBase:"https://"+s,debug:n.debug,log:(...v)=>r.log(...v)})}catch{}}});let u=document.createElement("script");u.src=new URL("live.min.js",n.card).href,u.async=!0,(document.head||document.documentElement).appendChild(u)}catch{}let m=new Set,c=a=>(a||"").split(/[?#]/)[0].split("/").pop()||"",p=()=>{try{let a=new Map;for(let s of n.f){if(s.x)continue;let u=c(s.local);if(!u)continue;let h=(a.get(u)||0)+1;a.set(u,h),h===2&&!m.has(u)&&(m.add(u),r.warn(U.replace("%s",u)))}}catch{}};p();let o=z(n);return()=>{p(),o()}})}catch{}})();
|
package/dist/live.min.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{var u="stagepass.live.v1",p="/__stagepass/live";function v(e,t){try{let r=new URL(e),l=new URL(t.endsWith("/")?t:t+"/");return!(r.protocol!=="https:"&&r.protocol!=="http:"||r.username||r.password||r.hostname!==l.hostname||r.pathname!==p)}catch{return!1}}function y(e,t=document){let r=e.replace(/\/?$/,"/"),l=Array.from(t.querySelectorAll('link[rel="stylesheet"][href]')),i=0,o=String(Date.now());for(let n of l){let a=n.href||n.getAttribute("href")||"";if(a.startsWith(r))try{let c=new URL(a,t.baseURI);c.searchParams.set("t",o);let s=n.cloneNode(!1);s.removeAttribute("integrity"),s.href=c.href,n.parentNode&&(n.parentNode.insertBefore(s,n),n.remove(),i++)}catch{}}return i}function h(e){try{let t=JSON.parse(e);return!t||typeof t!="object"||t.type!=="css"&&t.type!=="reload"?null:t}catch{return null}}function f(e){let t=e.log||(()=>{}),r=e.doc||document,l=e.reload||(()=>location.reload()),i=e.EventSourceImpl||(typeof EventSource<"u"?EventSource:null);if(!i)return()=>{};if(!v(e.url,e.localBase))return()=>{};let o=null,n=!1,a=()=>{if(!n&&(n=!0,o)){try{o.close()}catch{}o=null}};try{o=new i(e.url)}catch{return()=>{}}return o.onmessage=c=>{if(n)return;let s=h(String(c.data||""));if(s){if(s.type==="css"){y(e.localBase,r);return}s.type==="reload"&&(a(),l())}},o.onerror=()=>{e.debug&&t("Live reload unavailable (closed)."),a()},e.debug&&t("Live reload listening."),a}var d;try{let e=(d=window.stagepass)==null?void 0:d[Symbol.for(u)];typeof e=="function"&&e(f)}catch{}})();
|
package/dist/loader.js
CHANGED
|
@@ -57,13 +57,19 @@ var Stagepass = (() => {
|
|
|
57
57
|
const encoded = encodeURIComponent(value);
|
|
58
58
|
const hashIdx = url.indexOf("#");
|
|
59
59
|
const hash = hashIdx >= 0 ? url.slice(hashIdx) : "";
|
|
60
|
-
|
|
60
|
+
let base = hashIdx >= 0 ? url.slice(0, hashIdx) : url;
|
|
61
|
+
if (key === "_cb") {
|
|
62
|
+
base = base.replace(
|
|
63
|
+
/\?.*/,
|
|
64
|
+
(query) => query.replace(/[&?]_cb(=[^&]*)?(?=&|$)/g, "").replace(/^&/, "?")
|
|
65
|
+
);
|
|
66
|
+
}
|
|
61
67
|
const sep = base.includes("?") ? "&" : "?";
|
|
62
68
|
return `${base}${sep}${encodeURIComponent(key)}=${encoded}${hash}`;
|
|
63
69
|
}
|
|
64
70
|
function buildLocalAssetUrl(domain, relativePath, cacheBust) {
|
|
65
|
-
const clean = relativePath.startsWith("/") ? relativePath.
|
|
66
|
-
return `https://${domain}/${clean}?_cb=${
|
|
71
|
+
const clean = relativePath.startsWith("/") ? relativePath.slice(1) : relativePath;
|
|
72
|
+
return `https://${domain}/${clean}?_cb=${cacheBust}`;
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
// src/lna.ts
|
|
@@ -108,6 +114,11 @@ var Stagepass = (() => {
|
|
|
108
114
|
}
|
|
109
115
|
}
|
|
110
116
|
}
|
|
117
|
+
var NOCACHE_ATTR = "data-stagepass-nocache";
|
|
118
|
+
function isNoCacheEnabled(el) {
|
|
119
|
+
if (!el.hasAttribute(NOCACHE_ATTR)) return false;
|
|
120
|
+
return el.getAttribute(NOCACHE_ATTR) !== "false";
|
|
121
|
+
}
|
|
111
122
|
|
|
112
123
|
// src/env.ts
|
|
113
124
|
function parseStagingHosts(value) {
|
|
@@ -286,7 +297,7 @@ var Stagepass = (() => {
|
|
|
286
297
|
const W = window;
|
|
287
298
|
const d = document;
|
|
288
299
|
const loc = location;
|
|
289
|
-
const PKG_VERSION = true ? "2.
|
|
300
|
+
const PKG_VERSION = true ? "2.5.0" : "0.0.0";
|
|
290
301
|
const LOADER_RE = /loader(?:\.min)?\.js/i;
|
|
291
302
|
function flagBase(v, file) {
|
|
292
303
|
if (typeof v !== "string" || !(v = v.trim())) return null;
|
|
@@ -320,6 +331,7 @@ var Stagepass = (() => {
|
|
|
320
331
|
const loaderVersionAttr = attr("version");
|
|
321
332
|
const stagingHosts = parseStagingHosts(attr("staging-hosts"));
|
|
322
333
|
const aliasName = attr("alias");
|
|
334
|
+
const liveSrc = attr("live-src") === "true";
|
|
323
335
|
const p = new URLSearchParams(loc.search);
|
|
324
336
|
let hasActiveSession = false;
|
|
325
337
|
const flagState = { n: [0, 0], m: [], f: [], swapped: 0, v: PKG_VERSION, vd: isValidDomain };
|
|
@@ -518,7 +530,7 @@ var Stagepass = (() => {
|
|
|
518
530
|
});
|
|
519
531
|
const stagepassObj = W.stagepass || {};
|
|
520
532
|
const registry = createModuleRegistry(PKG_VERSION, spWarn);
|
|
521
|
-
|
|
533
|
+
const varsFrozen = Object.freeze({
|
|
522
534
|
isLocal,
|
|
523
535
|
env,
|
|
524
536
|
domain: dom || hostname,
|
|
@@ -526,10 +538,11 @@ var Stagepass = (() => {
|
|
|
526
538
|
version: PKG_VERSION,
|
|
527
539
|
client: clientInfo
|
|
528
540
|
});
|
|
541
|
+
stagepassObj.vars = varsFrozen;
|
|
529
542
|
stagepassObj.log = spLog;
|
|
530
543
|
stagepassObj.warn = spWarn;
|
|
531
544
|
stagepassObj.error = spError;
|
|
532
|
-
stagepassObj.resolveLocalUrl = (relativePath) => swap && dom && relativePath ? buildLocalAssetUrl(dom, relativePath,
|
|
545
|
+
stagepassObj.resolveLocalUrl = (relativePath) => swap && dom && relativePath ? buildLocalAssetUrl(dom, relativePath, varsFrozen.timestamp || Date.now()) : "";
|
|
533
546
|
stagepassObj.env = () => detectRuntimeEnv(hostname, dom, stagingHosts);
|
|
534
547
|
stagepassObj.is = (name) => stagepassObj.env() === name;
|
|
535
548
|
stagepassObj.can = (capability) => canCapability(clientInfo, capability);
|
|
@@ -628,7 +641,9 @@ var Stagepass = (() => {
|
|
|
628
641
|
function resolveAssetUrl(el, productionSrc, localPath) {
|
|
629
642
|
if (swap && localPath && dom) return buildLocalAssetUrl(dom, localPath, now);
|
|
630
643
|
const version = el.getAttribute("data-stagepass-v") || loaderVersionAttr;
|
|
631
|
-
|
|
644
|
+
let url = version ? appendQueryParam(productionSrc, "v", version) : productionSrc;
|
|
645
|
+
if (isNoCacheEnabled(el)) url = appendQueryParam(url, "_cb", Date.now());
|
|
646
|
+
return url;
|
|
632
647
|
}
|
|
633
648
|
function extractLocalFilename(ps) {
|
|
634
649
|
try {
|
|
@@ -641,8 +656,9 @@ var Stagepass = (() => {
|
|
|
641
656
|
}
|
|
642
657
|
const mine = /* @__PURE__ */ new WeakSet();
|
|
643
658
|
let lnaState = "";
|
|
644
|
-
function track(n, live, local, isScript, retry) {
|
|
659
|
+
function track(n, live, local, isScript, retry, explicit) {
|
|
645
660
|
const f = { live, local, type: isScript ? "js" : "css", st: "" };
|
|
661
|
+
if (explicit) f.x = true;
|
|
646
662
|
const name = fileOf(local);
|
|
647
663
|
mine.add(n);
|
|
648
664
|
flagState.f.push(f);
|
|
@@ -676,26 +692,46 @@ var Stagepass = (() => {
|
|
|
676
692
|
"data-stagepass",
|
|
677
693
|
"data-stagepass-path",
|
|
678
694
|
"data-stagepass-cachebust",
|
|
679
|
-
"data-stagepass-v"
|
|
695
|
+
"data-stagepass-v",
|
|
696
|
+
NOCACHE_ATTR
|
|
680
697
|
];
|
|
681
|
-
|
|
698
|
+
const LS = 'script[data-stagepass][src]:not([data-src]):not([data-stagepass-processed]),link[rel="stylesheet" i][data-stagepass][href]:not([data-href]):not([data-stagepass-processed])';
|
|
699
|
+
const ff = "onbeforescriptexecute" in d;
|
|
700
|
+
function rewriteLive(el) {
|
|
701
|
+
try {
|
|
702
|
+
const js = el.tagName === "SCRIPT";
|
|
703
|
+
if (js && (ff || d.currentScript === el)) return;
|
|
704
|
+
const k = js ? "src" : "href";
|
|
705
|
+
const ps = el.getAttribute(k);
|
|
706
|
+
if (!ps) return;
|
|
707
|
+
el.setAttribute("data-stagepass-processed", "true");
|
|
708
|
+
const x = el.getAttribute("data-stagepass-path");
|
|
709
|
+
const lp = x || extractLocalFilename(ps);
|
|
710
|
+
if (!lp) return;
|
|
711
|
+
const url = buildLocalAssetUrl(dom, lp, now);
|
|
712
|
+
el.removeAttribute("integrity");
|
|
713
|
+
if (!el.hasAttribute("crossorigin")) el.setAttribute("crossorigin", "anonymous");
|
|
714
|
+
el[k] = url;
|
|
715
|
+
track(el, ps, url, js, null, !!x);
|
|
716
|
+
} catch (_) {
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const scanLive = (r) => {
|
|
720
|
+
try {
|
|
721
|
+
if (r.matches && r.matches(LS)) rewriteLive(r);
|
|
722
|
+
r.querySelectorAll(LS).forEach(rewriteLive);
|
|
723
|
+
} catch (_) {
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
function swapEl(sel, srcAttr, type) {
|
|
682
727
|
d.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
|
|
683
728
|
try {
|
|
684
|
-
el.setAttribute("data-stagepass-processed", "true");
|
|
685
729
|
let lp = el.getAttribute("data-stagepass-path");
|
|
686
730
|
const hadExplicitPath = !!lp;
|
|
687
731
|
const ps = el.getAttribute(srcAttr);
|
|
688
732
|
if (!ps) return;
|
|
733
|
+
el.setAttribute("data-stagepass-processed", "true");
|
|
689
734
|
if (!lp && swap && dom) lp = extractLocalFilename(ps);
|
|
690
|
-
if (swap && lp && !hadExplicitPath && hasActiveSession) {
|
|
691
|
-
const count = (seen.get(lp) || 0) + 1;
|
|
692
|
-
seen.set(lp, count);
|
|
693
|
-
if (count === 2) {
|
|
694
|
-
spWarn(
|
|
695
|
-
`Multiple assets resolve to local file "${lp}" without data-stagepass-path. Set unique paths to avoid collisions.`
|
|
696
|
-
);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
735
|
const url = resolveAssetUrl(el, ps, lp);
|
|
700
736
|
if (!url) return;
|
|
701
737
|
const local = swap && lp && dom;
|
|
@@ -709,12 +745,12 @@ var Stagepass = (() => {
|
|
|
709
745
|
n2.href = url;
|
|
710
746
|
}
|
|
711
747
|
for (const a of Array.from(el.attributes)) {
|
|
712
|
-
if (a.name !== srcAttr && !SKIP.includes(a.name) &&
|
|
748
|
+
if (a.name !== srcAttr && !SKIP.includes(a.name) && a.name !== (isScript ? "src" : "href"))
|
|
713
749
|
n2.setAttribute(a.name, a.value);
|
|
714
|
-
}
|
|
715
750
|
}
|
|
751
|
+
if (local) n2.removeAttribute("integrity");
|
|
716
752
|
if (isScript) applyScriptLoadOrder(n2, el);
|
|
717
|
-
if (local) track(n2, ps, url, isScript, cors ? make : null);
|
|
753
|
+
if (local) track(n2, ps, url, isScript, cors ? make : null, hadExplicitPath);
|
|
718
754
|
return n2;
|
|
719
755
|
};
|
|
720
756
|
const n = make(!!local && !el.hasAttribute("crossorigin"));
|
|
@@ -728,11 +764,35 @@ var Stagepass = (() => {
|
|
|
728
764
|
}
|
|
729
765
|
});
|
|
730
766
|
}
|
|
767
|
+
if (swap && liveSrc) {
|
|
768
|
+
try {
|
|
769
|
+
new MutationObserver((ms) => {
|
|
770
|
+
for (const m of ms) for (const n of m.addedNodes) if (n.nodeType === 1) scanLive(n);
|
|
771
|
+
}).observe(d.documentElement, { childList: true, subtree: true });
|
|
772
|
+
if (ff)
|
|
773
|
+
d.addEventListener(
|
|
774
|
+
"beforescriptexecute",
|
|
775
|
+
(e) => {
|
|
776
|
+
const el = e.target;
|
|
777
|
+
if (!el || !el.matches || !el.matches(LS)) return;
|
|
778
|
+
const ps = el.getAttribute("src");
|
|
779
|
+
if (!ps || ps.indexOf("https://" + dom + "/") === 0) return;
|
|
780
|
+
e.preventDefault();
|
|
781
|
+
el.setAttribute("data-src", ps);
|
|
782
|
+
el.removeAttribute("src");
|
|
783
|
+
swapEl("script[data-stagepass]", "data-src", "script");
|
|
784
|
+
},
|
|
785
|
+
true
|
|
786
|
+
);
|
|
787
|
+
scanLive(d);
|
|
788
|
+
} catch (_) {
|
|
789
|
+
}
|
|
790
|
+
}
|
|
731
791
|
const process = () => {
|
|
732
792
|
try {
|
|
733
|
-
|
|
734
|
-
swapEl("
|
|
735
|
-
|
|
793
|
+
swapEl("script[data-stagepass]", "data-src", "script");
|
|
794
|
+
swapEl('link[rel="stylesheet"][data-stagepass]', "data-href", "link");
|
|
795
|
+
if (swap && liveSrc) scanLive(d);
|
|
736
796
|
if (renderFlag) renderFlag();
|
|
737
797
|
} catch (_) {
|
|
738
798
|
}
|
package/dist/loader.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Stagepass=(()=>{function
|
|
2
|
-
`);for(let
|
|
1
|
+
var Stagepass=(()=>{function N(t){return typeof t!="string"||!t?!1:t==="debug"||t==="localhost"?!0:t.startsWith("localhost:")?(t=t.slice(10),/^[1-9]\d{0,4}$/.test(t)&&+t<65536):/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.sp$/i.test(t)}function se(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var Le="stagepass_domain",V=12;function $e(t,s=Date.now()){if(!t||!t.startsWith("{"))return null;try{let o=JSON.parse(t);return typeof o.domain!="string"||typeof o.expires!="number"||!Number.isFinite(o.expires)||!N(o.domain)||o.expires<=s?null:{domain:o.domain,expires:o.expires}}catch{return null}}function Oe(t,s=V,o=Date.now()){let c=Number.isFinite(s)&&s>0?s:V;return{domain:t,expires:o+c*60*60*1e3}}function Ie(t){return JSON.stringify(t)}function Re(t){if(t==null||t==="")return V;let s=Number(t);return!Number.isFinite(s)||s<=0?V:s}function oe(t,s,o){if(!t||typeof t!="string")return t;let c=encodeURIComponent(o),p=t.indexOf("#"),b=p>=0?t.slice(p):"",v=p>=0?t.slice(0,p):t;s==="_cb"&&(v=v.replace(/\?.*/,j=>j.replace(/[&?]_cb(=[^&]*)?(?=&|$)/g,"").replace(/^&/,"?")));let $=v.includes("?")?"&":"?";return`${v}${$}${encodeURIComponent(s)}=${c}${b}`}function q(t,s,o){let c=s.startsWith("/")?s.slice(1):s;return`https://${t}/${c}?_cb=${o}`}async function Ce(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let s=["loopback-network","local-network-access"];for(let o of s)try{let c=await t.query({name:o}),p=c&&c.state;if(p==="granted"||p==="prompt"||p==="denied")return p}catch{}return"unknown"}function ae(t){return t==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":t==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function Ne(t,s){let o=s.hasAttribute("async"),c=s.hasAttribute("defer");o?t.async=!0:(t.async=!1,c||(t.defer=!0))}var B="data-stagepass-nocache";function je(t){return t.hasAttribute(B)?t.getAttribute(B)!=="false":!1}function Fe(t){return!t||typeof t!="string"?[]:t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}function Te(t,s,o=[]){if(s&&s.endsWith(".sp"))return"local";let c=(t||"").toLowerCase();return c.endsWith(".webflow.io")||o.some(p=>p===c)?"staging":"production"}function Me(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function Pe(t,s){try{return typeof t[s]>"u"}catch{return!1}}var rt=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],st=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function ot(t){for(let[s,o]of rt){let c=t.match(o);if(c)return{family:s,major:Number(c[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function at(t){let s=st.find(([,o])=>o.test(t));return{family:s?s[0]:"unknown"}}function it(t){let s="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,o="desktop";return/iPad|Tablet/i.test(t)?o="tablet":/Mobi|Android.+Mobile|iPhone/i.test(t)?o="mobile":/Android/i.test(t)&&s&&(o="tablet"),{type:o,touch:s}}function ie(){let t=null;try{let s=o=>matchMedia(`(prefers-color-scheme: ${o})`).matches;t=s("dark")?"dark":s("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function De(t){try{let s=window[t],o="__stagepass_test__";return s.setItem(o,"1"),s.removeItem(o),!0}catch{return!1}}function ct(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function He(){let t=navigator.userAgent||"",s=null;try{s=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:ie(),browser:ot(t),os:at(t),device:it(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:s},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:De("localStorage"),sessionStorage:De("sessionStorage")}}}function We(t,s){let o=t.capabilities;switch(s){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return ct();default:return!1}}function ze(t){if(!t||typeof t!="string")return null;let s=t.trim().match(/^(\d+)/);if(!s)return null;let o=Number(s[1]);return Number.isFinite(o)?o:null}function Ue(t,s){let o=ze(t),c=new Map;function p(b,v,$,j){if(!b||typeof b!="string")return s("stagepass.use: invalid module name"),!1;let x=ze(v);if(o==null||x==null)return s(`stagepass.use: cannot parse version for module "${b}"`),!1;if(x!==o)return s(`Module "${b}" major ${x} does not match loader major ${o}. Skipping.`),!1;try{return $(j),c.set(b,v),!0}catch(k){return s(`Module "${b}" failed to register:`,k),!1}}return{use:p,registered:c}}(function(){let t=Le,s="stagepass",o=window,c=document,p=location,b="2.5.0",v=/loader(?:\.min)?\.js/i;function $(e,n){if(typeof e!="string"||!(e=e.trim()))return null;try{let r=new URL(e,c.baseURI);return!/^https?:$/.test(r.protocol)||r.username||r.password?null:(r.search=r.hash="",n?new URL("./",r).href:r.href.replace(/\/?$/,"/"))}catch{return null}}function j(){try{if(c.currentScript instanceof HTMLScriptElement)return c.currentScript}catch{}try{let e=c.querySelectorAll('script[src*="loader"]');for(let n=e.length-1;n>=0;n--)if(v.test(e[n].src||""))return e[n]}catch{}return null}let x=j(),k=e=>x?x.getAttribute("data-stagepass-"+e):null,Ve=k("mute-console")==="true",qe=Re(k("session-hours")),Be=k("version"),ce=Fe(k("staging-hosts")),O=k("alias"),le=k("live-src")==="true",H=new URLSearchParams(p.search),_=!1,A={n:[0,0],m:[],f:[],swapped:0,v:b,vd:N},F=null,ue=()=>F&&F(),fe=()=>new Date().toTimeString().slice(0,8),W=e=>(e||"").split(/[?#]/)[0].split("/").pop()||"",z=(e,n)=>e.length>n?e.slice(0,n)+"\u2026":e,de=(e,n=0)=>{try{if(typeof e=="string")return n?JSON.stringify(e):e;if(e instanceof Error)return e.name+": "+e.message;if(!e||typeof e!="object")return String(e);if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";let r=Array.isArray(e);if(n>2)return r?"[\u2026]":"{\u2026}";let i=Object.keys(e),a=i.slice(0,20).map(l=>(r?"":l+": ")+de(e[l],n+1));return i.length>20&&a.push("\u2026"),z(r?"["+a.join(", ")+"]":"{"+a.join(", ")+"}",1e3)}catch{return"[unserializable]"}},G=(e,n=0)=>{let r=(e||"").split(`
|
|
2
|
+
`);for(let i=n;i<r.length;i++){let a=r[i].match(/([a-z][\w+.-]*:\/\/[^\s()]+?):(\d+):(\d+)/i);if(a&&!v.test(W(a[1])))return[a[1],a[2],a[3]]}return null},h=null,Ge=e=>e?h&&!e.indexOf(`https://${h}/`)?"local":"live":"external",I=(e,n,r="",i="",a="",l="",u)=>{A.n[e]++;let f=A.m,m={type:e?"error":"warn",time:fe(),src:u||(r?Ge(r):""),file:W(r),url:r.split(/[?#]/)[0],line:i?String(i):"",col:a?String(a):"",text:z(n,500),stack:z(l,2e3),c:1},S=d=>d.type+d.text+d.url+d.line+d.col;for(let d=f.length-1;d>=0;d--)if(S(f[d])===S(m)){m.c=f[d].c+1,f.splice(d,1);break}f.push(m),f.length>50&&f.shift(),ue()},J=(e,n,r,i)=>{let a=r.find(f=>f instanceof Error),l=a&&a.stack||"",u=G(l)||i;I(e,n+r.map(f=>de(f)).join(" "),u?u[0]:"",u?u[1]:"",u?u[2]:"",l)},T=!1,Je=e=>{T=!0;try{e()}catch{}T=!1};function R(e,...n){if(!_)return;let r=G(new Error().stack||"",3);(e==="warn"||e==="error")&&J(e==="warn"?0:1,"",n,r),Je(()=>{let i=`[\u{1F3AB} ${fe()}${r?" | "+W(r[0])+":"+r[1]:""}]`,a=console;e==="error"?a.log(`%c${i}`,"color:red;font-weight:bold",...n):a[e]?a[e](i,...n):a.log(i,e,...n)})}function Ke(...e){let n=e[0]==="warn"||e[0]==="error"?e.shift():"log";R(n,...e)}let M=(...e)=>R("warn",...e),pe=(...e)=>R("error",...e),K=(e,n)=>{let r=_;_=!0,R(e,n),_=r};function Ze(){try{let e=localStorage.getItem(t),n=$e(e);return!n&&e&&localStorage.removeItem(t),n?n.domain:null}catch{return null}}function Z(){try{localStorage.removeItem(t)}catch{}}let ge=!1,y=Ze();if(H.has(s)){let e=H.get(s);if(e==="off"||e==="0"||e==="false")Z(),y=null,K("log","\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":se(e);if(n&&N(n)){try{localStorage.setItem(t,Ie(Oe(n,qe)))}catch{}y=n,ge=!0,K("log",n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`)}else n&&K("warn",`Invalid domain: ${n}. Only .sp domains are allowed.`)}try{H.delete(s);let n=H.toString();history.replaceState({},"",p.pathname+(n?`?${n}`:"")+p.hash)}catch{}}y&&!N(y)&&(Z(),y=null);let P=y==="debug";_=!!y,y&&!ge&&!P&&R("log",`\u{1F50C} Stagepass connected to: ${y}`);let me=!!y,w=me&&!P;h=w?se(y):null;let Q=w?Date.now():0,L=p.hostname,Qe=L==="localhost"||L==="127.0.0.1"||L.startsWith("localhost:")||L.startsWith("127.0.0.1:"),he=w||Qe,be=he?"local":L.endsWith(".webflow.io")||ce.includes(L.toLowerCase())?"staging":"production";if(Ve&&be==="production"&&!_)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let ye={theme:new Set,session:new Set},Y=(e,n)=>ye[e].forEach(r=>{try{r(n)}catch{}}),C=He();try{let e=()=>Y("theme",{...Object.assign(C.theme,ie())});["dark","light"].forEach(n=>{let r=matchMedia(`(prefers-color-scheme: ${n})`);r.addEventListener?r.addEventListener("change",e):r.addListener&&r.addListener(e)})}catch{}o.addEventListener("resize",()=>{let e=C.viewport;e.width=o.innerWidth||0,e.height=o.innerHeight||0,e.dpr=o.devicePixelRatio||1});let g=o.stagepass||{},Ye=Ue(b,M),Se=Object.freeze({isLocal:he,env:be,domain:h||L,timestamp:Q,version:b,client:C});if(g.vars=Se,g.log=Ke,g.warn=M,g.error=pe,g.resolveLocalUrl=e=>w&&h&&e?q(h,e,Se.timestamp||Date.now()):"",g.env=()=>Te(L,h,ce),g.is=e=>g.env()===e,g.can=e=>We(C,e),g.client=e=>e==null||e===""?C:C[e],g.on=(e,n)=>{let r=ye[e];return!r||e!=="theme"&&e!=="session"?()=>{}:(r.add(n),()=>{r.delete(n)})},g.use=(e,n,r)=>Ye.use(e,n,r,g),o.stagepass=o.sp=g,globalThis.stagepass=globalThis.sp=g,O&&Me(O)&&O!=="sp"&&O!=="stagepass"&&[o,globalThis].forEach(e=>{Pe(e,O)&&(e[O]=g)}),me)try{let e=Symbol.for("stagepass.flag.v2"),n=k("flag-base")??o.stagepassFlagBase,r=$(n,!1);n!=null&&!r&&M("Ignored flag base (http(s) or relative only): "+z(String(n),99)),r=r||$(x&&x.src||"",!0),r||(r=`https://cdn.jsdelivr.net/npm/@stagepass/loader@${b}/dist/`,P&&M("Loader URL unknown, flag loads from "+r+". Set data-stagepass-flag-base")),Object.assign(A,{debug:P,domain:h,card:r+"flag-card.min.js",end:()=>{Z(),_=!0,R("log","\u{1F50C} Stagepass disconnected."),Y("session",{active:!1,domain:null,swap:!1,debug:!1}),p.reload()}}),Object.defineProperty(g,e,{configurable:!0,value:l=>{delete g[e];try{F=l(A)}catch{}}}),o.addEventListener("error",l=>{let u=l.target,f=u&&u!==o&&(u.src||u.href);typeof f=="string"?ve.has(u)||I(1,"Failed to load "+f.split(/[?#]/)[0],f):/^Script error\.?$/.test(l.message||"")&&!l.filename?I(1,"Error in a cross-origin script (details only in DevTools console)","","","","","external"):I(1,l.message||"Script error",l.filename||"",l.lineno,l.colno,l.error&&l.error.stack||"")},!0),o.addEventListener("unhandledrejection",l=>J(1,"Unhandled rejection: ",[l.reason],null));let i=console;["warn","error"].forEach((l,u)=>{let f=i[l];typeof f=="function"&&(i[l]=function(...m){if(!T){T=!0;try{J(u,"",m,G(new Error().stack||"",2))}catch{}T=!1}return f.apply(this,m)})});let a=c.createElement("script");a.src=r+"flag.min.js",a.async=!0,a.onerror=()=>M("Stagepass flag could not be loaded: "+a.src),(c.head||c.documentElement).appendChild(a)}catch{}Y("session",{active:_,domain:y,swap:w,debug:P});function Xe(e,n,r){if(w&&r&&h)return q(h,r,Q);let i=e.getAttribute("data-stagepass-v")||Be,a=i?oe(n,"v",i):n;return je(e)&&(a=oe(a,"_cb",Date.now())),a}function we(e){try{let n=new URL(e).pathname.split("/");return n[n.length-1]||n[n.length-2]||null}catch{let r=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return r?r[1]:null}}let ve=new WeakSet,X="";function ke(e,n,r,i,a,l){let u={live:n,local:r,type:i?"js":"css",st:""};l&&(u.x=!0);let f=W(r);ve.add(e),A.f.push(u),e.addEventListener("load",()=>{u.st="ok",A.swapped++,ue()}),e.addEventListener("error",()=>{let m=(d,re,U)=>{u.st=d,I(re,U,r)},S=o.fetch;if(typeof S!="function")return m("failed",1,`Failed to load ${f}`);S(r,{method:"HEAD",cache:"no-store"}).then(d=>m(d.ok?"failed":String(d.status),1,d.ok?`Failed to load ${f}`:`Local file not found (${d.status}): ${f}`),()=>S(r,{method:"HEAD",mode:"no-cors",cache:"no-store"}).then(()=>{if(!a)return m("failed",1,`Failed to load ${f}`);A.f.splice(A.f.indexOf(u),1),e.replaceWith(a(!1)),I(0,`Local server sends no CORS header for ${f}. Loaded without crossorigin, error details are limited`,r)},()=>m("failed",1,`Local server not reachable: ${f}. Run stagepass doctor`+(ae(X)?". "+ae(X):""))))})}let et=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v",B],ee='script[data-stagepass][src]:not([data-src]):not([data-stagepass-processed]),link[rel="stylesheet" i][data-stagepass][href]:not([data-href]):not([data-stagepass-processed])',Ee="onbeforescriptexecute"in c;function xe(e){try{let n=e.tagName==="SCRIPT";if(n&&(Ee||c.currentScript===e))return;let r=n?"src":"href",i=e.getAttribute(r);if(!i)return;e.setAttribute("data-stagepass-processed","true");let a=e.getAttribute("data-stagepass-path"),l=a||we(i);if(!l)return;let u=q(h,l,Q);e.removeAttribute("integrity"),e.hasAttribute("crossorigin")||e.setAttribute("crossorigin","anonymous"),e[r]=u,ke(e,i,u,n,null,!!a)}catch{}}let te=e=>{try{e.matches&&e.matches(ee)&&xe(e),e.querySelectorAll(ee).forEach(xe)}catch{}};function ne(e,n,r){c.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(i=>{try{let a=i.getAttribute("data-stagepass-path"),l=!!a,u=i.getAttribute(n);if(!u)return;i.setAttribute("data-stagepass-processed","true"),!a&&w&&h&&(a=we(u));let f=Xe(i,u,a);if(!f)return;let m=w&&a&&h,S=r==="script",d=U=>{let E=c.createElement(r);U&&(E.crossOrigin="anonymous"),S?E.src=f:(E.rel="stylesheet",E.href=f);for(let D of Array.from(i.attributes))D.name!==n&&!et.includes(D.name)&&D.name!==(S?"src":"href")&&E.setAttribute(D.name,D.value);return m&&E.removeAttribute("integrity"),S&&Ne(E,i),m&&ke(E,u,f,S,U?d:null,l),E},re=d(!!m&&!i.hasAttribute("crossorigin"));i.parentNode?(i.parentNode.insertBefore(re,i),i.remove()):pe(`${r} injection failed: No parent node`)}catch{}})}if(w&&le)try{new MutationObserver(e=>{for(let n of e)for(let r of n.addedNodes)r.nodeType===1&&te(r)}).observe(c.documentElement,{childList:!0,subtree:!0}),Ee&&c.addEventListener("beforescriptexecute",e=>{let n=e.target;if(!n||!n.matches||!n.matches(ee))return;let r=n.getAttribute("src");!r||r.indexOf("https://"+h+"/")===0||(e.preventDefault(),n.setAttribute("data-src",r),n.removeAttribute("src"),ne("script[data-stagepass]","data-src","script"))},!0),te(c)}catch{}let tt=()=>{try{ne("script[data-stagepass]","data-src","script"),ne('link[rel="stylesheet"][data-stagepass]',"data-href","link"),w&&le&&te(c),F&&F()}catch{}},_e=null,nt=()=>_e=_e||(w?Ce().then(e=>{X=e}).catch(()=>{}):Promise.resolve()),Ae=()=>{nt().then(tt)};Ae(),c.readyState==="loading"&&c.addEventListener("DOMContentLoaded",Ae)})();})();
|
package/global.d.ts
CHANGED
|
@@ -105,6 +105,8 @@ export type StagepassModuleFactory = (api: StagepassAPI) => void;
|
|
|
105
105
|
export interface StagepassAPI {
|
|
106
106
|
/**
|
|
107
107
|
* Frozen runtime variables.
|
|
108
|
+
* Prefer flat helpers (`env` / `is` / `can` / `client` / `on`) for new code.
|
|
109
|
+
* In `?stagepass=debug`, the first read logs a one-time hint toward those helpers.
|
|
108
110
|
* @example
|
|
109
111
|
* if (sp.vars.isLocal) sp.log('local session on', sp.vars.domain);
|
|
110
112
|
*/
|