@stagepass/modules 1.0.6 → 2.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Herz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # `@stagepass/modules`
2
+
3
+ Modular runtime extensions for Stagepass.
4
+
5
+ This package provides optional browser modules that extend `@stagepass/loader`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @stagepass/loader@2.0.0 @stagepass/modules@2.0.0
11
+ ```
12
+
13
+ `@stagepass/loader` must be loaded first.
14
+ `@stagepass/modules` declares `@stagepass/loader` as a peer dependency (`>=2.0.0`).
15
+
16
+ ## CDN Usage
17
+
18
+ Pin exact versions in production (jsDelivr preferred; unpkg works the same path layout):
19
+
20
+ ```html
21
+ <script
22
+ src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2.0.0/dist/loader.min.js"
23
+ data-stagepass-version="2.0.0"
24
+ ></script>
25
+ <script src="https://cdn.jsdelivr.net/npm/@stagepass/modules@2.0.0/dist/inject.min.js"></script>
26
+ <script src="https://cdn.jsdelivr.net/npm/@stagepass/modules@2.0.0/dist/cookies.min.js"></script>
27
+ ```
28
+
29
+ Or load all modules:
30
+
31
+ ```html
32
+ <script src="https://cdn.jsdelivr.net/npm/@stagepass/loader@2.0.0/dist/loader.min.js"></script>
33
+ <script src="https://cdn.jsdelivr.net/npm/@stagepass/modules@2.0.0/dist/all.min.js"></script>
34
+ ```
35
+
36
+ Published files: `dist/inject.min.js`, `dist/cookies.min.js`, `dist/all.min.js`.
37
+
38
+ ## Available Modules
39
+
40
+ ### Injector (`inject.min.js`)
41
+
42
+ Registers `sp.inject` (also `stagepass.inject`). Accepts a single options object, an array, or `{ scripts, styles }`.
43
+
44
+ ```js
45
+ await sp.inject({
46
+ src: 'https://cdn.example.com/lib.js',
47
+ stagepass: true,
48
+ localPath: 'lib.js', // alias: path
49
+ id: 'my-library',
50
+ type: 'script', // or 'style'; auto-detected from .css
51
+ version: '2.0.0', // production ?v=<version>
52
+ async: false, // default false (keeps order)
53
+ defer: true, // default true unless async is true
54
+ position: 'head', // 'head' | 'body-start' | 'body-end' | { target, action }
55
+ attributes: { crossorigin: 'anonymous' },
56
+ });
57
+
58
+ await sp.inject([
59
+ { src: 'https://cdn.example.com/a.js', stagepass: true, path: 'a.js', version: '2.0.0' },
60
+ { src: 'https://cdn.example.com/b.css', stagepass: true, localPath: 'b.css', type: 'style', version: '2.0.0' },
61
+ ]);
62
+
63
+ await sp.inject({
64
+ scripts: [{ src: 'https://cdn.example.com/a.js', stagepass: true, localPath: 'a.js' }],
65
+ styles: [{ src: 'https://cdn.example.com/b.css', stagepass: true, localPath: 'b.css' }],
66
+ });
67
+ ```
68
+
69
+ **Options**
70
+
71
+ | Field | Description |
72
+ | :--- | :--- |
73
+ | `src` | Required production URL. |
74
+ | `type` | `'script'` \| `'style'` (default: `.css` → style, else script). |
75
+ | `stagepass` | When not `false` and `sp.vars.isLocal`, resolve a local URL via `sp.resolveLocalUrl` (fallback `https://<domain>/<path>?_cb=<timestamp>`). |
76
+ | `localPath` / `path` | Local path under the linked root (default: filename from `src`). |
77
+ | `id` | Element id; skips inject if already present. |
78
+ | `async` | If `true`, set `script.async = true`; otherwise `async = false` and keep order. |
79
+ | `defer` | Default `true` when not async; set `false` to omit defer. |
80
+ | `version` | Production cache bust: append `?v=<version>` (URL-encoded). |
81
+ | `cacheBust` | Deprecated; does **not** append per-view timestamps in v2 production. Prefer `version`. |
82
+ | `attributes` | Extra HTML attributes on the created element. |
83
+ | `position` | `'head'` \| `'body-start'` \| `'body-end'` (default) \| `{ target: cssSelector, action: 'before' \| 'after' }`. |
84
+
85
+ Deduplication: skips when `id` already exists or a matching `script[src]` / `link[href]` is present. Failed items log in non-production and do not abort the rest of a batch.
86
+
87
+ ### Cookies (`cookies.min.js`)
88
+
89
+ Registers `sp.cookies` (also `stagepass.cookies`). Cookie helpers only, **not** a consent manager.
90
+
91
+ ```js
92
+ sp.cookies.bake('token', 'abc123', { days: 7, path: '/' });
93
+ sp.cookies.eat('token'); // 'abc123'
94
+ sp.cookies.has('token'); // true
95
+ sp.cookies.list(); // { token: 'abc123', ... }
96
+ sp.cookies.throw('token', { path: '/' });
97
+
98
+ sp.cookies.bake('profile', { id: 7, role: 'editor' }, { json: true, days: 30 });
99
+ sp.cookies.eat('profile', { json: true });
100
+ ```
101
+
102
+ | Method | Description |
103
+ | :--- | :--- |
104
+ | `bake(name, value, options?)` | Write/update a cookie. |
105
+ | `eat(name, options?)` | Read a cookie; `null` if missing. |
106
+ | `throw(name, options?)` | Delete via `Max-Age=0` + expired date. |
107
+ | `has(name)` | Existence check. |
108
+ | `list(options?)` | All visible cookies as a name → value map. |
109
+
110
+ **`bake` options:** `days?`, `maxAge?` (seconds), `path?` (default `/`), `domain?`, `secure?` (default `true` on HTTPS), `sameSite?` (`'Lax'` \| `'Strict'` \| `'None'`, default `'Lax'`), `encode?` (default `true`), `json?`.
111
+
112
+ **`eat` / `list` options:** `decode?` (default `true`), `json?`.
113
+
114
+ **`throw` options:** `path?` (default `/`), `domain?`, `secure?`, `sameSite?`.
115
+
116
+ Notes: `HttpOnly` cookies are invisible to JS; use the same `path`/`domain` to delete; `sameSite: 'None'` forces `Secure=true`.
117
+
118
+ ## Types
119
+
120
+ `global.d.ts` extends `@stagepass/loader` via declaration merging (`stagepass.inject`, `stagepass.cookies`).
121
+
122
+ ## Repository
123
+
124
+ - Full docs and examples: [stagepass repository](https://github.com/arobertherz/stagepass)
125
+ - Migration: [MIGRATION.md](../../MIGRATION.md)
package/dist/all.min.js CHANGED
@@ -1 +1 @@
1
- "use strict";var StagepassModules=(()=>{(function(){function d(){let t=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!t||!t.vars)throw new Error("Stagepass core loader must be loaded before modules");return t.vars}function u(t){let s=d();(s.env==="local"||s.env==="staging")&&console.log(`[Stagepass] ${t}`)}function h(t){if(!t||typeof t!="string")return"file";try{let e=new URL(t).pathname||"";if(!e||e.length===0){let o=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return o?o[1]:"file"}let n=e.split("/");return n[n.length-1]||n[n.length-2]||"file"}catch{try{let e=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return e?e[1]:"file"}catch{return"file"}}}function g(t,s){if(s)return s;if(!t||typeof t!="string")return"script";try{if(t.split(".").pop()?.toLowerCase()==="css")return"style"}catch{}return"script"}function b(t){let s=d(),{src:e,stagepass:n,localPath:o,path:a,cacheBust:l}=t;if(!e||typeof e!="string")throw new Error("Invalid src: must be a non-empty string");if(n!==!1&&s.isLocal){let i=o||a||h(e);if(!i||typeof i!="string")return e;let r=i.startsWith("/")?i.substring(1):i,c=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(c&&typeof c.resolveLocalUrl=="function"){let f=c.resolveLocalUrl(r);if(f)return f}return`https://${s.domain}/${r}?_cb=${s.timestamp}`}return l?e+(e.includes("?")?"&":"?")+"_cb="+Date.now():e}function m(t,s){let{id:e,type:n}=t,o=g(t.src,n);if(e&&document.getElementById(e))return u(`Skipping injection: Element with id "${e}" already exists`),!0;let a=o==="script"?`script[src="${s}"]`:`link[href="${s}"]`;return document.querySelector(a)?(u(`Skipping injection: Resource "${s}" already loaded`),!0):!1}function j(t="body-end"){if(typeof t=="string")switch(t){case"head":return document.head;case"body-start":return document.body?.firstChild||document.body;case"body-end":return document.body;default:return document.body}let{target:s,action:e}=t,n=document.querySelector(s);return n?e==="before"?n:n.nextSibling||n.parentNode:(u(`Warning: Target selector "${s}" not found, falling back to body-end`),document.body)}function I(t){return new Promise((s,e)=>{if(!t.src){let r=d(),c=new Error('InjectOptions must have a "src" property');r.env!=="production"&&console.error("[Stagepass]",c),e(c);return}let n=d(),o=g(t.src,t.type),a=b(t);if(m(t,a)){s();return}let l=o==="script"?document.createElement("script"):document.createElement("link");if(o==="script"){let r=l;r.src=a,t.async?r.async=!0:t.defer!==!1&&(r.defer=!0),t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([c,f])=>{r.setAttribute(c,f)}),r.onload=()=>{u(`Injected: ${a}`),s()},r.onerror=()=>{let c=new Error(`Failed to load script: ${a}`);n.env!=="production"&&console.error("[Stagepass]",c),e(c)}}else{let r=l;r.rel="stylesheet",r.href=a,t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([f,y])=>{r.setAttribute(f,y)});let c=setInterval(()=>{(r.sheet||r.styleSheet)&&(clearInterval(c),u(`Injected: ${a}`),s())},10);setTimeout(()=>{if(clearInterval(c),!(r.sheet||r.styleSheet)){let y=new Error(`Failed to load stylesheet: ${a}`);n.env!=="production"&&console.error("[Stagepass]",y),e(y)}},5e3)}let i=j(t.position);if(!i){e(new Error("Could not find insertion point"));return}if(i===document.head||i===document.body)i.appendChild(l);else{let r=i.parentNode;r&&(typeof t.position=="object"&&t.position.action==="before"?r.insertBefore(l,i):r.insertBefore(l,i.nextSibling))}})}async function w(t){let s=[];if(!Array.isArray(t)&&typeof t=="object"&&("scripts"in t||"styles"in t)){let e=t;e.scripts&&s.push(...e.scripts.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"script"}))),e.styles&&s.push(...e.styles.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"style"})))}else Array.isArray(t)?s=t.filter(e=>e&&typeof e=="object"&&"src"in e&&typeof e.src=="string"&&e.src.trim().length>0):t&&typeof t=="object"&&"src"in t&&typeof t.src=="string"&&t.src.trim().length>0&&(s=[t]);for(let e of s)try{await I(e)}catch(n){d().env!=="production"&&console.error("[Stagepass] Injection error:",n)}}let p=window.stagepass=window.stagepass||{};p.inject=w,globalThis.stagepass=p,window.sp=p,globalThis.sp=p})();})();
1
+ "use strict";var StagepassModules=(()=>{(function(){function u(){let e=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!e||!e.vars)throw new Error("Stagepass core loader must be loaded before modules");return e.vars}function p(e){let n=u();(n.env==="local"||n.env==="staging")&&console.log(`[Stagepass] ${e}`)}function g(e){if(!e||typeof e!="string")return"file";try{let t=new URL(e).pathname||"";if(!t||t.length===0){let i=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return i?i[1]:"file"}let s=t.split("/");return s[s.length-1]||s[s.length-2]||"file"}catch{try{let t=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return t?t[1]:"file"}catch{return"file"}}}function b(e,n){if(n)return n;if(!e||typeof e!="string")return"script";try{if(e.split(".").pop()?.toLowerCase()==="css")return"style"}catch{}return"script"}function m(e,n,t){let s=encodeURIComponent(t),i=e.indexOf("#"),d=i>=0?e.slice(i):"",l=i>=0?e.slice(0,i):e,a=l.includes("?")?"&":"?";return`${l}${a}${encodeURIComponent(n)}=${s}${d}`}function w(e){let n=u(),{src:t,stagepass:s,localPath:i,path:d,version:l}=e;if(!t||typeof t!="string")throw new Error("Invalid src: must be a non-empty string");if(s!==!1&&n.isLocal){let a=i||d||g(t);if(!a||typeof a!="string")return t;let o=a.startsWith("/")?a.substring(1):a,c=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(c&&typeof c.resolveLocalUrl=="function"){let f=c.resolveLocalUrl(o);if(f)return f}return`https://${n.domain}/${o}?_cb=${n.timestamp}`}return l?m(t,"v",l):t}function S(e,n){let{id:t,type:s}=e,i=b(e.src,s);if(t&&document.getElementById(t))return p(`Skipping injection: Element with id "${t}" already exists`),!0;let d=i==="script"?`script[src="${n}"]`:`link[href="${n}"]`;return document.querySelector(d)?(p(`Skipping injection: Resource "${n}" already loaded`),!0):!1}function j(e="body-end"){if(typeof e=="string")switch(e){case"head":return document.head;case"body-start":return document.body?.firstChild||document.body;case"body-end":return document.body;default:return document.body}let{target:n,action:t}=e,s=document.querySelector(n);return s?t==="before"?s:s.nextSibling||s.parentNode:(p(`Warning: Target selector "${n}" not found, falling back to body-end`),document.body)}function I(e){return new Promise((n,t)=>{if(!e.src){let o=u(),c=new Error('InjectOptions must have a "src" property');o.env!=="production"&&console.error("[Stagepass]",c),t(c);return}let s=u(),i=b(e.src,e.type),d=w(e);if(S(e,d)){n();return}let l=i==="script"?document.createElement("script"):document.createElement("link");if(i==="script"){let o=l;o.src=d,e.async?o.async=!0:(o.async=!1,e.defer!==!1&&(o.defer=!0)),e.id&&(o.id=e.id),e.attributes&&Object.entries(e.attributes).forEach(([c,f])=>{o.setAttribute(c,f)}),o.onload=()=>{p(`Injected: ${d}`),n()},o.onerror=()=>{let c=new Error(`Failed to load script: ${d}`);s.env!=="production"&&console.error("[Stagepass]",c),t(c)}}else{let o=l;o.rel="stylesheet",o.href=d,e.id&&(o.id=e.id),e.attributes&&Object.entries(e.attributes).forEach(([f,h])=>{o.setAttribute(f,h)});let c=setInterval(()=>{(o.sheet||o.styleSheet)&&(clearInterval(c),p(`Injected: ${d}`),n())},10);setTimeout(()=>{if(clearInterval(c),!(o.sheet||o.styleSheet)){let h=new Error(`Failed to load stylesheet: ${d}`);s.env!=="production"&&console.error("[Stagepass]",h),t(h)}},5e3)}let a=j(e.position);if(!a){t(new Error("Could not find insertion point"));return}if(a===document.head||a===document.body)a.appendChild(l);else{let o=a.parentNode;o&&(typeof e.position=="object"&&e.position.action==="before"?o.insertBefore(l,a):o.insertBefore(l,a.nextSibling))}})}async function y(e){let n=[];if(!Array.isArray(e)&&typeof e=="object"&&("scripts"in e||"styles"in e)){let t=e;t.scripts&&n.push(...t.scripts.filter(s=>s&&typeof s=="object"&&"src"in s&&typeof s.src=="string"&&s.src.trim().length>0).map(s=>({...s,type:"script"}))),t.styles&&n.push(...t.styles.filter(s=>s&&typeof s=="object"&&"src"in s&&typeof s.src=="string"&&s.src.trim().length>0).map(s=>({...s,type:"style"})))}else Array.isArray(e)?n=e.filter(t=>t&&typeof t=="object"&&"src"in t&&typeof t.src=="string"&&t.src.trim().length>0):e&&typeof e=="object"&&"src"in e&&typeof e.src=="string"&&e.src.trim().length>0&&(n=[e]);for(let t of n)try{await I(t)}catch(s){u().env!=="production"&&console.error("[Stagepass] Injection error:",s)}}let r=window.stagepass=window.stagepass||{};r.inject=y,globalThis.stagepass=r,window.sp=r,globalThis.sp=r})();(function(){function u(){let r=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!r||!r.vars)throw new Error("Stagepass core loader must be loaded before modules");return r}function p(){return window.location.protocol==="https:"}function g(r){try{return decodeURIComponent(r)}catch{return r}}function b(r,e){let t=e.decode!==!1?g(r):r;if(!e.json)return t;try{return JSON.parse(t)}catch{return t}}function m(r,e,n={}){let t=u();if(!r||typeof r!="string"||r.includes(";"))throw new Error("Invalid cookie name");let s=n.encode!==!1,i=n.sameSite||"Lax",d=n.secure!==void 0?n.secure:p(),l=n.path||"/",a=n.json?JSON.stringify(e):String(e),o=s?encodeURIComponent(r):r;a=s?encodeURIComponent(a):a;let c=[`${o}=${a}`];if(typeof n.maxAge=="number"&&c.push(`Max-Age=${Math.floor(n.maxAge)}`),typeof n.days=="number"){let h=new Date(Date.now()+n.days*24*60*60*1e3);c.push(`Expires=${h.toUTCString()}`)}l&&c.push(`Path=${l}`),n.domain&&c.push(`Domain=${n.domain}`),c.push(`SameSite=${i}`);let f=d;i==="None"&&!f&&(f=!0,typeof t.warn=="function"&&t.warn("SameSite=None requires Secure=true. Enforcing Secure for cookie write.")),f&&c.push("Secure"),document.cookie=c.join("; ")}function w(r,e={}){if(!r||typeof r!="string")return null;let n=e.decode===!1?r:g(r),t=document.cookie?document.cookie.split("; "):[];for(let s of t){let i=s.indexOf("=");if(i<0)continue;let d=s.substring(0,i),l=s.substring(i+1),a=g(d);if(d===n||a===n)return b(l,e)}return null}function S(r){return w(r)!==null}function j(r={}){let e=document.cookie?document.cookie.split("; "):[],n={};for(let t of e){let s=t.indexOf("=");if(s<0)continue;let i=t.substring(0,s),d=t.substring(s+1),l=r.decode===!1?i:g(i);n[l]=b(d,r)}return n}function I(r,e={}){m(r,"",{days:-1,maxAge:0,path:e.path||"/",domain:e.domain,secure:e.secure,sameSite:e.sameSite})}let y=window.stagepass=window.stagepass||{};y.cookies={bake:m,eat:w,throw:I,has:S,list:j},globalThis.stagepass=y,window.sp=y,globalThis.sp=y})();})();
@@ -0,0 +1 @@
1
+ "use strict";var StagepassInject=(()=>{(function(){function y(){let e=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!e||!e.vars)throw new Error("Stagepass core loader must be loaded before modules");return e}function S(){return window.location.protocol==="https:"}function d(e){try{return decodeURIComponent(e)}catch{return e}}function g(e,o){let t=o.decode!==!1?d(e):e;if(!o.json)return t;try{return JSON.parse(t)}catch{return t}}function p(e,o,n={}){let t=y();if(!e||typeof e!="string"||e.includes(";"))throw new Error("Invalid cookie name");let s=n.encode!==!1,i=n.sameSite||"Lax",r=n.secure!==void 0?n.secure:S(),c=n.path||"/",u=n.json?JSON.stringify(o):String(o),k=s?encodeURIComponent(e):e;u=s?encodeURIComponent(u):u;let a=[`${k}=${u}`];if(typeof n.maxAge=="number"&&a.push(`Max-Age=${Math.floor(n.maxAge)}`),typeof n.days=="number"){let x=new Date(Date.now()+n.days*24*60*60*1e3);a.push(`Expires=${x.toUTCString()}`)}c&&a.push(`Path=${c}`),n.domain&&a.push(`Domain=${n.domain}`),a.push(`SameSite=${i}`);let l=r;i==="None"&&!l&&(l=!0,typeof t.warn=="function"&&t.warn("SameSite=None requires Secure=true. Enforcing Secure for cookie write.")),l&&a.push("Secure"),document.cookie=a.join("; ")}function m(e,o={}){if(!e||typeof e!="string")return null;let n=o.decode===!1?e:d(e),t=document.cookie?document.cookie.split("; "):[];for(let s of t){let i=s.indexOf("=");if(i<0)continue;let r=s.substring(0,i),c=s.substring(i+1),u=d(r);if(r===n||u===n)return g(c,o)}return null}function w(e){return m(e)!==null}function h(e={}){let o=document.cookie?document.cookie.split("; "):[],n={};for(let t of o){let s=t.indexOf("=");if(s<0)continue;let i=t.substring(0,s),r=t.substring(s+1),c=e.decode===!1?i:d(i);n[c]=g(r,e)}return n}function b(e,o={}){p(e,"",{days:-1,maxAge:0,path:o.path||"/",domain:o.domain,secure:o.secure,sameSite:o.sameSite})}let f=window.stagepass=window.stagepass||{};f.cookies={bake:p,eat:m,throw:b,has:w,list:h},globalThis.stagepass=f,window.sp=f,globalThis.sp=f})();})();
@@ -1 +1 @@
1
- "use strict";var StagepassInject=(()=>{(function(){function d(){let t=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!t||!t.vars)throw new Error("Stagepass core loader must be loaded before modules");return t.vars}function u(t){let s=d();(s.env==="local"||s.env==="staging")&&console.log(`[Stagepass] ${t}`)}function h(t){if(!t||typeof t!="string")return"file";try{let e=new URL(t).pathname||"";if(!e||e.length===0){let o=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return o?o[1]:"file"}let n=e.split("/");return n[n.length-1]||n[n.length-2]||"file"}catch{try{let e=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return e?e[1]:"file"}catch{return"file"}}}function g(t,s){if(s)return s;if(!t||typeof t!="string")return"script";try{if(t.split(".").pop()?.toLowerCase()==="css")return"style"}catch{}return"script"}function b(t){let s=d(),{src:e,stagepass:n,localPath:o,path:a,cacheBust:l}=t;if(!e||typeof e!="string")throw new Error("Invalid src: must be a non-empty string");if(n!==!1&&s.isLocal){let i=o||a||h(e);if(!i||typeof i!="string")return e;let r=i.startsWith("/")?i.substring(1):i,c=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(c&&typeof c.resolveLocalUrl=="function"){let f=c.resolveLocalUrl(r);if(f)return f}return`https://${s.domain}/${r}?_cb=${s.timestamp}`}return l?e+(e.includes("?")?"&":"?")+"_cb="+Date.now():e}function m(t,s){let{id:e,type:n}=t,o=g(t.src,n);if(e&&document.getElementById(e))return u(`Skipping injection: Element with id "${e}" already exists`),!0;let a=o==="script"?`script[src="${s}"]`:`link[href="${s}"]`;return document.querySelector(a)?(u(`Skipping injection: Resource "${s}" already loaded`),!0):!1}function j(t="body-end"){if(typeof t=="string")switch(t){case"head":return document.head;case"body-start":return document.body?.firstChild||document.body;case"body-end":return document.body;default:return document.body}let{target:s,action:e}=t,n=document.querySelector(s);return n?e==="before"?n:n.nextSibling||n.parentNode:(u(`Warning: Target selector "${s}" not found, falling back to body-end`),document.body)}function I(t){return new Promise((s,e)=>{if(!t.src){let r=d(),c=new Error('InjectOptions must have a "src" property');r.env!=="production"&&console.error("[Stagepass]",c),e(c);return}let n=d(),o=g(t.src,t.type),a=b(t);if(m(t,a)){s();return}let l=o==="script"?document.createElement("script"):document.createElement("link");if(o==="script"){let r=l;r.src=a,t.async?r.async=!0:t.defer!==!1&&(r.defer=!0),t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([c,f])=>{r.setAttribute(c,f)}),r.onload=()=>{u(`Injected: ${a}`),s()},r.onerror=()=>{let c=new Error(`Failed to load script: ${a}`);n.env!=="production"&&console.error("[Stagepass]",c),e(c)}}else{let r=l;r.rel="stylesheet",r.href=a,t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([f,y])=>{r.setAttribute(f,y)});let c=setInterval(()=>{(r.sheet||r.styleSheet)&&(clearInterval(c),u(`Injected: ${a}`),s())},10);setTimeout(()=>{if(clearInterval(c),!(r.sheet||r.styleSheet)){let y=new Error(`Failed to load stylesheet: ${a}`);n.env!=="production"&&console.error("[Stagepass]",y),e(y)}},5e3)}let i=j(t.position);if(!i){e(new Error("Could not find insertion point"));return}if(i===document.head||i===document.body)i.appendChild(l);else{let r=i.parentNode;r&&(typeof t.position=="object"&&t.position.action==="before"?r.insertBefore(l,i):r.insertBefore(l,i.nextSibling))}})}async function w(t){let s=[];if(!Array.isArray(t)&&typeof t=="object"&&("scripts"in t||"styles"in t)){let e=t;e.scripts&&s.push(...e.scripts.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"script"}))),e.styles&&s.push(...e.styles.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"style"})))}else Array.isArray(t)?s=t.filter(e=>e&&typeof e=="object"&&"src"in e&&typeof e.src=="string"&&e.src.trim().length>0):t&&typeof t=="object"&&"src"in t&&typeof t.src=="string"&&t.src.trim().length>0&&(s=[t]);for(let e of s)try{await I(e)}catch(n){d().env!=="production"&&console.error("[Stagepass] Injection error:",n)}}let p=window.stagepass=window.stagepass||{};p.inject=w,globalThis.stagepass=p,window.sp=p,globalThis.sp=p})();})();
1
+ "use strict";var StagepassInject=(()=>{(function(){function d(){let t=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(!t||!t.vars)throw new Error("Stagepass core loader must be loaded before modules");return t.vars}function p(t){let s=d();(s.env==="local"||s.env==="staging")&&console.log(`[Stagepass] ${t}`)}function h(t){if(!t||typeof t!="string")return"file";try{let e=new URL(t).pathname||"";if(!e||e.length===0){let c=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return c?c[1]:"file"}let n=e.split("/");return n[n.length-1]||n[n.length-2]||"file"}catch{try{let e=t.match(/\/([^\/\?#]+)(?:\?|#|$)/);return e?e[1]:"file"}catch{return"file"}}}function g(t,s){if(s)return s;if(!t||typeof t!="string")return"script";try{if(t.split(".").pop()?.toLowerCase()==="css")return"style"}catch{}return"script"}function b(t,s,e){let n=encodeURIComponent(e),c=t.indexOf("#"),o=c>=0?t.slice(c):"",l=c>=0?t.slice(0,c):t,i=l.includes("?")?"&":"?";return`${l}${i}${encodeURIComponent(s)}=${n}${o}`}function m(t){let s=d(),{src:e,stagepass:n,localPath:c,path:o,version:l}=t;if(!e||typeof e!="string")throw new Error("Invalid src: must be a non-empty string");if(n!==!1&&s.isLocal){let i=c||o||h(e);if(!i||typeof i!="string")return e;let r=i.startsWith("/")?i.substring(1):i,a=window.stagepass||globalThis.stagepass||window.sp||globalThis.sp;if(a&&typeof a.resolveLocalUrl=="function"){let f=a.resolveLocalUrl(r);if(f)return f}return`https://${s.domain}/${r}?_cb=${s.timestamp}`}return l?b(e,"v",l):e}function j(t,s){let{id:e,type:n}=t,c=g(t.src,n);if(e&&document.getElementById(e))return p(`Skipping injection: Element with id "${e}" already exists`),!0;let o=c==="script"?`script[src="${s}"]`:`link[href="${s}"]`;return document.querySelector(o)?(p(`Skipping injection: Resource "${s}" already loaded`),!0):!1}function I(t="body-end"){if(typeof t=="string")switch(t){case"head":return document.head;case"body-start":return document.body?.firstChild||document.body;case"body-end":return document.body;default:return document.body}let{target:s,action:e}=t,n=document.querySelector(s);return n?e==="before"?n:n.nextSibling||n.parentNode:(p(`Warning: Target selector "${s}" not found, falling back to body-end`),document.body)}function w(t){return new Promise((s,e)=>{if(!t.src){let r=d(),a=new Error('InjectOptions must have a "src" property');r.env!=="production"&&console.error("[Stagepass]",a),e(a);return}let n=d(),c=g(t.src,t.type),o=m(t);if(j(t,o)){s();return}let l=c==="script"?document.createElement("script"):document.createElement("link");if(c==="script"){let r=l;r.src=o,t.async?r.async=!0:(r.async=!1,t.defer!==!1&&(r.defer=!0)),t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([a,f])=>{r.setAttribute(a,f)}),r.onload=()=>{p(`Injected: ${o}`),s()},r.onerror=()=>{let a=new Error(`Failed to load script: ${o}`);n.env!=="production"&&console.error("[Stagepass]",a),e(a)}}else{let r=l;r.rel="stylesheet",r.href=o,t.id&&(r.id=t.id),t.attributes&&Object.entries(t.attributes).forEach(([f,u])=>{r.setAttribute(f,u)});let a=setInterval(()=>{(r.sheet||r.styleSheet)&&(clearInterval(a),p(`Injected: ${o}`),s())},10);setTimeout(()=>{if(clearInterval(a),!(r.sheet||r.styleSheet)){let u=new Error(`Failed to load stylesheet: ${o}`);n.env!=="production"&&console.error("[Stagepass]",u),e(u)}},5e3)}let i=I(t.position);if(!i){e(new Error("Could not find insertion point"));return}if(i===document.head||i===document.body)i.appendChild(l);else{let r=i.parentNode;r&&(typeof t.position=="object"&&t.position.action==="before"?r.insertBefore(l,i):r.insertBefore(l,i.nextSibling))}})}async function v(t){let s=[];if(!Array.isArray(t)&&typeof t=="object"&&("scripts"in t||"styles"in t)){let e=t;e.scripts&&s.push(...e.scripts.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"script"}))),e.styles&&s.push(...e.styles.filter(n=>n&&typeof n=="object"&&"src"in n&&typeof n.src=="string"&&n.src.trim().length>0).map(n=>({...n,type:"style"})))}else Array.isArray(t)?s=t.filter(e=>e&&typeof e=="object"&&"src"in e&&typeof e.src=="string"&&e.src.trim().length>0):t&&typeof t=="object"&&"src"in t&&typeof t.src=="string"&&t.src.trim().length>0&&(s=[t]);for(let e of s)try{await w(e)}catch(n){d().env!=="production"&&console.error("[Stagepass] Injection error:",n)}}let y=window.stagepass=window.stagepass||{};y.inject=v,globalThis.stagepass=y,window.sp=y,globalThis.sp=y})();})();
package/global.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Options for `stagepass.inject` / `sp.inject`.
3
+ */
4
+ export interface StagepassInjectOptions {
5
+ src: string;
6
+ type?: 'script' | 'style';
7
+ stagepass?: boolean;
8
+ localPath?: string;
9
+ path?: string;
10
+ id?: string;
11
+ async?: boolean;
12
+ defer?: boolean;
13
+ /** @deprecated No longer appends per-view timestamps in production. Use `version`. */
14
+ cacheBust?: boolean;
15
+ /** Production version token appended as `?v=`. */
16
+ version?: string;
17
+ attributes?: Record<string, string>;
18
+ position?:
19
+ | 'head'
20
+ | 'body-start'
21
+ | 'body-end'
22
+ | { target: string; action: 'before' | 'after' };
23
+ }
24
+
25
+ export interface StagepassInjectBatchOptions {
26
+ scripts?: StagepassInjectOptions[];
27
+ styles?: StagepassInjectOptions[];
28
+ }
29
+
30
+ export interface StagepassCookiesAPI {
31
+ /** Write a cookie. */
32
+ bake: (name: string, value: unknown, options?: Record<string, unknown>) => void;
33
+ /** Read a cookie. */
34
+ eat: (name: string, options?: Record<string, unknown>) => unknown;
35
+ /** Delete a cookie. */
36
+ throw: (name: string, options?: Record<string, unknown>) => void;
37
+ /** Whether a cookie exists. */
38
+ has: (name: string) => boolean;
39
+ /** List cookies as a name → value map. */
40
+ list: (options?: Record<string, unknown>) => Record<string, unknown>;
41
+ }
42
+
43
+ export type StagepassInjectAPI = (
44
+ options:
45
+ | StagepassInjectOptions
46
+ | StagepassInjectOptions[]
47
+ | StagepassInjectBatchOptions
48
+ ) => Promise<void>;
49
+
50
+ /** Declaration merging: extend loader StagepassAPI with modules. */
51
+ declare module '@stagepass/loader' {
52
+ interface StagepassAPI {
53
+ /** Programmatic asset injector (from `@stagepass/modules`). */
54
+ inject?: StagepassInjectAPI;
55
+ /** Cookie helpers (from `@stagepass/modules`). */
56
+ cookies?: StagepassCookiesAPI;
57
+ }
58
+ }
59
+
60
+ export {};
package/package.json CHANGED
@@ -1,17 +1,22 @@
1
1
  {
2
2
  "name": "@stagepass/modules",
3
- "version": "1.0.6",
3
+ "version": "2.0.0",
4
4
  "description": "Modular feature extensions for Stagepass",
5
5
  "type": "module",
6
6
  "main": "dist/all.min.js",
7
+ "types": "global.d.ts",
7
8
  "files": [
8
- "dist"
9
+ "dist",
10
+ "global.d.ts",
11
+ "README.md",
12
+ "LICENSE"
9
13
  ],
10
14
  "scripts": {
11
15
  "build": "tsup",
12
16
  "dev": "tsup --watch",
13
- "test": "vitest run",
14
- "test:watch": "vitest"
17
+ "test": "vitest run && npm run typecheck",
18
+ "test:watch": "vitest",
19
+ "typecheck": "tsc --noEmit -p fixtures/tsconfig.json"
15
20
  },
16
21
  "keywords": [
17
22
  "stagepass",
@@ -26,11 +31,11 @@
26
31
  },
27
32
  "license": "MIT",
28
33
  "peerDependencies": {
29
- "@stagepass/loader": ">=1.0.0"
34
+ "@stagepass/loader": ">=2.0.0"
30
35
  },
31
36
  "devDependencies": {
32
37
  "tsup": "^8.0.1",
33
38
  "typescript": "^5.3.3",
34
- "vitest": "^2.1.0"
39
+ "vitest": "^5.0.5"
35
40
  }
36
41
  }