@stagepass/loader 1.0.2 → 1.1.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/dist/loader.js CHANGED
@@ -3,40 +3,45 @@ var Stagepass = (() => {
3
3
  (function() {
4
4
  const K = "stagepass_domain";
5
5
  const P = "stagepass";
6
- function isValidDomain(d) {
7
- return d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
8
- }
6
+ const isValidDomain = (d) => d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
9
7
  const p = new URLSearchParams(window.location.search);
10
- const svCheck = localStorage.getItem(K);
11
- const hasValidSession = svCheck && isValidDomain(svCheck);
12
- const hasParam = p.has(P);
13
- if (!hasValidSession && !hasParam) {
14
- const noop = () => {
15
- };
16
- console.log = noop;
17
- console.warn = noop;
18
- console.error = noop;
19
- console.info = noop;
20
- console.debug = noop;
8
+ const loaderScript = document.querySelector('script[src*="loader"]');
9
+ let modulesParam = null;
10
+ let silentParam = null;
11
+ if (loaderScript && loaderScript.src) {
12
+ try {
13
+ const scriptUrl = new URL(loaderScript.src);
14
+ modulesParam = scriptUrl.searchParams.get("modules");
15
+ silentParam = scriptUrl.searchParams.get("silent");
16
+ } catch (e) {
17
+ const modulesMatch = loaderScript.src.match(/[?&]modules(=([^&]*))?/);
18
+ if (modulesMatch) {
19
+ modulesParam = modulesMatch[2] !== void 0 ? modulesMatch[2] : "";
20
+ }
21
+ const silentMatch = loaderScript.src.match(/[?&]silent/);
22
+ if (silentMatch) {
23
+ silentParam = "";
24
+ }
25
+ }
21
26
  }
22
27
  function log(level, ...args) {
23
28
  var _a;
24
29
  const v = localStorage.getItem(K);
25
- if (!v || v !== "debug" && !v) return;
30
+ if (!v) return;
26
31
  const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
27
- let c = "unknown";
32
+ let c = "";
28
33
  try {
29
34
  const s = (_a = new Error().stack) == null ? void 0 : _a.split("\n");
30
35
  if (s) {
31
36
  const l = s.find((x, i) => i > 2 && !x.includes("log"));
32
37
  if (l) {
33
- const m = l.match(/(\/?([^\/\?:]+))(\?[^\s)]*)?:([0-9]+):[0-9]+/);
34
- if (m) c = `${m[2]}:${m[4]}`;
38
+ const m = l.match(/:([0-9]+):/);
39
+ if (m) c = `:${m[1]}`;
35
40
  }
36
41
  }
37
42
  } catch (e) {
38
43
  }
39
- const pre = `[\u{1F3AB} ${t} \u{1F4CD} ${c}]`;
44
+ const pre = `[\u{1F3AB} ${t}${c ? " \u{1F4CD}" + c : ""}]`;
40
45
  if (level === "error") {
41
46
  console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
42
47
  } else if (console[level]) {
@@ -51,22 +56,23 @@ var Stagepass = (() => {
51
56
  window.splog = splog;
52
57
  window.spwarn = spwarn;
53
58
  window.sperror = sperror;
54
- function clean(d) {
55
- return d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
56
- }
59
+ const clean = (d) => d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
57
60
  let paramProcessed = false;
61
+ let sv = localStorage.getItem(K);
58
62
  if (p.has(P)) {
59
63
  const v = p.get(P);
60
64
  if (v === "off" || v === "0" || v === "false") {
61
65
  localStorage.removeItem(K);
66
+ sv = null;
62
67
  splog("\u{1F50C} Stagepass disconnected.");
63
68
  } else if (v) {
64
69
  const c = v === "debug" ? "debug" : clean(v);
65
70
  if (c && isValidDomain(c)) {
66
71
  localStorage.setItem(K, c);
72
+ sv = c;
67
73
  splog(c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`);
68
74
  paramProcessed = true;
69
- } else if (c && !isValidDomain(c)) {
75
+ } else if (c) {
70
76
  spwarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
71
77
  }
72
78
  }
@@ -74,7 +80,6 @@ var Stagepass = (() => {
74
80
  const s = p.toString();
75
81
  window.history.replaceState({}, "", window.location.pathname + (s ? `?${s}` : "") + window.location.hash);
76
82
  }
77
- let sv = localStorage.getItem(K);
78
83
  if (sv && !isValidDomain(sv)) {
79
84
  localStorage.removeItem(K);
80
85
  sv = null;
@@ -85,10 +90,32 @@ var Stagepass = (() => {
85
90
  const dev = !!sv;
86
91
  const swap = !!sv && sv !== "debug";
87
92
  const dom = swap ? clean(sv) : null;
88
- const cacheBust = swap ? Date.now() : 0;
93
+ const now = swap ? Date.now() : 0;
94
+ const cacheBust = now;
95
+ const sessionStartTime = now;
96
+ const hostname = window.location.hostname;
97
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
98
+ const isLocal = swap || isLocalhost;
99
+ const env = isLocal ? "local" : hostname.endsWith(".webflow.io") ? "staging" : "production";
100
+ const hasValidSession = sv && isValidDomain(sv);
101
+ const shouldSuppress = !hasValidSession && !p.has(P);
102
+ if (shouldSuppress && (env === "production" || env === "staging" && silentParam !== null)) {
103
+ const noop = () => {
104
+ };
105
+ console.log = console.warn = console.error = console.info = console.debug = noop;
106
+ }
107
+ const stagepassObj = window.stagepass || {};
108
+ stagepassObj.vars = Object.freeze({
109
+ isLocal,
110
+ env,
111
+ domain: dom || hostname,
112
+ timestamp: sessionStartTime,
113
+ version: "1.1.0"
114
+ });
115
+ window.stagepass = stagepassObj;
116
+ globalThis.stagepass = stagepassObj;
89
117
  function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
90
- const els = document.querySelectorAll(`${sel}:not([data-stagepass-processed])`);
91
- els.forEach((el) => {
118
+ document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
92
119
  el.setAttribute("data-stagepass-processed", "true");
93
120
  let lp = el.getAttribute(pathAttr);
94
121
  const ps = el.getAttribute(srcAttr);
@@ -103,45 +130,63 @@ var Stagepass = (() => {
103
130
  if (match) lp = match[1];
104
131
  }
105
132
  }
106
- let url = "";
107
- if (swap && lp && dom) {
108
- const cp = lp.startsWith("/") ? lp.substring(1) : lp;
109
- url = `https://${dom}/${cp}?_cb=${cacheBust}`;
110
- } else if (ps) {
111
- url = ps;
133
+ const url = swap && lp && dom ? `https://${dom}/${lp.startsWith("/") ? lp.substring(1) : lp}?_cb=${cacheBust}` : ps;
134
+ if (!url) return;
135
+ const n = document.createElement(type);
136
+ if (type === "script") {
137
+ n.src = url;
138
+ Array.from(el.attributes).forEach((a) => {
139
+ const attr = a;
140
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
141
+ });
142
+ if (!el.hasAttribute("async") && !el.hasAttribute("defer")) n.setAttribute("defer", "");
143
+ } else {
144
+ n.rel = "stylesheet";
145
+ n.href = url;
146
+ Array.from(el.attributes).forEach((a) => {
147
+ const attr = a;
148
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
149
+ });
112
150
  }
113
- if (url) {
114
- const n = document.createElement(type);
115
- if (type === "script") {
116
- n.src = url;
117
- Array.from(el.attributes).forEach((a) => {
118
- const attr = a;
119
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
120
- });
121
- if (!el.hasAttribute("async") && !el.hasAttribute("defer")) {
122
- n.setAttribute("defer", "");
123
- }
124
- } else {
125
- n.rel = "stylesheet";
126
- n.href = url;
127
- Array.from(el.attributes).forEach((a) => {
128
- const attr = a;
129
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
130
- });
131
- }
132
- if (el.parentNode) {
133
- el.parentNode.insertBefore(n, el);
134
- el.remove();
135
- } else {
136
- sperror(`${type} injection failed: No parent node`);
137
- }
151
+ if (el.parentNode) {
152
+ el.parentNode.insertBefore(n, el);
153
+ el.remove();
154
+ } else {
155
+ sperror(`${type} injection failed: No parent node`);
138
156
  }
139
157
  });
140
158
  }
141
- function process() {
159
+ function loadModules() {
160
+ if (modulesParam === null) return;
161
+ const modulesToLoad = modulesParam === "" ? ["all"] : modulesParam.split(",").map((m) => m.trim()).filter(Boolean);
162
+ if (modulesToLoad.length === 0) return;
163
+ let baseUrl = window.location.origin;
164
+ if (loaderScript && loaderScript.src) {
165
+ try {
166
+ const scriptUrl = new URL(loaderScript.src);
167
+ const pathParts = scriptUrl.pathname.split("/");
168
+ pathParts.pop();
169
+ baseUrl = `${scriptUrl.origin}${pathParts.join("/")}`;
170
+ } catch (e) {
171
+ baseUrl = loaderScript.src.replace(/\/[^\/\?]+(\?.*)?$/, "");
172
+ }
173
+ }
174
+ modulesToLoad.forEach((moduleName) => {
175
+ const moduleUrl = `${baseUrl}/${moduleName}.min.js`;
176
+ const script = document.createElement("script");
177
+ script.src = moduleUrl;
178
+ script.async = true;
179
+ document.head.appendChild(script);
180
+ if (env !== "production") {
181
+ splog(`\u{1F4E6} Loading module: ${moduleName}`);
182
+ }
183
+ });
184
+ }
185
+ const process = () => {
142
186
  swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", ["data-src", "data-stagepass", "data-stagepass-path"]);
143
187
  swapEl('link[rel="stylesheet"][data-stagepass]', "data-stagepass-path", "data-href", "link", ["href", "data-href", "data-stagepass", "data-stagepass-path"]);
144
- }
188
+ };
189
+ loadModules();
145
190
  process();
146
191
  if (document.readyState === "loading") {
147
192
  document.addEventListener("DOMContentLoaded", process);
@@ -151,7 +196,7 @@ var Stagepass = (() => {
151
196
  const f = document.createElement("div");
152
197
  f.id = "stagepass-flag";
153
198
  f.textContent = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
154
- f.style.cssText = `font-size: 12px; line-height: 1; font-weight: bold; color: #fff; background-color: #D92662; padding: 4px 6px; z-index: 9999999999; position: fixed; top: 0; right: 0; cursor: pointer; border-radius: 0 0 0 4px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; user-select: none;`;
199
+ f.style.cssText = 'font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;';
155
200
  f.addEventListener("click", () => {
156
201
  localStorage.removeItem(K);
157
202
  splog("\u{1F50C} Stagepass disconnected.");
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{(function(){let d="stagepass_domain",h="stagepass";function b(t){return t==="debug"||t.endsWith(".sp")||t==="localhost"||t.startsWith("localhost:")}let f=new URLSearchParams(window.location.search),A=localStorage.getItem(d),D=A&&b(A),T=f.has(h);if(!D&&!T){let t=()=>{};console.log=t,console.warn=t,console.error=t,console.info=t,console.debug=t}function y(t,...l){var s;let e=localStorage.getItem(d);if(!e||e!=="debug"&&!e)return;let u=new Date().toTimeString().split(" ")[0],m="unknown";try{let a=(s=new Error().stack)==null?void 0:s.split(`
2
- `);if(a){let i=a.find((r,n)=>n>2&&!r.includes("log"));if(i){let r=i.match(/(\/?([^\/\?:]+))(\?[^\s)]*)?:([0-9]+):[0-9]+/);r&&(m=`${r[2]}:${r[4]}`)}}}catch{}let S=`[\u{1F3AB} ${u} \u{1F4CD} ${m}]`;t==="error"?console.log(`%c${S}`,"color: red; font-weight: bold;",...l):console[t]?console[t](S,...l):console.log(S,t,...l)}let g=(...t)=>y("log",...t),$=(...t)=>y("warn",...t),v=(...t)=>y("error",...t);window.splog=g,window.spwarn=$,window.sperror=v;function L(t){return t?t.replace(/^https?:\/\//,"").replace(/\/$/,""):null}let k=!1;if(f.has(h)){let t=f.get(h);if(t==="off"||t==="0"||t==="false")localStorage.removeItem(d),g("\u{1F50C} Stagepass disconnected.");else if(t){let e=t==="debug"?"debug":L(t);e&&b(e)?(localStorage.setItem(d,e),g(e==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${e}`),k=!0):e&&!b(e)&&$(`Invalid domain: ${e}. Only .sp domains are allowed.`)}f.delete(h);let l=f.toString();window.history.replaceState({},"",window.location.pathname+(l?`?${l}`:"")+window.location.hash)}let o=localStorage.getItem(d);o&&!b(o)&&(localStorage.removeItem(d),o=null),o&&!k&&o!=="debug"&&g(`\u{1F50C} Stagepass connected to: ${o}`);let M=!!o,w=!!o&&o!=="debug",E=w?L(o):null,P=w?Date.now():0;function C(t,l,e,u,m){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(s=>{s.setAttribute("data-stagepass-processed","true");let a=s.getAttribute(l),i=s.getAttribute(e);if(!i)return;if(!a&&i&&w&&E)try{let c=new URL(i).pathname.split("/");a=c[c.length-1]||c[c.length-2]}catch{let c=i.match(/\/([^\/\?#]+)(?:\?|#|$)/);c&&(a=c[1])}let r="";if(w&&a&&E){let n=a.startsWith("/")?a.substring(1):a;r=`https://${E}/${n}?_cb=${P}`}else i&&(r=i);if(r){let n=document.createElement(u);u==="script"?(n.src=r,Array.from(s.attributes).forEach(c=>{let p=c;m.includes(p.name)||n.setAttribute(p.name,p.value)}),!s.hasAttribute("async")&&!s.hasAttribute("defer")&&n.setAttribute("defer","")):(n.rel="stylesheet",n.href=r,Array.from(s.attributes).forEach(c=>{let p=c;m.includes(p.name)||n.setAttribute(p.name,p.value)})),s.parentNode?(s.parentNode.insertBefore(n,s),s.remove()):v(`${u} injection failed: No parent node`)}})}function I(){C("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path"]),C('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path"])}I(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",I);function x(){if(!M)return;let t=document.createElement("div");t.id="stagepass-flag",t.textContent=o==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",t.style.cssText='font-size: 12px; line-height: 1; font-weight: bold; color: #fff; background-color: #D92662; padding: 4px 6px; z-index: 9999999999; position: fixed; top: 0; right: 0; cursor: pointer; border-radius: 0 0 0 4px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; user-select: none;',t.addEventListener("click",()=>{localStorage.removeItem(d),g("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(t):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",x):x()})();})();
1
+ var Stagepass=(()=>{(function(){let g="stagepass_domain",y="stagepass",$=t=>t==="debug"||t.endsWith(".sp")||t==="localhost"||t.startsWith("localhost:"),w=new URLSearchParams(window.location.search),d=document.querySelector('script[src*="loader"]'),b=null,v=null;if(d&&d.src)try{let t=new URL(d.src);b=t.searchParams.get("modules"),v=t.searchParams.get("silent")}catch{let s=d.src.match(/[?&]modules(=([^&]*))?/);s&&(b=s[2]!==void 0?s[2]:""),d.src.match(/[?&]silent/)&&(v="")}function A(t,...s){var l;if(!localStorage.getItem(g))return;let c=new Date().toTimeString().split(" ")[0],i="";try{let p=(l=new Error().stack)==null?void 0:l.split(`
2
+ `);if(p){let h=p.find((r,u)=>u>2&&!r.includes("log"));if(h){let r=h.match(/:([0-9]+):/);r&&(i=`:${r[1]}`)}}}catch{}let o=`[\u{1F3AB} ${c}${i?" \u{1F4CD}"+i:""}]`;t==="error"?console.log(`%c${o}`,"color: red; font-weight: bold;",...s):console[t]?console[t](o,...s):console.log(o,t,...s)}let f=(...t)=>A("log",...t),T=(...t)=>A("warn",...t),P=(...t)=>A("error",...t);window.splog=f,window.spwarn=T,window.sperror=P;let k=t=>t?t.replace(/^https?:\/\//,"").replace(/\/$/,""):null,C=!1,n=localStorage.getItem(g);if(w.has(y)){let t=w.get(y);if(t==="off"||t==="0"||t==="false")localStorage.removeItem(g),n=null,f("\u{1F50C} Stagepass disconnected.");else if(t){let e=t==="debug"?"debug":k(t);e&&$(e)?(localStorage.setItem(g,e),n=e,f(e==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${e}`),C=!0):e&&T(`Invalid domain: ${e}. Only .sp domains are allowed.`)}w.delete(y);let s=w.toString();window.history.replaceState({},"",window.location.pathname+(s?`?${s}`:"")+window.location.hash)}n&&!$(n)&&(localStorage.removeItem(g),n=null),n&&!C&&n!=="debug"&&f(`\u{1F50C} Stagepass connected to: ${n}`);let j=!!n,S=!!n&&n!=="debug",E=S?k(n):null,U=S?Date.now():0,W=U,B=U,m=window.location.hostname,R=m==="localhost"||m==="127.0.0.1"||m.startsWith("localhost:")||m.startsWith("127.0.0.1:"),I=S||R,L=I?"local":m.endsWith(".webflow.io")?"staging":"production";!(n&&$(n))&&!w.has(y)&&(L==="production"||L==="staging"&&v!==null)&&(console.log=console.warn=console.error=console.info=console.debug=()=>{});let M=window.stagepass||{};M.vars=Object.freeze({isLocal:I,env:L,domain:E||m,timestamp:B,version:"1.1.0"}),window.stagepass=M,globalThis.stagepass=M;function x(t,s,e,c,i){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(o=>{o.setAttribute("data-stagepass-processed","true");let l=o.getAttribute(s),p=o.getAttribute(e);if(!p)return;if(!l&&p&&S&&E)try{let a=new URL(p).pathname.split("/");l=a[a.length-1]||a[a.length-2]}catch{let a=p.match(/\/([^\/\?#]+)(?:\?|#|$)/);a&&(l=a[1])}let h=S&&l&&E?`https://${E}/${l.startsWith("/")?l.substring(1):l}?_cb=${W}`:p;if(!h)return;let r=document.createElement(c);c==="script"?(r.src=h,Array.from(o.attributes).forEach(u=>{let a=u;i.includes(a.name)||r.setAttribute(a.name,a.value)}),!o.hasAttribute("async")&&!o.hasAttribute("defer")&&r.setAttribute("defer","")):(r.rel="stylesheet",r.href=h,Array.from(o.attributes).forEach(u=>{let a=u;i.includes(a.name)||r.setAttribute(a.name,a.value)})),o.parentNode?(o.parentNode.insertBefore(r,o),o.remove()):P(`${c} injection failed: No parent node`)})}function H(){if(b===null)return;let t=b===""?["all"]:b.split(",").map(e=>e.trim()).filter(Boolean);if(t.length===0)return;let s=window.location.origin;if(d&&d.src)try{let e=new URL(d.src),c=e.pathname.split("/");c.pop(),s=`${e.origin}${c.join("/")}`}catch{s=d.src.replace(/\/[^\/\?]+(\?.*)?$/,"")}t.forEach(e=>{let c=`${s}/${e}.min.js`,i=document.createElement("script");i.src=c,i.async=!0,document.head.appendChild(i),L!=="production"&&f(`\u{1F4E6} Loading module: ${e}`)})}let D=()=>{x("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path"]),x('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path"])};H(),D(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",D);function O(){if(!j)return;let t=document.createElement("div");t.id="stagepass-flag",t.textContent=n==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",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",()=>{localStorage.removeItem(g),f("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(t):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O()})();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Universal loader for Stagepass - injects local files into Webflow projects",
5
5
  "main": "dist/loader.min.js",
6
6
  "type": "module",