@walkeros/web-core 4.8.2 → 4.8.3-next-1793115089237

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/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @walkeros/web-core
2
2
 
3
+ ## 4.8.3-next-1793115089237
4
+
5
+ ### Patch Changes
6
+
7
+ - 29d2218: The gtag and d8a destinations now set `analytics_storage` from
8
+ `analytics` consent instead of `functional` by default, matching what the
9
+ Cookiebot, CookieFirst and CookiePro sources report. With the Usercentrics
10
+ source, map your measurement category to `analytics` in its `categoryMap`. If
11
+ your consent commands report measurement consent as `functional`, map it
12
+ yourself, like
13
+ `como: { functional: 'analytics_storage', marketing: ['ad_storage', 'ad_user_data', 'ad_personalization'] }`.
14
+ When several consent keys map to one parameter, the parameter is granted only
15
+ if all of them are granted in the current consent state; before, the key that
16
+ came last won.
17
+ - 5313635: The test page `page` from `@walkeros/web-core/dev` now answers each
18
+ vendor script a step inserts with `load`, as a browser does, so a destination
19
+ that waits for its script delivers in the examples runner and the conformance
20
+ kit instead of timing out. `failScripts` still fails those scripts on demand.
21
+ - Updated dependencies [34fd225]
22
+ - Updated dependencies [5313635]
23
+ - Updated dependencies [5313635]
24
+ - Updated dependencies [5313635]
25
+ - Updated dependencies [5313635]
26
+ - Updated dependencies [5313635]
27
+ - Updated dependencies [34fd225]
28
+ - Updated dependencies [5313635]
29
+ - @walkeros/core@4.8.3-next-1793115089237
30
+
3
31
  ## 4.8.2
4
32
 
5
33
  ### Patch Changes
@@ -304,9 +332,6 @@
304
332
  and `event.context` remain required.
305
333
  - Each source self-registers via TypeScript module augmentation of `SourceMap`
306
334
  in `@walkeros/core`.
307
- - App-side coordination (`/workspaces/developer/app`) is a follow-up plan, not
308
- part of this release. Telemetry from v4 CLI/MCP will not validate against
309
- the existing app schema until that follow-up ships.
310
335
  - `Mapping.Rule.skip` is renamed to `Mapping.Rule.silent`. Customer flow.json
311
336
  configs using `skip: true` in mapping rules must rename to `silent: true`.
312
337
  Hard cut: no legacy alias, the field is gone.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Browser-specific utilities for client-side walkerOS implementations, covering
10
10
  DOM interactions, browser information, storage, element visibility, web hashing,
11
11
  and web-based communication.
12
12
 
13
- [Documentation](https://www.walkeros.io/docs) •
13
+ [Documentation](https://www.walkeros.io/docs/core/web) •
14
14
  [NPM Package](https://www.npmjs.com/package/@walkeros/web-core) •
15
15
  [Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/web/core)
16
16
 
@@ -28,7 +28,7 @@ import { getAttribute, isVisible, sendWeb } from '@walkeros/web-core';
28
28
  const element = document.querySelector('[data-elb="product"]');
29
29
  const entity = getAttribute(element, 'data-elb');
30
30
 
31
- if (isVisible(element)) {
31
+ if (isVisible(element, window, document)) {
32
32
  await sendWeb('https://api.example.com/events', { entity });
33
33
  }
34
34
  ```
@@ -36,7 +36,7 @@ if (isVisible(element)) {
36
36
  ## Documentation
37
37
 
38
38
  Full configuration, mapping, and examples live in the docs:
39
- **https://www.walkeros.io/docs**
39
+ **https://www.walkeros.io/docs/core/web**
40
40
 
41
41
  ## Contribute
42
42
 
package/dist/dev.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};function a(){const e=[],t=new WeakMap;return{querySelectorAll:()=>[...e],createElement:()=>{const e=new Map,r={src:"",async:!1,getAttribute:t=>{var s;return"src"===t?r.src:null!=(s=e.get(t))?s:null},setAttribute:(t,r)=>{e.set(t,r)},addEventListener:(e,s)=>{var n;"load"===e&&t.set(r,[...null!=(n=t.get(r))?n:[],s])}};return r},head:{appendChild:r=>{var s;e.push(r),(null!=(s=t.get(r))?s:[]).forEach(e=>e())}}}}((e,r)=>{for(var s in r)t(e,s,{get:r[s],enumerable:!0})})(o,{mockScriptDocument:()=>a,page:()=>h}),module.exports=(e=o,((e,o,a,i)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of s(o))n.call(e,l)||l===a||t(e,l,{get:()=>o[l],enumerable:!(i=r(o,l))||i.enumerable});return e})(t({},"__esModule",{value:!0}),e));require("@walkeros/core");var i="data-walkeros-vendor";function l(e,t,r){const s=Object.getOwnPropertyDescriptor(e,t);return Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{s?Object.defineProperty(e,t,s):Reflect.deleteProperty(e,t)}}function u(e){return Array.from(e.querySelectorAll("script"))}function c(e){return class{constructor(){this.status=0,this.statusText="",this.response="",this.responseText="",this.readyState=0,this.onload=null,this.onerror=null,this.onreadystatechange=null,this.method="GET",this.url="",this.async=!0}open(e,t,r=!0){this.method=e,this.url=t,this.async=r,this.readyState=1}setRequestHeader(){}addEventListener(e,t){"load"===e&&(this.onload=t),"error"===e&&(this.onerror=t)}send(t){const{answer:r,settle:s}=e(["XMLHttpRequest",this.method,this.url,t]),n=()=>{var e,t,n,o,a;if(s(),this.readyState=4,r.error){if(!this.async)throw new Error("NetworkError");null==(e=this.onerror)||e.call(this)}else this.status=null!=(t=r.status)?t:200,this.statusText=null!=(n=r.statusText)?n:"",this.responseText=function(e){return void 0===e?"":"string"==typeof e?e:JSON.stringify(e)}(r.body),this.response=this.responseText,null==(o=this.onreadystatechange)||o.call(this),null==(a=this.onload)||a.call(this)};this.async?new Promise(e=>setTimeout(e,0)).then(n):n()}}}var h={open(e){if("undefined"==typeof document)throw new Error("the web page needs a document: run it in a jsdom test environment");const t=document,r=new Set(u(t)),s=()=>u(t).filter(e=>!r.has(e)),n=[l(window,"XMLHttpRequest",c(e)),l(navigator,"sendBeacon",(t,r)=>{var s;const{answer:n,settle:o}=e(["sendBeacon",t,r]);return o(),!n.error&&(null!=(s=n.status)?s:200)<400})];return{globals:{document:t},scripts:()=>{const e=s(),t=e.filter(e=>e.hasAttribute(i)).length;return{marked:t,unmarked:e.length-t}},failScripts:()=>{t.querySelectorAll(`script[${i}]`).forEach(e=>e.dispatchEvent(new Event("error")))},close:()=>{n.splice(0).forEach(e=>e()),s().forEach(e=>e.remove())}}}};//# sourceMappingURL=dev.js.map
1
+ "use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,o={};function a(){const e=[],t=new WeakMap;return{querySelectorAll:()=>[...e],createElement:()=>{const e=new Map,r={src:"",async:!1,getAttribute:t=>{var n;return"src"===t?r.src:null!=(n=e.get(t))?n:null},setAttribute:(t,r)=>{e.set(t,r)},addEventListener:(e,n)=>{var s;"load"===e&&t.set(r,[...null!=(s=t.get(r))?s:[],n])}};return r},head:{appendChild:r=>{var n;e.push(r),(null!=(n=t.get(r))?n:[]).forEach(e=>e())}}}}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(o,{mockScriptDocument:()=>a,page:()=>h}),module.exports=(e=o,((e,o,a,i)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of n(o))s.call(e,l)||l===a||t(e,l,{get:()=>o[l],enumerable:!(i=r(o,l))||i.enumerable});return e})(t({},"__esModule",{value:!0}),e));require("@walkeros/core");var i="data-walkeros-vendor";function l(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}}function c(e){return Array.from(e.querySelectorAll("script"))}function u(e){return class{constructor(){this.status=0,this.statusText="",this.response="",this.responseText="",this.readyState=0,this.onload=null,this.onerror=null,this.onreadystatechange=null,this.method="GET",this.url="",this.async=!0}open(e,t,r=!0){this.method=e,this.url=t,this.async=r,this.readyState=1}setRequestHeader(){}addEventListener(e,t){"load"===e&&(this.onload=t),"error"===e&&(this.onerror=t)}send(t){const{answer:r,settle:n}=e(["XMLHttpRequest",this.method,this.url,t]),s=()=>{var e,t,s,o,a;if(n(),this.readyState=4,r.error){if(!this.async)throw new Error("NetworkError");null==(e=this.onerror)||e.call(this)}else this.status=null!=(t=r.status)?t:200,this.statusText=null!=(s=r.statusText)?s:"",this.responseText=function(e){return void 0===e?"":"string"==typeof e?e:JSON.stringify(e)}(r.body),this.response=this.responseText,null==(o=this.onreadystatechange)||o.call(this),null==(a=this.onload)||a.call(this)};this.async?new Promise(e=>setTimeout(e,0)).then(s):s()}}}var h={open(e){if("undefined"==typeof document)throw new Error("the web page needs a document: run it in a jsdom test environment");const t=document,r=new Set(c(t)),n=()=>c(t).filter(e=>!r.has(e)),s=[l(window,"XMLHttpRequest",u(e)),l(navigator,"sendBeacon",(t,r)=>{var n;const{answer:s,settle:o}=e(["sendBeacon",t,r]);return o(),!s.error&&(null!=(n=s.status)?n:200)<400})],o=new WeakSet,a=new MutationObserver(e=>{for(const{addedNodes:t}of e)t.forEach(e=>{e instanceof HTMLScriptElement&&e.hasAttribute(i)&&!o.has(e)&&(o.add(e),e.dispatchEvent(new Event("load")))})});return a.observe(t,{childList:!0,subtree:!0}),{globals:{document:t},scripts:()=>{const e=n(),t=e.filter(e=>e.hasAttribute(i)).length;return{marked:t,unmarked:e.length-t}},failScripts:()=>{t.querySelectorAll(`script[${i}]`).forEach(e=>e.dispatchEvent(new Event("error")))},close:()=>{a.disconnect(),s.splice(0).forEach(e=>e()),n().forEach(e=>e.remove())}}}};//# sourceMappingURL=dev.js.map
package/dist/dev.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev.ts","../src/mockScriptDocument.ts","../src/loadVendor.ts","../src/dev/page.ts"],"sourcesContent":["export { mockScriptDocument } from './mockScriptDocument';\nexport type { MockScript, MockScriptDocument } from './mockScriptDocument';\nexport { page } from './dev/page';\n","/** A script element, as far as `loadVendor` uses one. */\nexport type MockScript = {\n src: string;\n async: boolean;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n addEventListener(type: string, listener: () => void): void;\n};\n\n/** A document, as far as `loadVendor` injects into one. */\nexport type MockScriptDocument = {\n querySelectorAll(selector: string): MockScript[];\n createElement(tagName: string): MockScript;\n head: { appendChild(script: MockScript): void };\n};\n\n/**\n * A document without a DOM for `loadVendor` to inject into, for an examples\n * env (tests, simulation in Node). It keeps the scripts appended to its head,\n * so each src goes in once, and an appended script loads at once.\n */\nexport function mockScriptDocument(): MockScriptDocument {\n const scripts: MockScript[] = [];\n const loads = new WeakMap<MockScript, Array<() => void>>();\n\n return {\n querySelectorAll: () => [...scripts],\n createElement: () => {\n const attributes = new Map<string, string>();\n const script: MockScript = {\n src: '',\n async: false,\n getAttribute: (name) =>\n name === 'src' ? script.src : (attributes.get(name) ?? null),\n setAttribute: (name, value) => {\n attributes.set(name, value);\n },\n addEventListener: (type, listener) => {\n if (type === 'load')\n loads.set(script, [...(loads.get(script) ?? []), listener]);\n },\n };\n return script;\n },\n head: {\n appendChild: (script) => {\n scripts.push(script);\n (loads.get(script) ?? []).forEach((listener) => listener());\n },\n },\n };\n}\n","import { resolveDestinationTimeout, StepError } from '@walkeros/core';\n\n/** Attribute on every script `loadVendor` injects. */\nexport const VENDOR_SCRIPT_MARKER = 'data-walkeros-vendor';\n\nexport interface LoadVendorOptions {\n /** The destination's timeout; the load deadline is its resolved value. */\n timeout?: number;\n /**\n * Attributes the vendor's tag needs (e.g. `data-domain`), set before the\n * script is inserted. `src` and the marker cannot be overwritten.\n */\n attributes?: Record<string, string>;\n /**\n * The document the script goes into, and whose scripts are the registry:\n * the destination's env one (`getEnv(env).document`). The global document\n * without it.\n */\n document?: Document;\n}\n\nexport interface Vendor<T> {\n /**\n * Resolves with the vendor once its script loaded and `get()` finds it.\n * Rejects `vendor-not-loaded` after the script's `error` (final for the\n * page), `vendor-not-ready` when the vendor is missing, `vendor-timeout`\n * when the script did not load by the deadline. Past the deadline, and\n * without a script, it checks `get()` on each call.\n */\n ready(): Promise<T>;\n /**\n * For vendors that replay their own stub (called synchronously): throws\n * `vendor-not-loaded` once the injected script fired `error`.\n */\n check(): void;\n}\n\ntype Outcome = 'loaded' | 'failed' | 'expired';\n\ninterface Injected {\n state: 'loading' | 'loaded' | 'failed';\n /** The deadline passed before the script loaded or failed. */\n expired: boolean;\n timeout: number;\n waiting: Array<(outcome: Outcome) => void>;\n}\n\n/** The state of each vendor script, kept with its element. */\nconst injected = new WeakMap<Element, Injected>();\n\n/**\n * The page's script for `src`. The page itself is the registry: its one\n * marked script with that src means the src was injected (once per page, a\n * failure is never re-injected), and another document has its own.\n */\nfunction scriptOf(doc: Document, src: string): HTMLScriptElement | undefined {\n const marked = doc.querySelectorAll<HTMLScriptElement>(\n `script[${VENDOR_SCRIPT_MARKER}]`,\n );\n return Array.from(marked).find(\n (script) => script.getAttribute('src') === src,\n );\n}\n\nfunction inject(\n doc: Document,\n src: string,\n timeout: number,\n attributes: Record<string, string>,\n available: () => boolean,\n): Injected {\n const existing = scriptOf(doc, src);\n const known = existing && injected.get(existing);\n if (known) return known;\n\n const entry: Injected = {\n state: 'loading',\n expired: false,\n timeout,\n waiting: [],\n };\n\n // A marked script without state (another bundle's) is adopted, not\n // doubled. Its `load` may have fired already: with the vendor there, it is\n // ready at once; otherwise it is watched like an own script.\n if (existing && available()) {\n entry.state = 'loaded';\n injected.set(existing, entry);\n return entry;\n }\n const script = existing ?? doc.createElement('script');\n\n const settle = (outcome: Outcome) => {\n const waiting = entry.waiting;\n entry.waiting = [];\n waiting.forEach((notify) => notify(outcome));\n };\n\n const timer = setTimeout(() => {\n entry.expired = true;\n settle('expired');\n }, timeout);\n\n injected.set(script, entry);\n script.addEventListener('load', () => {\n clearTimeout(timer);\n entry.state = 'loaded';\n settle('loaded');\n });\n script.addEventListener('error', () => {\n clearTimeout(timer);\n entry.state = 'failed';\n settle('failed');\n });\n\n if (!existing) {\n for (const [name, value] of Object.entries(attributes))\n script.setAttribute(name, value);\n // After the attributes, so they never replace the src or the marker.\n script.src = src;\n script.async = true;\n script.setAttribute(VENDOR_SCRIPT_MARKER, '');\n doc.head.appendChild(script);\n }\n\n return entry;\n}\n\nconst notLoaded = () =>\n new StepError('Vendor script failed to load', { code: 'vendor-not-loaded' });\n\nconst notReady = () =>\n new StepError('Vendor not ready: its global is missing', {\n code: 'vendor-not-ready',\n });\n\nconst timedOut = (timeout: number) =>\n new StepError(`Vendor script did not load within ${timeout}ms`, {\n code: 'vendor-timeout',\n });\n\n/**\n * Injects a vendor script once per `src` on the page (marked\n * `data-walkeros-vendor`, with the `attributes` its tag needs) and reports\n * its readiness. The deadline runs from the injection and equals the\n * destination's resolved timeout, so an awaited `ready()` settles before the\n * push's own timeout. Without `src` (the page loads the vendor) nothing is\n * injected and there is no deadline. A `src` with no document to inject\n * into (neither `options.document` nor a global one) throws\n * `vendor-not-ready`.\n */\nexport function loadVendor<T>(\n src: string | undefined,\n get: () => T | undefined,\n options: LoadVendorOptions = {},\n): Vendor<T> {\n const available = () => {\n const vendor = get();\n return vendor !== undefined && vendor !== null;\n };\n\n let script: Injected | undefined;\n if (src) {\n const doc =\n options.document ??\n (typeof document !== 'undefined' ? document : undefined);\n if (!doc)\n throw new StepError(`Vendor script ${src} has no document to go into`, {\n code: 'vendor-not-ready',\n });\n script = inject(\n doc,\n src,\n resolveDestinationTimeout(options.timeout),\n options.attributes ?? {},\n available,\n );\n }\n\n const present = (): Promise<T> => {\n const vendor = get();\n return vendor === undefined || vendor === null\n ? Promise.reject(notReady())\n : Promise.resolve(vendor);\n };\n\n return {\n ready() {\n if (!script) return present();\n if (script.state === 'failed') return Promise.reject(notLoaded());\n if (script.state === 'loaded' || script.expired) return present();\n\n return new Promise<T>((resolve, reject) => {\n script.waiting.push((outcome) => {\n if (outcome === 'failed') reject(notLoaded());\n else if (outcome === 'expired') reject(timedOut(script.timeout));\n else present().then(resolve, reject);\n });\n });\n },\n check() {\n if (script?.state === 'failed') throw notLoaded();\n },\n };\n}\n","import type { Flow } from '@walkeros/core';\nimport { VENDOR_SCRIPT_MARKER } from '../loadVendor';\n\n/**\n * The page a web step runs on in the conformance kit and the examples runner\n * of `@walkeros/collector/dev`. While a run is open, `navigator.sendBeacon`\n * and `XMLHttpRequest` answer through the kit's boundary (`sendWeb` runs on\n * them), and the scripts the run adds are tracked; closing the run restores\n * both and removes those scripts, so the next run starts on the page it\n * found (the page is loadVendor's once-per-src registry).\n */\n\nconst macrotask = () => new Promise<void>((resolve) => setTimeout(resolve, 0));\n\nfunction bodyText(body: unknown): string {\n if (body === undefined) return '';\n return typeof body === 'string' ? body : JSON.stringify(body);\n}\n\n/**\n * Replace one property for a run; returns its restore. A property that did\n * not exist is deleted again.\n */\nfunction replace(target: object, key: string, value: unknown): () => void {\n const original = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, key, {\n value,\n configurable: true,\n writable: true,\n });\n return () => {\n if (original) Object.defineProperty(target, key, original);\n else Reflect.deleteProperty(target, key);\n };\n}\n\nfunction scriptsOf(doc: Document): HTMLScriptElement[] {\n return Array.from(doc.querySelectorAll('script'));\n}\n\n/**\n * `XMLHttpRequest` at the boundary: synchronous by default, as sendWeb opens\n * it; the async form answers late.\n */\nfunction kitXMLHttpRequest(record: Flow.StepRecord) {\n return class KitXMLHttpRequest {\n status = 0;\n statusText = '';\n response: unknown = '';\n responseText = '';\n readyState = 0;\n onload: (() => void) | null = null;\n onerror: (() => void) | null = null;\n onreadystatechange: (() => void) | null = null;\n private method = 'GET';\n private url = '';\n private async = true;\n\n open(method: string, url: string, async = true) {\n this.method = method;\n this.url = url;\n this.async = async;\n this.readyState = 1;\n }\n setRequestHeader() {}\n addEventListener(type: string, listener: () => void) {\n if (type === 'load') this.onload = listener;\n if (type === 'error') this.onerror = listener;\n }\n send(body?: unknown) {\n const { answer, settle } = record([\n 'XMLHttpRequest',\n this.method,\n this.url,\n body,\n ]);\n const done = () => {\n settle();\n this.readyState = 4;\n if (answer.error) {\n if (!this.async) throw new Error('NetworkError');\n this.onerror?.();\n return;\n }\n this.status = answer.status ?? 200;\n this.statusText = answer.statusText ?? '';\n this.responseText = bodyText(answer.body);\n this.response = this.responseText;\n this.onreadystatechange?.();\n this.onload?.();\n };\n if (this.async) macrotask().then(done);\n else done();\n }\n };\n}\n\nexport const page: Flow.StepPage = {\n open(record) {\n if (typeof document === 'undefined')\n throw new Error(\n 'the web page needs a document: run it in a jsdom test environment',\n );\n const doc = document;\n const before = new Set(scriptsOf(doc));\n const added = () => scriptsOf(doc).filter((script) => !before.has(script));\n\n const beacon = (url: string, data?: unknown): boolean => {\n const { answer, settle } = record(['sendBeacon', url, data]);\n settle();\n return !answer.error && (answer.status ?? 200) < 400;\n };\n const restores = [\n replace(window, 'XMLHttpRequest', kitXMLHttpRequest(record)),\n replace(navigator, 'sendBeacon', beacon),\n ];\n\n return {\n globals: { document: doc },\n scripts: () => {\n const scripts = added();\n const marked = scripts.filter((script) =>\n script.hasAttribute(VENDOR_SCRIPT_MARKER),\n ).length;\n return { marked, unmarked: scripts.length - marked };\n },\n failScripts: () => {\n doc\n .querySelectorAll(`script[${VENDOR_SCRIPT_MARKER}]`)\n .forEach((script) => script.dispatchEvent(new Event('error')));\n },\n close: () => {\n restores.splice(0).forEach((restore) => restore());\n added().forEach((script) => script.remove());\n },\n };\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,SAAS,qBAAyC;AACvD,QAAM,UAAwB,CAAC;AAC/B,QAAM,QAAQ,oBAAI,QAAuC;AAEzD,SAAO;AAAA,IACL,kBAAkB,MAAM,CAAC,GAAG,OAAO;AAAA,IACnC,eAAe,MAAM;AACnB,YAAM,aAAa,oBAAI,IAAoB;AAC3C,YAAM,SAAqB;AAAA,QACzB,KAAK;AAAA,QACL,OAAO;AAAA,QACP,cAAc,CAAC,SAAM;AAhC7B;AAiCU,0BAAS,QAAQ,OAAO,OAAO,gBAAW,IAAI,IAAI,MAAnB,YAAwB;AAAA;AAAA,QACzD,cAAc,CAAC,MAAM,UAAU;AAC7B,qBAAW,IAAI,MAAM,KAAK;AAAA,QAC5B;AAAA,QACA,kBAAkB,CAAC,MAAM,aAAa;AArC9C;A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,cAAc,KAAK,IAAI,CAAC;AAC3D,aAAO;AACP,aAAO,CAAC,OAAO,WAAU,YAAO,WAAP,YAAiB,OAAO;AAAA,IACnD;AACA,UAAM,WAAW;AAAA,MACf,QAAQ,QAAQ,kBAAkB,kBAAkB,MAAM,CAAC;AAAA,MAC3D,QAAQ,WAAW,cAAc,MAAM;AAAA,IACzC;AAEA,WAAO;AAAA,MACL,SAAS,EAAE,UAAU,IAAI;AAAA,MACzB,SAAS,MAAM;AACb,cAAM,UAAU,MAAM;AACtB,cAAM,SAAS,QAAQ;AAAA,UAAO,CAAC,WAC7B,OAAO,aAAa,oBAAoB;AAAA,QAC1C,EAAE;AACF,eAAO,EAAE,QAAQ,UAAU,QAAQ,SAAS,OAAO;AAAA,MACrD;AAAA,MACA,aAAa,MAAM;AACjB,YACG,iBAAiB,UAAU,oBAAoB,GAAG,EAClD,QAAQ,CAAC,WAAW,OAAO,cAAc,IAAI,MAAM,OAAO,CAAC,CAAC;AAAA,MACjE;AAAA,MACA,OAAO,MAAM;AACX,iBAAS,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,QAAQ,CAAC;AACjD,cAAM,EAAE,QAAQ,CAAC,WAAW,OAAO,OAAO,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/dev.ts","../src/mockScriptDocument.ts","../src/loadVendor.ts","../src/dev/page.ts"],"sourcesContent":["export { mockScriptDocument } from './mockScriptDocument';\nexport type { MockScript, MockScriptDocument } from './mockScriptDocument';\nexport { page } from './dev/page';\n","/** A script element, as far as `loadVendor` uses one. */\nexport type MockScript = {\n src: string;\n async: boolean;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n addEventListener(type: string, listener: () => void): void;\n};\n\n/** A document, as far as `loadVendor` injects into one. */\nexport type MockScriptDocument = {\n querySelectorAll(selector: string): MockScript[];\n createElement(tagName: string): MockScript;\n head: { appendChild(script: MockScript): void };\n};\n\n/**\n * A document without a DOM for `loadVendor` to inject into, for an examples\n * env (tests, simulation in Node). It keeps the scripts appended to its head,\n * so each src goes in once, and an appended script loads at once.\n */\nexport function mockScriptDocument(): MockScriptDocument {\n const scripts: MockScript[] = [];\n const loads = new WeakMap<MockScript, Array<() => void>>();\n\n return {\n querySelectorAll: () => [...scripts],\n createElement: () => {\n const attributes = new Map<string, string>();\n const script: MockScript = {\n src: '',\n async: false,\n getAttribute: (name) =>\n name === 'src' ? script.src : (attributes.get(name) ?? null),\n setAttribute: (name, value) => {\n attributes.set(name, value);\n },\n addEventListener: (type, listener) => {\n if (type === 'load')\n loads.set(script, [...(loads.get(script) ?? []), listener]);\n },\n };\n return script;\n },\n head: {\n appendChild: (script) => {\n scripts.push(script);\n (loads.get(script) ?? []).forEach((listener) => listener());\n },\n },\n };\n}\n","import { resolveDestinationTimeout, StepError } from '@walkeros/core';\n\n/** Attribute on every script `loadVendor` injects. */\nexport const VENDOR_SCRIPT_MARKER = 'data-walkeros-vendor';\n\nexport interface LoadVendorOptions {\n /** The destination's timeout; the load deadline is its resolved value. */\n timeout?: number;\n /**\n * Attributes the vendor's tag needs (e.g. `data-domain`), set before the\n * script is inserted. `src` and the marker cannot be overwritten.\n */\n attributes?: Record<string, string>;\n /**\n * The document the script goes into, and whose scripts are the registry:\n * the destination's env one (`getEnv(env).document`). The global document\n * without it.\n */\n document?: Document;\n}\n\nexport interface Vendor<T> {\n /**\n * Resolves with the vendor once its script loaded and `get()` finds it.\n * Rejects `vendor-not-loaded` after the script's `error` (final for the\n * page), `vendor-not-ready` when the vendor is missing, `vendor-timeout`\n * when the script did not load by the deadline. Past the deadline, and\n * without a script, it checks `get()` on each call.\n */\n ready(): Promise<T>;\n /**\n * For vendors that replay their own stub (called synchronously): throws\n * `vendor-not-loaded` once the injected script fired `error`.\n */\n check(): void;\n}\n\ntype Outcome = 'loaded' | 'failed' | 'expired';\n\ninterface Injected {\n state: 'loading' | 'loaded' | 'failed';\n /** The deadline passed before the script loaded or failed. */\n expired: boolean;\n timeout: number;\n waiting: Array<(outcome: Outcome) => void>;\n}\n\n/** The state of each vendor script, kept with its element. */\nconst injected = new WeakMap<Element, Injected>();\n\n/**\n * The page's script for `src`. The page itself is the registry: its one\n * marked script with that src means the src was injected (once per page, a\n * failure is never re-injected), and another document has its own.\n */\nfunction scriptOf(doc: Document, src: string): HTMLScriptElement | undefined {\n const marked = doc.querySelectorAll<HTMLScriptElement>(\n `script[${VENDOR_SCRIPT_MARKER}]`,\n );\n return Array.from(marked).find(\n (script) => script.getAttribute('src') === src,\n );\n}\n\nfunction inject(\n doc: Document,\n src: string,\n timeout: number,\n attributes: Record<string, string>,\n available: () => boolean,\n): Injected {\n const existing = scriptOf(doc, src);\n const known = existing && injected.get(existing);\n if (known) return known;\n\n const entry: Injected = {\n state: 'loading',\n expired: false,\n timeout,\n waiting: [],\n };\n\n // A marked script without state (another bundle's) is adopted, not\n // doubled. Its `load` may have fired already: with the vendor there, it is\n // ready at once; otherwise it is watched like an own script.\n if (existing && available()) {\n entry.state = 'loaded';\n injected.set(existing, entry);\n return entry;\n }\n const script = existing ?? doc.createElement('script');\n\n const settle = (outcome: Outcome) => {\n const waiting = entry.waiting;\n entry.waiting = [];\n waiting.forEach((notify) => notify(outcome));\n };\n\n const timer = setTimeout(() => {\n entry.expired = true;\n settle('expired');\n }, timeout);\n\n injected.set(script, entry);\n script.addEventListener('load', () => {\n clearTimeout(timer);\n entry.state = 'loaded';\n settle('loaded');\n });\n script.addEventListener('error', () => {\n clearTimeout(timer);\n entry.state = 'failed';\n settle('failed');\n });\n\n if (!existing) {\n for (const [name, value] of Object.entries(attributes))\n script.setAttribute(name, value);\n // After the attributes, so they never replace the src or the marker.\n script.src = src;\n script.async = true;\n script.setAttribute(VENDOR_SCRIPT_MARKER, '');\n doc.head.appendChild(script);\n }\n\n return entry;\n}\n\nconst notLoaded = () =>\n new StepError('Vendor script failed to load', { code: 'vendor-not-loaded' });\n\nconst notReady = () =>\n new StepError('Vendor not ready: its global is missing', {\n code: 'vendor-not-ready',\n });\n\nconst timedOut = (timeout: number) =>\n new StepError(`Vendor script did not load within ${timeout}ms`, {\n code: 'vendor-timeout',\n });\n\n/**\n * Injects a vendor script once per `src` on the page (marked\n * `data-walkeros-vendor`, with the `attributes` its tag needs) and reports\n * its readiness. The deadline runs from the injection and equals the\n * destination's resolved timeout, so an awaited `ready()` settles before the\n * push's own timeout. Without `src` (the page loads the vendor) nothing is\n * injected and there is no deadline. A `src` with no document to inject\n * into (neither `options.document` nor a global one) throws\n * `vendor-not-ready`.\n */\nexport function loadVendor<T>(\n src: string | undefined,\n get: () => T | undefined,\n options: LoadVendorOptions = {},\n): Vendor<T> {\n const available = () => {\n const vendor = get();\n return vendor !== undefined && vendor !== null;\n };\n\n let script: Injected | undefined;\n if (src) {\n const doc =\n options.document ??\n (typeof document !== 'undefined' ? document : undefined);\n if (!doc)\n throw new StepError(`Vendor script ${src} has no document to go into`, {\n code: 'vendor-not-ready',\n });\n script = inject(\n doc,\n src,\n resolveDestinationTimeout(options.timeout),\n options.attributes ?? {},\n available,\n );\n }\n\n const present = (): Promise<T> => {\n const vendor = get();\n return vendor === undefined || vendor === null\n ? Promise.reject(notReady())\n : Promise.resolve(vendor);\n };\n\n return {\n ready() {\n if (!script) return present();\n if (script.state === 'failed') return Promise.reject(notLoaded());\n if (script.state === 'loaded' || script.expired) return present();\n\n return new Promise<T>((resolve, reject) => {\n script.waiting.push((outcome) => {\n if (outcome === 'failed') reject(notLoaded());\n else if (outcome === 'expired') reject(timedOut(script.timeout));\n else present().then(resolve, reject);\n });\n });\n },\n check() {\n if (script?.state === 'failed') throw notLoaded();\n },\n };\n}\n","import type { Flow } from '@walkeros/core';\nimport { VENDOR_SCRIPT_MARKER } from '../loadVendor';\n\n/**\n * The page a web step runs on in the conformance kit and the examples runner\n * of `@walkeros/collector/dev`. While a run is open, `navigator.sendBeacon`\n * and `XMLHttpRequest` answer through the kit's boundary (`sendWeb` runs on\n * them), and the scripts the run adds are tracked: a marked vendor script\n * loads unless `failScripts` fails it. Closing the run restores both and\n * removes those scripts, so the next run starts on the page it found (the\n * page is loadVendor's once-per-src registry).\n */\n\nconst macrotask = () => new Promise<void>((resolve) => setTimeout(resolve, 0));\n\nfunction bodyText(body: unknown): string {\n if (body === undefined) return '';\n return typeof body === 'string' ? body : JSON.stringify(body);\n}\n\n/**\n * Replace one property for a run; returns its restore. A property that did\n * not exist is deleted again.\n */\nfunction replace(target: object, key: string, value: unknown): () => void {\n const original = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, key, {\n value,\n configurable: true,\n writable: true,\n });\n return () => {\n if (original) Object.defineProperty(target, key, original);\n else Reflect.deleteProperty(target, key);\n };\n}\n\nfunction scriptsOf(doc: Document): HTMLScriptElement[] {\n return Array.from(doc.querySelectorAll('script'));\n}\n\n/**\n * `XMLHttpRequest` at the boundary: synchronous by default, as sendWeb opens\n * it; the async form answers late.\n */\nfunction kitXMLHttpRequest(record: Flow.StepRecord) {\n return class KitXMLHttpRequest {\n status = 0;\n statusText = '';\n response: unknown = '';\n responseText = '';\n readyState = 0;\n onload: (() => void) | null = null;\n onerror: (() => void) | null = null;\n onreadystatechange: (() => void) | null = null;\n private method = 'GET';\n private url = '';\n private async = true;\n\n open(method: string, url: string, async = true) {\n this.method = method;\n this.url = url;\n this.async = async;\n this.readyState = 1;\n }\n setRequestHeader() {}\n addEventListener(type: string, listener: () => void) {\n if (type === 'load') this.onload = listener;\n if (type === 'error') this.onerror = listener;\n }\n send(body?: unknown) {\n const { answer, settle } = record([\n 'XMLHttpRequest',\n this.method,\n this.url,\n body,\n ]);\n const done = () => {\n settle();\n this.readyState = 4;\n if (answer.error) {\n if (!this.async) throw new Error('NetworkError');\n this.onerror?.();\n return;\n }\n this.status = answer.status ?? 200;\n this.statusText = answer.statusText ?? '';\n this.responseText = bodyText(answer.body);\n this.response = this.responseText;\n this.onreadystatechange?.();\n this.onload?.();\n };\n if (this.async) macrotask().then(done);\n else done();\n }\n };\n}\n\nexport const page: Flow.StepPage = {\n open(record) {\n if (typeof document === 'undefined')\n throw new Error(\n 'the web page needs a document: run it in a jsdom test environment',\n );\n const doc = document;\n const before = new Set(scriptsOf(doc));\n const added = () => scriptsOf(doc).filter((script) => !before.has(script));\n\n const beacon = (url: string, data?: unknown): boolean => {\n const { answer, settle } = record(['sendBeacon', url, data]);\n settle();\n return !answer.error && (answer.status ?? 200) < 400;\n };\n const restores = [\n replace(window, 'XMLHttpRequest', kitXMLHttpRequest(record)),\n replace(navigator, 'sendBeacon', beacon),\n ];\n\n // A vendor script a run adds loads, as in a browser: once, right after\n // it is inserted (loadVendor listens before it inserts). jsdom fetches\n // no script, so without this answer every awaited script times out.\n const loaded = new WeakSet<Node>();\n const observer = new MutationObserver((mutations) => {\n for (const { addedNodes } of mutations)\n addedNodes.forEach((node) => {\n if (\n !(node instanceof HTMLScriptElement) ||\n !node.hasAttribute(VENDOR_SCRIPT_MARKER) ||\n loaded.has(node)\n )\n return;\n loaded.add(node);\n node.dispatchEvent(new Event('load'));\n });\n });\n observer.observe(doc, { childList: true, subtree: true });\n\n return {\n globals: { document: doc },\n scripts: () => {\n const scripts = added();\n const marked = scripts.filter((script) =>\n script.hasAttribute(VENDOR_SCRIPT_MARKER),\n ).length;\n return { marked, unmarked: scripts.length - marked };\n },\n failScripts: () => {\n doc\n .querySelectorAll(`script[${VENDOR_SCRIPT_MARKER}]`)\n .forEach((script) => script.dispatchEvent(new Event('error')));\n },\n close: () => {\n observer.disconnect();\n restores.splice(0).forEach((restore) => restore());\n added().forEach((script) => script.remove());\n },\n };\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,SAAS,qBAAyC;AACvD,QAAM,UAAwB,CAAC;AAC/B,QAAM,QAAQ,oBAAI,QAAuC;AAEzD,SAAO;AAAA,IACL,kBAAkB,MAAM,CAAC,GAAG,OAAO;AAAA,IACnC,eAAe,MAAM;AACnB,YAAM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B,GAAG,EAClD,QAAQ,CAAC,WAAW,OAAO,cAAc,IAAI,MAAM,OAAO,CAAC,CAAC;AAAA,MACjE;AAAA,MACA,OAAO,MAAM;AACX,iBAAS,WAAW;AACpB,iBAAS,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,QAAQ,CAAC;AACjD,cAAM,EAAE,QAAQ,CAAC,WAAW,OAAO,OAAO,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/dist/dev.mjs CHANGED
@@ -1 +1 @@
1
- function t(){const t=[],e=new WeakMap;return{querySelectorAll:()=>[...t],createElement:()=>{const t=new Map,r={src:"",async:!1,getAttribute:e=>{var s;return"src"===e?r.src:null!=(s=t.get(e))?s:null},setAttribute:(e,r)=>{t.set(e,r)},addEventListener:(t,s)=>{var n;"load"===t&&e.set(r,[...null!=(n=e.get(r))?n:[],s])}};return r},head:{appendChild:r=>{var s;t.push(r),(null!=(s=e.get(r))?s:[]).forEach(t=>t())}}}}import{resolveDestinationTimeout as e,StepError as r}from"@walkeros/core";var s="data-walkeros-vendor";function n(t,e,r){const s=Object.getOwnPropertyDescriptor(t,e);return Object.defineProperty(t,e,{value:r,configurable:!0,writable:!0}),()=>{s?Object.defineProperty(t,e,s):Reflect.deleteProperty(t,e)}}function o(t){return Array.from(t.querySelectorAll("script"))}function a(t){return class{constructor(){this.status=0,this.statusText="",this.response="",this.responseText="",this.readyState=0,this.onload=null,this.onerror=null,this.onreadystatechange=null,this.method="GET",this.url="",this.async=!0}open(t,e,r=!0){this.method=t,this.url=e,this.async=r,this.readyState=1}setRequestHeader(){}addEventListener(t,e){"load"===t&&(this.onload=e),"error"===t&&(this.onerror=e)}send(e){const{answer:r,settle:s}=t(["XMLHttpRequest",this.method,this.url,e]),n=()=>{var t,e,n,o,a;if(s(),this.readyState=4,r.error){if(!this.async)throw new Error("NetworkError");null==(t=this.onerror)||t.call(this)}else this.status=null!=(e=r.status)?e:200,this.statusText=null!=(n=r.statusText)?n:"",this.responseText=function(t){return void 0===t?"":"string"==typeof t?t:JSON.stringify(t)}(r.body),this.response=this.responseText,null==(o=this.onreadystatechange)||o.call(this),null==(a=this.onload)||a.call(this)};this.async?new Promise(t=>setTimeout(t,0)).then(n):n()}}}var i={open(t){if("undefined"==typeof document)throw new Error("the web page needs a document: run it in a jsdom test environment");const e=document,r=new Set(o(e)),i=()=>o(e).filter(t=>!r.has(t)),l=[n(window,"XMLHttpRequest",a(t)),n(navigator,"sendBeacon",(e,r)=>{var s;const{answer:n,settle:o}=t(["sendBeacon",e,r]);return o(),!n.error&&(null!=(s=n.status)?s:200)<400})];return{globals:{document:e},scripts:()=>{const t=i(),e=t.filter(t=>t.hasAttribute(s)).length;return{marked:e,unmarked:t.length-e}},failScripts:()=>{e.querySelectorAll(`script[${s}]`).forEach(t=>t.dispatchEvent(new Event("error")))},close:()=>{l.splice(0).forEach(t=>t()),i().forEach(t=>t.remove())}}}};export{t as mockScriptDocument,i as page};//# sourceMappingURL=dev.mjs.map
1
+ function e(){const e=[],t=new WeakMap;return{querySelectorAll:()=>[...e],createElement:()=>{const e=new Map,r={src:"",async:!1,getAttribute:t=>{var s;return"src"===t?r.src:null!=(s=e.get(t))?s:null},setAttribute:(t,r)=>{e.set(t,r)},addEventListener:(e,s)=>{var n;"load"===e&&t.set(r,[...null!=(n=t.get(r))?n:[],s])}};return r},head:{appendChild:r=>{var s;e.push(r),(null!=(s=t.get(r))?s:[]).forEach(e=>e())}}}}import{resolveDestinationTimeout as t,StepError as r}from"@walkeros/core";var s="data-walkeros-vendor";function n(e,t,r){const s=Object.getOwnPropertyDescriptor(e,t);return Object.defineProperty(e,t,{value:r,configurable:!0,writable:!0}),()=>{s?Object.defineProperty(e,t,s):Reflect.deleteProperty(e,t)}}function o(e){return Array.from(e.querySelectorAll("script"))}function a(e){return class{constructor(){this.status=0,this.statusText="",this.response="",this.responseText="",this.readyState=0,this.onload=null,this.onerror=null,this.onreadystatechange=null,this.method="GET",this.url="",this.async=!0}open(e,t,r=!0){this.method=e,this.url=t,this.async=r,this.readyState=1}setRequestHeader(){}addEventListener(e,t){"load"===e&&(this.onload=t),"error"===e&&(this.onerror=t)}send(t){const{answer:r,settle:s}=e(["XMLHttpRequest",this.method,this.url,t]),n=()=>{var e,t,n,o,a;if(s(),this.readyState=4,r.error){if(!this.async)throw new Error("NetworkError");null==(e=this.onerror)||e.call(this)}else this.status=null!=(t=r.status)?t:200,this.statusText=null!=(n=r.statusText)?n:"",this.responseText=function(e){return void 0===e?"":"string"==typeof e?e:JSON.stringify(e)}(r.body),this.response=this.responseText,null==(o=this.onreadystatechange)||o.call(this),null==(a=this.onload)||a.call(this)};this.async?new Promise(e=>setTimeout(e,0)).then(n):n()}}}var i={open(e){if("undefined"==typeof document)throw new Error("the web page needs a document: run it in a jsdom test environment");const t=document,r=new Set(o(t)),i=()=>o(t).filter(e=>!r.has(e)),l=[n(window,"XMLHttpRequest",a(e)),n(navigator,"sendBeacon",(t,r)=>{var s;const{answer:n,settle:o}=e(["sendBeacon",t,r]);return o(),!n.error&&(null!=(s=n.status)?s:200)<400})],c=new WeakSet,u=new MutationObserver(e=>{for(const{addedNodes:t}of e)t.forEach(e=>{e instanceof HTMLScriptElement&&e.hasAttribute(s)&&!c.has(e)&&(c.add(e),e.dispatchEvent(new Event("load")))})});return u.observe(t,{childList:!0,subtree:!0}),{globals:{document:t},scripts:()=>{const e=i(),t=e.filter(e=>e.hasAttribute(s)).length;return{marked:t,unmarked:e.length-t}},failScripts:()=>{t.querySelectorAll(`script[${s}]`).forEach(e=>e.dispatchEvent(new Event("error")))},close:()=>{u.disconnect(),l.splice(0).forEach(e=>e()),i().forEach(e=>e.remove())}}}};export{e as mockScriptDocument,i as page};//# sourceMappingURL=dev.mjs.map
package/dist/dev.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mockScriptDocument.ts","../src/loadVendor.ts","../src/dev/page.ts"],"sourcesContent":["/** A script element, as far as `loadVendor` uses one. */\nexport type MockScript = {\n src: string;\n async: boolean;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n addEventListener(type: string, listener: () => void): void;\n};\n\n/** A document, as far as `loadVendor` injects into one. */\nexport type MockScriptDocument = {\n querySelectorAll(selector: string): MockScript[];\n createElement(tagName: string): MockScript;\n head: { appendChild(script: MockScript): void };\n};\n\n/**\n * A document without a DOM for `loadVendor` to inject into, for an examples\n * env (tests, simulation in Node). It keeps the scripts appended to its head,\n * so each src goes in once, and an appended script loads at once.\n */\nexport function mockScriptDocument(): MockScriptDocument {\n const scripts: MockScript[] = [];\n const loads = new WeakMap<MockScript, Array<() => void>>();\n\n return {\n querySelectorAll: () => [...scripts],\n createElement: () => {\n const attributes = new Map<string, string>();\n const script: MockScript = {\n src: '',\n async: false,\n getAttribute: (name) =>\n name === 'src' ? script.src : (attributes.get(name) ?? null),\n setAttribute: (name, value) => {\n attributes.set(name, value);\n },\n addEventListener: (type, listener) => {\n if (type === 'load')\n loads.set(script, [...(loads.get(script) ?? []), listener]);\n },\n };\n return script;\n },\n head: {\n appendChild: (script) => {\n scripts.push(script);\n (loads.get(script) ?? []).forEach((listener) => listener());\n },\n },\n };\n}\n","import { resolveDestinationTimeout, StepError } from '@walkeros/core';\n\n/** Attribute on every script `loadVendor` injects. */\nexport const VENDOR_SCRIPT_MARKER = 'data-walkeros-vendor';\n\nexport interface LoadVendorOptions {\n /** The destination's timeout; the load deadline is its resolved value. */\n timeout?: number;\n /**\n * Attributes the vendor's tag needs (e.g. `data-domain`), set before the\n * script is inserted. `src` and the marker cannot be overwritten.\n */\n attributes?: Record<string, string>;\n /**\n * The document the script goes into, and whose scripts are the registry:\n * the destination's env one (`getEnv(env).document`). The global document\n * without it.\n */\n document?: Document;\n}\n\nexport interface Vendor<T> {\n /**\n * Resolves with the vendor once its script loaded and `get()` finds it.\n * Rejects `vendor-not-loaded` after the script's `error` (final for the\n * page), `vendor-not-ready` when the vendor is missing, `vendor-timeout`\n * when the script did not load by the deadline. Past the deadline, and\n * without a script, it checks `get()` on each call.\n */\n ready(): Promise<T>;\n /**\n * For vendors that replay their own stub (called synchronously): throws\n * `vendor-not-loaded` once the injected script fired `error`.\n */\n check(): void;\n}\n\ntype Outcome = 'loaded' | 'failed' | 'expired';\n\ninterface Injected {\n state: 'loading' | 'loaded' | 'failed';\n /** The deadline passed before the script loaded or failed. */\n expired: boolean;\n timeout: number;\n waiting: Array<(outcome: Outcome) => void>;\n}\n\n/** The state of each vendor script, kept with its element. */\nconst injected = new WeakMap<Element, Injected>();\n\n/**\n * The page's script for `src`. The page itself is the registry: its one\n * marked script with that src means the src was injected (once per page, a\n * failure is never re-injected), and another document has its own.\n */\nfunction scriptOf(doc: Document, src: string): HTMLScriptElement | undefined {\n const marked = doc.querySelectorAll<HTMLScriptElement>(\n `script[${VENDOR_SCRIPT_MARKER}]`,\n );\n return Array.from(marked).find(\n (script) => script.getAttribute('src') === src,\n );\n}\n\nfunction inject(\n doc: Document,\n src: string,\n timeout: number,\n attributes: Record<string, string>,\n available: () => boolean,\n): Injected {\n const existing = scriptOf(doc, src);\n const known = existing && injected.get(existing);\n if (known) return known;\n\n const entry: Injected = {\n state: 'loading',\n expired: false,\n timeout,\n waiting: [],\n };\n\n // A marked script without state (another bundle's) is adopted, not\n // doubled. Its `load` may have fired already: with the vendor there, it is\n // ready at once; otherwise it is watched like an own script.\n if (existing && available()) {\n entry.state = 'loaded';\n injected.set(existing, entry);\n return entry;\n }\n const script = existing ?? doc.createElement('script');\n\n const settle = (outcome: Outcome) => {\n const waiting = entry.waiting;\n entry.waiting = [];\n waiting.forEach((notify) => notify(outcome));\n };\n\n const timer = setTimeout(() => {\n entry.expired = true;\n settle('expired');\n }, timeout);\n\n injected.set(script, entry);\n script.addEventListener('load', () => {\n clearTimeout(timer);\n entry.state = 'loaded';\n settle('loaded');\n });\n script.addEventListener('error', () => {\n clearTimeout(timer);\n entry.state = 'failed';\n settle('failed');\n });\n\n if (!existing) {\n for (const [name, value] of Object.entries(attributes))\n script.setAttribute(name, value);\n // After the attributes, so they never replace the src or the marker.\n script.src = src;\n script.async = true;\n script.setAttribute(VENDOR_SCRIPT_MARKER, '');\n doc.head.appendChild(script);\n }\n\n return entry;\n}\n\nconst notLoaded = () =>\n new StepError('Vendor script failed to load', { code: 'vendor-not-loaded' });\n\nconst notReady = () =>\n new StepError('Vendor not ready: its global is missing', {\n code: 'vendor-not-ready',\n });\n\nconst timedOut = (timeout: number) =>\n new StepError(`Vendor script did not load within ${timeout}ms`, {\n code: 'vendor-timeout',\n });\n\n/**\n * Injects a vendor script once per `src` on the page (marked\n * `data-walkeros-vendor`, with the `attributes` its tag needs) and reports\n * its readiness. The deadline runs from the injection and equals the\n * destination's resolved timeout, so an awaited `ready()` settles before the\n * push's own timeout. Without `src` (the page loads the vendor) nothing is\n * injected and there is no deadline. A `src` with no document to inject\n * into (neither `options.document` nor a global one) throws\n * `vendor-not-ready`.\n */\nexport function loadVendor<T>(\n src: string | undefined,\n get: () => T | undefined,\n options: LoadVendorOptions = {},\n): Vendor<T> {\n const available = () => {\n const vendor = get();\n return vendor !== undefined && vendor !== null;\n };\n\n let script: Injected | undefined;\n if (src) {\n const doc =\n options.document ??\n (typeof document !== 'undefined' ? document : undefined);\n if (!doc)\n throw new StepError(`Vendor script ${src} has no document to go into`, {\n code: 'vendor-not-ready',\n });\n script = inject(\n doc,\n src,\n resolveDestinationTimeout(options.timeout),\n options.attributes ?? {},\n available,\n );\n }\n\n const present = (): Promise<T> => {\n const vendor = get();\n return vendor === undefined || vendor === null\n ? Promise.reject(notReady())\n : Promise.resolve(vendor);\n };\n\n return {\n ready() {\n if (!script) return present();\n if (script.state === 'failed') return Promise.reject(notLoaded());\n if (script.state === 'loaded' || script.expired) return present();\n\n return new Promise<T>((resolve, reject) => {\n script.waiting.push((outcome) => {\n if (outcome === 'failed') reject(notLoaded());\n else if (outcome === 'expired') reject(timedOut(script.timeout));\n else present().then(resolve, reject);\n });\n });\n },\n check() {\n if (script?.state === 'failed') throw notLoaded();\n },\n };\n}\n","import type { Flow } from '@walkeros/core';\nimport { VENDOR_SCRIPT_MARKER } from '../loadVendor';\n\n/**\n * The page a web step runs on in the conformance kit and the examples runner\n * of `@walkeros/collector/dev`. While a run is open, `navigator.sendBeacon`\n * and `XMLHttpRequest` answer through the kit's boundary (`sendWeb` runs on\n * them), and the scripts the run adds are tracked; closing the run restores\n * both and removes those scripts, so the next run starts on the page it\n * found (the page is loadVendor's once-per-src registry).\n */\n\nconst macrotask = () => new Promise<void>((resolve) => setTimeout(resolve, 0));\n\nfunction bodyText(body: unknown): string {\n if (body === undefined) return '';\n return typeof body === 'string' ? body : JSON.stringify(body);\n}\n\n/**\n * Replace one property for a run; returns its restore. A property that did\n * not exist is deleted again.\n */\nfunction replace(target: object, key: string, value: unknown): () => void {\n const original = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, key, {\n value,\n configurable: true,\n writable: true,\n });\n return () => {\n if (original) Object.defineProperty(target, key, original);\n else Reflect.deleteProperty(target, key);\n };\n}\n\nfunction scriptsOf(doc: Document): HTMLScriptElement[] {\n return Array.from(doc.querySelectorAll('script'));\n}\n\n/**\n * `XMLHttpRequest` at the boundary: synchronous by default, as sendWeb opens\n * it; the async form answers late.\n */\nfunction kitXMLHttpRequest(record: Flow.StepRecord) {\n return class KitXMLHttpRequest {\n status = 0;\n statusText = '';\n response: unknown = '';\n responseText = '';\n readyState = 0;\n onload: (() => void) | null = null;\n onerror: (() => void) | null = null;\n onreadystatechange: (() => void) | null = null;\n private method = 'GET';\n private url = '';\n private async = true;\n\n open(method: string, url: string, async = true) {\n this.method = method;\n this.url = url;\n this.async = async;\n this.readyState = 1;\n }\n setRequestHeader() {}\n addEventListener(type: string, listener: () => void) {\n if (type === 'load') this.onload = listener;\n if (type === 'error') this.onerror = listener;\n }\n send(body?: unknown) {\n const { answer, settle } = record([\n 'XMLHttpRequest',\n this.method,\n this.url,\n body,\n ]);\n const done = () => {\n settle();\n this.readyState = 4;\n if (answer.error) {\n if (!this.async) throw new Error('NetworkError');\n this.onerror?.();\n return;\n }\n this.status = answer.status ?? 200;\n this.statusText = answer.statusText ?? '';\n this.responseText = bodyText(answer.body);\n this.response = this.responseText;\n this.onreadystatechange?.();\n this.onload?.();\n };\n if (this.async) macrotask().then(done);\n else done();\n }\n };\n}\n\nexport const page: Flow.StepPage = {\n open(record) {\n if (typeof document === 'undefined')\n throw new Error(\n 'the web page needs a document: run it in a jsdom test environment',\n );\n const doc = document;\n const before = new Set(scriptsOf(doc));\n const added = () => scriptsOf(doc).filter((script) => !before.has(script));\n\n const beacon = (url: string, data?: unknown): boolean => {\n const { answer, settle } = record(['sendBeacon', url, data]);\n settle();\n return !answer.error && (answer.status ?? 200) < 400;\n };\n const restores = [\n replace(window, 'XMLHttpRequest', kitXMLHttpRequest(record)),\n replace(navigator, 'sendBeacon', beacon),\n ];\n\n return {\n globals: { document: doc },\n scripts: () => {\n const scripts = added();\n const marked = scripts.filter((script) =>\n script.hasAttribute(VENDOR_SCRIPT_MARKER),\n ).length;\n return { marked, unmarked: scripts.length - marked };\n },\n failScripts: () => {\n doc\n .querySelectorAll(`script[${VENDOR_SCRIPT_MARKER}]`)\n .forEach((script) => script.dispatchEvent(new Event('error')));\n },\n close: () => {\n restores.splice(0).forEach((restore) => restore());\n added().forEach((script) => script.remove());\n },\n };\n },\n};\n"],"mappings":";AAqBO,SAAS,qBAAyC;AACvD,QAAM,UAAwB,CAAC;AAC/B,QAAM,QAAQ,oBAAI,QAAuC;AAEzD,SAAO;AAAA,IACL,kBAAkB,MAAM,CAAC,GAAG,OAAO;AAAA,IACnC,eAAe,MAAM;AACnB,YAAM,aAAa,oBAAI,IAAoB;AAC3C,YAAM,SAAqB;AAAA,QACzB,KAAK;AAAA,QACL,OAAO;AAAA,QACP,cAAc,CAAC,SAAM;AAhC7B;AAiCU,0BAAS,QAAQ,OAAO,OAAO,gBAAW,IAAI,IAAI,MAAnB,YAAwB;AAAA;AAAA,QACzD,cAAc,CAAC,MA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,IAAI,MAAM,CAAC;AAEzE,UAAM,SAAS,CAAC,KAAa,SAA4B;AA3G7D;AA4GM,YAAM,EAAE,QAAQ,OAAO,IAAI,OAAO,CAAC,cAAc,KAAK,IAAI,CAAC;AAC3D,aAAO;AACP,aAAO,CAAC,OAAO,WAAU,YAAO,WAAP,YAAiB,OAAO;AAAA,IACnD;AACA,UAAM,WAAW;AAAA,MACf,QAAQ,QAAQ,kBAAkB,kBAAkB,MAAM,CAAC;AAAA,MAC3D,QAAQ,WAAW,cAAc,MAAM;AAAA,IACzC;AAEA,WAAO;AAAA,MACL,SAAS,EAAE,UAAU,IAAI;AAAA,MACzB,SAAS,MAAM;AACb,cAAM,UAAU,MAAM;AACtB,cAAM,SAAS,QAAQ;AAAA,UAAO,CAAC,WAC7B,OAAO,aAAa,oBAAoB;AAAA,QAC1C,EAAE;AACF,eAAO,EAAE,QAAQ,UAAU,QAAQ,SAAS,OAAO;AAAA,MACrD;AAAA,MACA,aAAa,MAAM;AACjB,YACG,iBAAiB,UAAU,oBAAoB,GAAG,EAClD,QAAQ,CAAC,WAAW,OAAO,cAAc,IAAI,MAAM,OAAO,CAAC,CAAC;AAAA,MACjE;AAAA,MACA,OAAO,MAAM;AACX,iBAAS,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,QAAQ,CAAC;AACjD,cAAM,EAAE,QAAQ,CAAC,WAAW,OAAO,OAAO,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/mockScriptDocument.ts","../src/loadVendor.ts","../src/dev/page.ts"],"sourcesContent":["/** A script element, as far as `loadVendor` uses one. */\nexport type MockScript = {\n src: string;\n async: boolean;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n addEventListener(type: string, listener: () => void): void;\n};\n\n/** A document, as far as `loadVendor` injects into one. */\nexport type MockScriptDocument = {\n querySelectorAll(selector: string): MockScript[];\n createElement(tagName: string): MockScript;\n head: { appendChild(script: MockScript): void };\n};\n\n/**\n * A document without a DOM for `loadVendor` to inject into, for an examples\n * env (tests, simulation in Node). It keeps the scripts appended to its head,\n * so each src goes in once, and an appended script loads at once.\n */\nexport function mockScriptDocument(): MockScriptDocument {\n const scripts: MockScript[] = [];\n const loads = new WeakMap<MockScript, Array<() => void>>();\n\n return {\n querySelectorAll: () => [...scripts],\n createElement: () => {\n const attributes = new Map<string, string>();\n const script: MockScript = {\n src: '',\n async: false,\n getAttribute: (name) =>\n name === 'src' ? script.src : (attributes.get(name) ?? null),\n setAttribute: (name, value) => {\n attributes.set(name, value);\n },\n addEventListener: (type, listener) => {\n if (type === 'load')\n loads.set(script, [...(loads.get(script) ?? []), listener]);\n },\n };\n return script;\n },\n head: {\n appendChild: (script) => {\n scripts.push(script);\n (loads.get(script) ?? []).forEach((listener) => listener());\n },\n },\n };\n}\n","import { resolveDestinationTimeout, StepError } from '@walkeros/core';\n\n/** Attribute on every script `loadVendor` injects. */\nexport const VENDOR_SCRIPT_MARKER = 'data-walkeros-vendor';\n\nexport interface LoadVendorOptions {\n /** The destination's timeout; the load deadline is its resolved value. */\n timeout?: number;\n /**\n * Attributes the vendor's tag needs (e.g. `data-domain`), set before the\n * script is inserted. `src` and the marker cannot be overwritten.\n */\n attributes?: Record<string, string>;\n /**\n * The document the script goes into, and whose scripts are the registry:\n * the destination's env one (`getEnv(env).document`). The global document\n * without it.\n */\n document?: Document;\n}\n\nexport interface Vendor<T> {\n /**\n * Resolves with the vendor once its script loaded and `get()` finds it.\n * Rejects `vendor-not-loaded` after the script's `error` (final for the\n * page), `vendor-not-ready` when the vendor is missing, `vendor-timeout`\n * when the script did not load by the deadline. Past the deadline, and\n * without a script, it checks `get()` on each call.\n */\n ready(): Promise<T>;\n /**\n * For vendors that replay their own stub (called synchronously): throws\n * `vendor-not-loaded` once the injected script fired `error`.\n */\n check(): void;\n}\n\ntype Outcome = 'loaded' | 'failed' | 'expired';\n\ninterface Injected {\n state: 'loading' | 'loaded' | 'failed';\n /** The deadline passed before the script loaded or failed. */\n expired: boolean;\n timeout: number;\n waiting: Array<(outcome: Outcome) => void>;\n}\n\n/** The state of each vendor script, kept with its element. */\nconst injected = new WeakMap<Element, Injected>();\n\n/**\n * The page's script for `src`. The page itself is the registry: its one\n * marked script with that src means the src was injected (once per page, a\n * failure is never re-injected), and another document has its own.\n */\nfunction scriptOf(doc: Document, src: string): HTMLScriptElement | undefined {\n const marked = doc.querySelectorAll<HTMLScriptElement>(\n `script[${VENDOR_SCRIPT_MARKER}]`,\n );\n return Array.from(marked).find(\n (script) => script.getAttribute('src') === src,\n );\n}\n\nfunction inject(\n doc: Document,\n src: string,\n timeout: number,\n attributes: Record<string, string>,\n available: () => boolean,\n): Injected {\n const existing = scriptOf(doc, src);\n const known = existing && injected.get(existing);\n if (known) return known;\n\n const entry: Injected = {\n state: 'loading',\n expired: false,\n timeout,\n waiting: [],\n };\n\n // A marked script without state (another bundle's) is adopted, not\n // doubled. Its `load` may have fired already: with the vendor there, it is\n // ready at once; otherwise it is watched like an own script.\n if (existing && available()) {\n entry.state = 'loaded';\n injected.set(existing, entry);\n return entry;\n }\n const script = existing ?? doc.createElement('script');\n\n const settle = (outcome: Outcome) => {\n const waiting = entry.waiting;\n entry.waiting = [];\n waiting.forEach((notify) => notify(outcome));\n };\n\n const timer = setTimeout(() => {\n entry.expired = true;\n settle('expired');\n }, timeout);\n\n injected.set(script, entry);\n script.addEventListener('load', () => {\n clearTimeout(timer);\n entry.state = 'loaded';\n settle('loaded');\n });\n script.addEventListener('error', () => {\n clearTimeout(timer);\n entry.state = 'failed';\n settle('failed');\n });\n\n if (!existing) {\n for (const [name, value] of Object.entries(attributes))\n script.setAttribute(name, value);\n // After the attributes, so they never replace the src or the marker.\n script.src = src;\n script.async = true;\n script.setAttribute(VENDOR_SCRIPT_MARKER, '');\n doc.head.appendChild(script);\n }\n\n return entry;\n}\n\nconst notLoaded = () =>\n new StepError('Vendor script failed to load', { code: 'vendor-not-loaded' });\n\nconst notReady = () =>\n new StepError('Vendor not ready: its global is missing', {\n code: 'vendor-not-ready',\n });\n\nconst timedOut = (timeout: number) =>\n new StepError(`Vendor script did not load within ${timeout}ms`, {\n code: 'vendor-timeout',\n });\n\n/**\n * Injects a vendor script once per `src` on the page (marked\n * `data-walkeros-vendor`, with the `attributes` its tag needs) and reports\n * its readiness. The deadline runs from the injection and equals the\n * destination's resolved timeout, so an awaited `ready()` settles before the\n * push's own timeout. Without `src` (the page loads the vendor) nothing is\n * injected and there is no deadline. A `src` with no document to inject\n * into (neither `options.document` nor a global one) throws\n * `vendor-not-ready`.\n */\nexport function loadVendor<T>(\n src: string | undefined,\n get: () => T | undefined,\n options: LoadVendorOptions = {},\n): Vendor<T> {\n const available = () => {\n const vendor = get();\n return vendor !== undefined && vendor !== null;\n };\n\n let script: Injected | undefined;\n if (src) {\n const doc =\n options.document ??\n (typeof document !== 'undefined' ? document : undefined);\n if (!doc)\n throw new StepError(`Vendor script ${src} has no document to go into`, {\n code: 'vendor-not-ready',\n });\n script = inject(\n doc,\n src,\n resolveDestinationTimeout(options.timeout),\n options.attributes ?? {},\n available,\n );\n }\n\n const present = (): Promise<T> => {\n const vendor = get();\n return vendor === undefined || vendor === null\n ? Promise.reject(notReady())\n : Promise.resolve(vendor);\n };\n\n return {\n ready() {\n if (!script) return present();\n if (script.state === 'failed') return Promise.reject(notLoaded());\n if (script.state === 'loaded' || script.expired) return present();\n\n return new Promise<T>((resolve, reject) => {\n script.waiting.push((outcome) => {\n if (outcome === 'failed') reject(notLoaded());\n else if (outcome === 'expired') reject(timedOut(script.timeout));\n else present().then(resolve, reject);\n });\n });\n },\n check() {\n if (script?.state === 'failed') throw notLoaded();\n },\n };\n}\n","import type { Flow } from '@walkeros/core';\nimport { VENDOR_SCRIPT_MARKER } from '../loadVendor';\n\n/**\n * The page a web step runs on in the conformance kit and the examples runner\n * of `@walkeros/collector/dev`. While a run is open, `navigator.sendBeacon`\n * and `XMLHttpRequest` answer through the kit's boundary (`sendWeb` runs on\n * them), and the scripts the run adds are tracked: a marked vendor script\n * loads unless `failScripts` fails it. Closing the run restores both and\n * removes those scripts, so the next run starts on the page it found (the\n * page is loadVendor's once-per-src registry).\n */\n\nconst macrotask = () => new Promise<void>((resolve) => setTimeout(resolve, 0));\n\nfunction bodyText(body: unknown): string {\n if (body === undefined) return '';\n return typeof body === 'string' ? body : JSON.stringify(body);\n}\n\n/**\n * Replace one property for a run; returns its restore. A property that did\n * not exist is deleted again.\n */\nfunction replace(target: object, key: string, value: unknown): () => void {\n const original = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, key, {\n value,\n configurable: true,\n writable: true,\n });\n return () => {\n if (original) Object.defineProperty(target, key, original);\n else Reflect.deleteProperty(target, key);\n };\n}\n\nfunction scriptsOf(doc: Document): HTMLScriptElement[] {\n return Array.from(doc.querySelectorAll('script'));\n}\n\n/**\n * `XMLHttpRequest` at the boundary: synchronous by default, as sendWeb opens\n * it; the async form answers late.\n */\nfunction kitXMLHttpRequest(record: Flow.StepRecord) {\n return class KitXMLHttpRequest {\n status = 0;\n statusText = '';\n response: unknown = '';\n responseText = '';\n readyState = 0;\n onload: (() => void) | null = null;\n onerror: (() => void) | null = null;\n onreadystatechange: (() => void) | null = null;\n private method = 'GET';\n private url = '';\n private async = true;\n\n open(method: string, url: string, async = true) {\n this.method = method;\n this.url = url;\n this.async = async;\n this.readyState = 1;\n }\n setRequestHeader() {}\n addEventListener(type: string, listener: () => void) {\n if (type === 'load') this.onload = listener;\n if (type === 'error') this.onerror = listener;\n }\n send(body?: unknown) {\n const { answer, settle } = record([\n 'XMLHttpRequest',\n this.method,\n this.url,\n body,\n ]);\n const done = () => {\n settle();\n this.readyState = 4;\n if (answer.error) {\n if (!this.async) throw new Error('NetworkError');\n this.onerror?.();\n return;\n }\n this.status = answer.status ?? 200;\n this.statusText = answer.statusText ?? '';\n this.responseText = bodyText(answer.body);\n this.response = this.responseText;\n this.onreadystatechange?.();\n this.onload?.();\n };\n if (this.async) macrotask().then(done);\n else done();\n }\n };\n}\n\nexport const page: Flow.StepPage = {\n open(record) {\n if (typeof document === 'undefined')\n throw new Error(\n 'the web page needs a document: run it in a jsdom test environment',\n );\n const doc = document;\n const before = new Set(scriptsOf(doc));\n const added = () => scriptsOf(doc).filter((script) => !before.has(script));\n\n const beacon = (url: string, data?: unknown): boolean => {\n const { answer, settle } = record(['sendBeacon', url, data]);\n settle();\n return !answer.error && (answer.status ?? 200) < 400;\n };\n const restores = [\n replace(window, 'XMLHttpRequest', kitXMLHttpRequest(record)),\n replace(navigator, 'sendBeacon', beacon),\n ];\n\n // A vendor script a run adds loads, as in a browser: once, right after\n // it is inserted (loadVendor listens before it inserts). jsdom fetches\n // no script, so without this answer every awaited script times out.\n const loaded = new WeakSet<Node>();\n const observer = new MutationObserver((mutations) => {\n for (const { addedNodes } of mutations)\n addedNodes.forEach((node) => {\n if (\n !(node instanceof HTMLScriptElement) ||\n !node.hasAttribute(VENDOR_SCRIPT_MARKER) ||\n loaded.has(node)\n )\n return;\n loaded.add(node);\n node.dispatchEvent(new Event('load'));\n });\n });\n observer.observe(doc, { childList: true, subtree: true });\n\n return {\n globals: { document: doc },\n scripts: () => {\n const scripts = added();\n const marked = scripts.filter((script) =>\n script.hasAttribute(VENDOR_SCRIPT_MARKER),\n ).length;\n return { marked, unmarked: scripts.length - marked };\n },\n failScripts: () => {\n doc\n .querySelectorAll(`script[${VENDOR_SCRIPT_MARKER}]`)\n .forEach((script) => script.dispatchEvent(new Event('error')));\n },\n close: () => {\n observer.disconnect();\n restores.splice(0).forEach((restore) => restore());\n added().forEach((script) => script.remove());\n },\n };\n },\n};\n"],"mappings":";AAqBO,SAAS,qBAAyC;AACvD,QAAM,UAAwB,CAAC;AAC/B,QAAM,QAAQ,oBAAI,QAAuC;AAEzD,SAAO;AAAA,IACL,kBAAkB,MAAM,CAAC,GAAG,OAAO;AAAA,IACnC,eAAe,MAAM;AACnB,YAAM,aAAa,oBAAI,IAAoB;AAC3C,YAAM,SAAqB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,WAAW,OAAO,cAAc,IAAI,MAAM,OAAO,CAAC,CAAC;AAAA,MACjE;AAAA,MACA,OAAO,MAAM;AACX,iBAAS,WAAW;AACpB,iBAAS,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,QAAQ,CAAC;AACjD,cAAM,EAAE,QAAQ,CAAC,WAAW,OAAO,OAAO,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Elb, Destination as Destination$1, MoinTarget, ObserveSlot, PreviewKey, PreviewCrypto, SendHeaders, SendResponse, SendDataValue, StorageType, WalkerOS, Source as Source$1, Collector as Collector$1, Hooks, On } from '@walkeros/core';
1
+ import { WalkerOS, Elb, Destination as Destination$1, MoinTarget, ObserveSlot, PreviewKey, PreviewCrypto, SendHeaders, SendResponse, SendDataValue, StorageType, Source as Source$1, Collector as Collector$1, Hooks, On } from '@walkeros/core';
2
2
 
3
3
  /**
4
4
  * Get attribute value from element
@@ -37,6 +37,32 @@ declare function getLanguage(navigatorRef: Navigator): string | undefined;
37
37
  declare function getTimezone(): string | undefined;
38
38
  declare function getScreenSize(windowRef: Window): string;
39
39
 
40
+ /**
41
+ * walkerOS consent groups mapped to consent mode parameters, as Google
42
+ * Consent Mode and the tools compatible with it (d8a) name them.
43
+ */
44
+ interface ConsentMapping {
45
+ [walkerOSConsentGroup: string]: string | string[];
46
+ }
47
+ type ConsentModeValue = 'granted' | 'denied';
48
+ /**
49
+ * Default mapping: measurement storage follows `analytics`, the ad
50
+ * parameters follow `marketing`.
51
+ */
52
+ declare const DEFAULT_CONSENT_MODE_MAPPING: ConsentMapping;
53
+ /** Every parameter a mapping names, once, in mapping order. */
54
+ declare function consentModeParameters(mapping: ConsentMapping): string[];
55
+ /**
56
+ * Resolve consent mode parameters from walkerOS consent.
57
+ *
58
+ * A parameter is granted only when every group that maps to it is granted in
59
+ * `state`, the whole consent state; a group missing from it counts as denied.
60
+ * With `changed`, the result holds only the parameters of those groups, as a
61
+ * consent update carries only what a consent command changed. Groups the
62
+ * mapping does not name resolve nothing.
63
+ */
64
+ declare function resolveConsentMode(mapping: ConsentMapping, state: WalkerOS.Consent, changed?: WalkerOS.Consent): Record<string, ConsentModeValue>;
65
+
40
66
  declare const elb$1: Elb.Fn<void>;
41
67
 
42
68
  type TypesGeneric$1 = Destination$1.TypesGeneric;
@@ -438,4 +464,4 @@ declare namespace collector {
438
464
  export type { collector_Collector as Collector, collector_Config as Config, collector_Destinations as Destinations, collector_InitConfig as InitConfig, collector_Scope as Scope, collector_State as State };
439
465
  }
440
466
 
441
- export { destination as DestinationWeb, elb as Elb, type LoadVendorOptions, SESSION_STORAGE_KEY, type SendWebOptions, type SendWebOptionsFetch, type SendWebReturn, type SendWebTransport, source as SourceWeb, type StorageEnv, type StorageValue, type SwapActivatorConfig, VENDOR_SCRIPT_MARKER, type Vendor, walker as Walker, collector as WebCollector, browserSwapActivator, composedAncestors, deepElementFromPoint, elb$1 as elb, getAttribute, getEnv, getHashWeb, getLanguage, getScreenSize, getTimezone, isVisible, loadVendor, moin, pageObserveSlot, parseInlineConfig, sendWeb, sendWebAsBeacon, sendWebAsFetch, sendWebAsXhr, shadowHostsAbove, splitAttribute, splitKeyVal, storageDelete, storageRead, storageWrite };
467
+ export { type ConsentMapping, type ConsentModeValue, DEFAULT_CONSENT_MODE_MAPPING, destination as DestinationWeb, elb as Elb, type LoadVendorOptions, SESSION_STORAGE_KEY, type SendWebOptions, type SendWebOptionsFetch, type SendWebReturn, type SendWebTransport, source as SourceWeb, type StorageEnv, type StorageValue, type SwapActivatorConfig, VENDOR_SCRIPT_MARKER, type Vendor, walker as Walker, collector as WebCollector, browserSwapActivator, composedAncestors, consentModeParameters, deepElementFromPoint, elb$1 as elb, getAttribute, getEnv, getHashWeb, getLanguage, getScreenSize, getTimezone, isVisible, loadVendor, moin, pageObserveSlot, parseInlineConfig, resolveConsentMode, sendWeb, sendWebAsBeacon, sendWebAsFetch, sendWebAsXhr, shadowHostsAbove, splitAttribute, splitKeyVal, storageDelete, storageRead, storageWrite };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Elb, Destination as Destination$1, MoinTarget, ObserveSlot, PreviewKey, PreviewCrypto, SendHeaders, SendResponse, SendDataValue, StorageType, WalkerOS, Source as Source$1, Collector as Collector$1, Hooks, On } from '@walkeros/core';
1
+ import { WalkerOS, Elb, Destination as Destination$1, MoinTarget, ObserveSlot, PreviewKey, PreviewCrypto, SendHeaders, SendResponse, SendDataValue, StorageType, Source as Source$1, Collector as Collector$1, Hooks, On } from '@walkeros/core';
2
2
 
3
3
  /**
4
4
  * Get attribute value from element
@@ -37,6 +37,32 @@ declare function getLanguage(navigatorRef: Navigator): string | undefined;
37
37
  declare function getTimezone(): string | undefined;
38
38
  declare function getScreenSize(windowRef: Window): string;
39
39
 
40
+ /**
41
+ * walkerOS consent groups mapped to consent mode parameters, as Google
42
+ * Consent Mode and the tools compatible with it (d8a) name them.
43
+ */
44
+ interface ConsentMapping {
45
+ [walkerOSConsentGroup: string]: string | string[];
46
+ }
47
+ type ConsentModeValue = 'granted' | 'denied';
48
+ /**
49
+ * Default mapping: measurement storage follows `analytics`, the ad
50
+ * parameters follow `marketing`.
51
+ */
52
+ declare const DEFAULT_CONSENT_MODE_MAPPING: ConsentMapping;
53
+ /** Every parameter a mapping names, once, in mapping order. */
54
+ declare function consentModeParameters(mapping: ConsentMapping): string[];
55
+ /**
56
+ * Resolve consent mode parameters from walkerOS consent.
57
+ *
58
+ * A parameter is granted only when every group that maps to it is granted in
59
+ * `state`, the whole consent state; a group missing from it counts as denied.
60
+ * With `changed`, the result holds only the parameters of those groups, as a
61
+ * consent update carries only what a consent command changed. Groups the
62
+ * mapping does not name resolve nothing.
63
+ */
64
+ declare function resolveConsentMode(mapping: ConsentMapping, state: WalkerOS.Consent, changed?: WalkerOS.Consent): Record<string, ConsentModeValue>;
65
+
40
66
  declare const elb$1: Elb.Fn<void>;
41
67
 
42
68
  type TypesGeneric$1 = Destination$1.TypesGeneric;
@@ -438,4 +464,4 @@ declare namespace collector {
438
464
  export type { collector_Collector as Collector, collector_Config as Config, collector_Destinations as Destinations, collector_InitConfig as InitConfig, collector_Scope as Scope, collector_State as State };
439
465
  }
440
466
 
441
- export { destination as DestinationWeb, elb as Elb, type LoadVendorOptions, SESSION_STORAGE_KEY, type SendWebOptions, type SendWebOptionsFetch, type SendWebReturn, type SendWebTransport, source as SourceWeb, type StorageEnv, type StorageValue, type SwapActivatorConfig, VENDOR_SCRIPT_MARKER, type Vendor, walker as Walker, collector as WebCollector, browserSwapActivator, composedAncestors, deepElementFromPoint, elb$1 as elb, getAttribute, getEnv, getHashWeb, getLanguage, getScreenSize, getTimezone, isVisible, loadVendor, moin, pageObserveSlot, parseInlineConfig, sendWeb, sendWebAsBeacon, sendWebAsFetch, sendWebAsXhr, shadowHostsAbove, splitAttribute, splitKeyVal, storageDelete, storageRead, storageWrite };
467
+ export { type ConsentMapping, type ConsentModeValue, DEFAULT_CONSENT_MODE_MAPPING, destination as DestinationWeb, elb as Elb, type LoadVendorOptions, SESSION_STORAGE_KEY, type SendWebOptions, type SendWebOptionsFetch, type SendWebReturn, type SendWebTransport, source as SourceWeb, type StorageEnv, type StorageValue, type SwapActivatorConfig, VENDOR_SCRIPT_MARKER, type Vendor, walker as Walker, collector as WebCollector, browserSwapActivator, composedAncestors, consentModeParameters, deepElementFromPoint, elb$1 as elb, getAttribute, getEnv, getHashWeb, getLanguage, getScreenSize, getTimezone, isVisible, loadVendor, moin, pageObserveSlot, parseInlineConfig, resolveConsentMode, sendWeb, sendWebAsBeacon, sendWebAsFetch, sendWebAsXhr, shadowHostsAbove, splitAttribute, splitKeyVal, storageDelete, storageRead, storageWrite };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i={};function a(e,t){return(e.getAttribute(t)||"").trim()}function s(e,t=";"){if(!e)return[];const n=new RegExp(`(?:\\\\[\\s\\S]?|'(?:\\\\[\\s\\S]|[^'\\\\])*'(?![\\w\\u0080-\\uffff])|[^${t}\\\\])+`,"g");return e.match(n)||[]}function c(e){const[,t=e,n=""]=e.match(/^((?:\\[\s\S]|[^\\:])*):([\s\S]*)$/)||[];return[l(t),l(n)]}function l(e){return e.replace(/^\s*'|\\([\s\S])|'\s*$/g,(e,t)=>t||"").trim()}function u(e){const t={};return s(e).forEach(e=>{const[n,o]=c(e);n&&("true"===o?t[n]=!0:"false"===o?t[n]=!1:o&&/^\d+$/.test(o)?t[n]=parseInt(o,10):o&&/^\d+\.\d+$/.test(o)?t[n]=parseFloat(o):t[n]=o||!0)}),t}function d(e){return e.language}function f(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function w(e){return`${e.screen.width}x${e.screen.height}`}((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(i,{DestinationWeb:()=>ie,Elb:()=>se,SESSION_STORAGE_KEY:()=>W,SourceWeb:()=>ae,VENDOR_SCRIPT_MARKER:()=>O,Walker:()=>le,WebCollector:()=>ce,browserSwapActivator:()=>H,composedAncestors:()=>y,deepElementFromPoint:()=>v,elb:()=>g,getAttribute:()=>a,getEnv:()=>p,getHashWeb:()=>S,getLanguage:()=>d,getScreenSize:()=>w,getTimezone:()=>f,isVisible:()=>E,loadVendor:()=>C,moin:()=>L,pageObserveSlot:()=>x,parseInlineConfig:()=>u,sendWeb:()=>z,sendWebAsBeacon:()=>Z,sendWebAsFetch:()=>X,sendWebAsXhr:()=>Q,shadowHostsAbove:()=>b,splitAttribute:()=>s,splitKeyVal:()=>c,storageDelete:()=>ne,storageRead:()=>oe,storageWrite:()=>re}),module.exports=(e=i,((e,i,a,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of o(i))r.call(e,c)||c===a||t(e,c,{get:()=>i[c],enumerable:!(s=n(i,c))||s.enumerable});return e})(t({},"__esModule",{value:!0}),e));var g=function(){const e=window;(e.elbLayer=e.elbLayer||[]).push(arguments)},m=require("@walkeros/core");function p(e){const t={window:"undefined"!=typeof window?window:globalThis.window,document:"undefined"!=typeof document?document:globalThis.document,...e},n=e&&e[m.OBSERVE_ENV_KEY];if(("undefined"==typeof __WALKEROS_OBSERVE__||__WALKEROS_OBSERVE__)&&(0,m.isEnvObserve)(n)){delete t[m.OBSERVE_ENV_KEY];const e=(0,m.observeEnv)(t,n.paths,n.record).env,o=new Set;for(const e of n.paths){const n=(0,m.parseCallPath)(e)[0];if(void 0===n)continue;const r=t[n];null!==r&&"object"==typeof r&&o.add(n)}const r=Array.from(o,t=>[t,e[t]]);for(const[e,n]of r)t[e]=n}return t}var h=require("@walkeros/core");async function S(e,t){return(await async function(e){const t=(0,h.isDefined)(window)&&window.crypto?window.crypto:void 0;if(!t||!t.subtle||!TextEncoder)return;const n=(new TextEncoder).encode(e),o=await t.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)||"").slice(0,t)}function v(e,t,n){let o=e.elementFromPoint(t,n);for(;o&&o.shadowRoot;){const e=o.shadowRoot.elementFromPoint(t,n);if(!e||e===o)break;o=e}return o}function y(e,t){const n=[];let o=e;for(;o;){let e=o.parentElement;if(!e){const n=o.getRootNode();n instanceof t.self.ShadowRoot&&(e=n.host)}if(!e)break;n.push(e),o=e}return n}function b(e,t){const n=[];let o=e.getRootNode();for(;o instanceof t.self.ShadowRoot;)n.push(o.host),o=o.host.getRootNode();return n}function E(e,t,n){if(!function(e,t){const n=t.getComputedStyle(e);if("none"===n.display)return!1;if("visible"!==n.visibility)return!1;let o=e;for(;o;){const e=t.getComputedStyle(o).opacity;if(e&&Number(e)<.1)return!1;const n=o.parentElement;if(n){o=n;continue}const r=o.getRootNode();o=r instanceof t.self.ShadowRoot?r.host:null}return!0}(e,t))return!1;const o=e.getBoundingClientRect(),r=n.documentElement.clientWidth||t.innerWidth,i=n.documentElement.clientHeight||t.innerHeight,a=Math.max(o.left,0),s=Math.max(o.top,0),c=Math.min(o.right,r),l=Math.min(o.bottom,i);if(c<=a||l<=s)return!1;const u=v(n,(a+c)/2,(s+l)/2);return!!u&&(u===e||(!!y(u,t).includes(e)||!!b(e,t).includes(u)))}var R=require("@walkeros/core"),O="data-walkeros-vendor",A=new WeakMap;function _(e,t,n,o,r){const i=function(e,t){const n=e.querySelectorAll(`script[${O}]`);return Array.from(n).find(e=>e.getAttribute("src")===t)}(e,t),a=i&&A.get(i);if(a)return a;const s={state:"loading",expired:!1,timeout:n,waiting:[]};if(i&&r())return s.state="loaded",A.set(i,s),s;const c=null!=i?i:e.createElement("script"),l=e=>{const t=s.waiting;s.waiting=[],t.forEach(t=>t(e))},u=setTimeout(()=>{s.expired=!0,l("expired")},n);if(A.set(c,s),c.addEventListener("load",()=>{clearTimeout(u),s.state="loaded",l("loaded")}),c.addEventListener("error",()=>{clearTimeout(u),s.state="failed",l("failed")}),!i){for(const[e,t]of Object.entries(o))c.setAttribute(e,t);c.src=t,c.async=!0,c.setAttribute(O,""),e.head.appendChild(c)}return s}var k=()=>new R.StepError("Vendor script failed to load",{code:"vendor-not-loaded"}),P=()=>new R.StepError("Vendor not ready: its global is missing",{code:"vendor-not-ready"}),$=e=>new R.StepError(`Vendor script did not load within ${e}ms`,{code:"vendor-timeout"});function C(e,t,n={}){var o,r;const i=()=>{const e=t();return null!=e};let a;if(e){const t=null!=(o=n.document)?o:"undefined"!=typeof document?document:void 0;if(!t)throw new R.StepError(`Vendor script ${e} has no document to go into`,{code:"vendor-not-ready"});a=_(t,e,(0,R.resolveDestinationTimeout)(n.timeout),null!=(r=n.attributes)?r:{},i)}const s=()=>{const e=t();return null==e?Promise.reject(P()):Promise.resolve(e)};return{ready:()=>a?"failed"===a.state?Promise.reject(k()):"loaded"===a.state||a.expired?s():new Promise((e,t)=>{a.waiting.push(n=>{"failed"===n?t(k()):"expired"===n?t($(a.timeout)):s().then(e,t)})}):s(),check(){if("failed"===(null==a?void 0:a.state))throw k()}}}var T=require("@walkeros/core");function I(e,t,n){return new Promise(o=>{let r,i,a=!1;const s=e=>{a||(a=!0,o(e),void 0!==i&&clearTimeout(i),!e&&(null==r?void 0:r.parentNode)&&r.parentNode.removeChild(r))};try{if("undefined"==typeof document)return void s(!1);r=document.createElement("script"),void 0!==n&&(i=setTimeout(()=>s(!1),n)),r.onload=()=>s(!0),r.onerror=()=>s(!1),r.setAttribute("integrity",t),r.setAttribute("crossorigin","anonymous"),r.async=!0,r.src=e,document.head.appendChild(r)}catch(e){s(!1)}})}var U=/^[A-Za-z0-9_-]{64}$/,V=Symbol.for("walkeros.moin");function L(e=T.MOIN_PRODUCTION){"undefined"!=typeof window&&function(e,t){try{if("undefined"==typeof URLSearchParams||e.top!==e||Reflect.get(e,V))return;let n=new URLSearchParams(e.location.search).has(T.MOIN_PARAM);try{const t=e.sessionStorage;n=n||"1"===t.getItem(T.MOIN_PARAM),n&&t.setItem(T.MOIN_PARAM,"1")}catch(e){}if(!n)return;Reflect.set(e,V,!0);const o=n=>{if(n.origin!==t.app)return;const r=n.data;if("object"!=typeof r||null===r)return;if(1!==Reflect.get(r,"elbMoin"))return;const i=Reflect.get(r,"file");"string"==typeof i&&U.test(i)&&(e.removeEventListener("message",o,!0),I(`${t.base}${i}.js`,`sha384-${i.replace(/-/g,"+").replace(/_/g,"/")}`))};e.addEventListener("message",o,!0)}catch(e){}}(window,e)}var N=require("@walkeros/core");function x(){return{read(){const e=function(){var e;try{const t=new URLSearchParams(window.location.search.replace(/^\?/,"")).getAll(N.OBSERVE_STORAGE_KEY);return t.length>0&&null!=(e=t[t.length-1])?e:null}catch(e){return null}}(),t=null!=e?e:function(){try{return window.localStorage.getItem(N.OBSERVE_STORAGE_KEY)}catch(e){return null}}();return t?{raw:t,fromUrl:null!==e}:null},keep(e,t){!function(e){try{window.localStorage.setItem(N.OBSERVE_STORAGE_KEY,e)}catch(e){}}(e),t&&function(){try{const e=window.location.href,t=e.indexOf("#"),n=t>=0?e.slice(t):"",o=t>=0?e.slice(0,t):e,r=o.indexOf("?"),i=r>=0?o.slice(0,r):o,a=new URLSearchParams(r>=0?o.slice(r+1):"");a.delete(N.OBSERVE_STORAGE_KEY);const s=a.toString();window.history.replaceState({},"",`${i}${s?`?${s}`:""}${n}`)}catch(e){}}()},clear(e){!function(e){try{window.localStorage.getItem(N.OBSERVE_STORAGE_KEY)===e&&window.localStorage.removeItem(N.OBSERVE_STORAGE_KEY)}catch(e){}}(e)}}}var M=require("@walkeros/core"),j="elbPreview",W="elbPreviewSession",B="[walkerOS:preview]",D=5e3;function K(e){let t=null;return{get(){var n;try{return null!=(n=window.localStorage.getItem(e))?n:t}catch(e){return t}},set(n){try{window.localStorage.setItem(e,n)}catch(e){t=n}},clear(){t=null;try{window.localStorage.removeItem(e)}catch(e){}}}}function q(){if("undefined"!=typeof URLSearchParams)try{const e=window.location.href,t=e.indexOf("#"),n=t>=0?e.slice(t):"",o=t>=0?e.slice(0,t):e,r=o.indexOf("?"),i=r>=0?o.slice(0,r):o,a=new URLSearchParams(r>=0?o.slice(r+1):"");a.delete("elbPreview"),a.delete("elbPreviewSession"),a.delete("elbObserve");const s=a.toString();window.history.replaceState({},"",`${i}${s?`?${s}`:""}${n}`)}catch(e){}}async function H(e){var t,n,o,r;if("undefined"==typeof window||"undefined"==typeof document)return!1;const i=window,a=K(j),s=K(W),c=K(M.OBSERVE_STORAGE_KEY),l=null!=(t=e.now)?t:()=>Date.now(),u=e=>console.warn(`${B} ${e}`);let d=null,f=null,w=null;if("undefined"!=typeof URLSearchParams)try{const e=new URLSearchParams(i.location.search.replace(/^\?/,"")),t=e.getAll("elbPreview");d=t.length>0&&null!=(n=t[t.length-1])?n:null;const a=e.getAll("elbPreviewSession");f=a.length>0&&null!=(o=a[a.length-1])?o:null;const s=e.getAll("elbObserve");w=s.length>0&&null!=(r=s[s.length-1])?r:null}catch(e){d=null,f=null,w=null}if("off"===d)return a.clear(),s.clear(),c.clear(),q(),!1;const g=a.get();if(!d&&!g)return!1;const m=(t,n)=>(0,M.verifyActivation)(t,{keyring:e.keyring,iss:e.iss,origin:i.location.origin,pb:e.pb,acceptForeign:e.acceptForeign,demoAllowlist:e.demoAllowlist,source:n,now:l(),crypto:e.crypto});let p=null;if(d){const e=await m(d,"url");e.ok?(p=e.grant,a.set(d),f?s.set(f):s.clear(),w?c.set(w):c.clear()):u(e.reason),q()}if(!p&&g){const e=await m(g,"storage");e.ok?p=e.grant:(u(e.reason),"no-subtle"!==e.reason&&(a.clear(),s.clear(),c.clear()))}if(!p)return!1;const h=`https://${e.previewOrigin}/preview/${p.art}.js`;return await I(h,p.sri,D)?(console.info(`${B} active ${p.art} ends ${new Date(1e3*p.sxp).toISOString()}`),!0):(u("swap-failed"),a.clear(),s.clear(),c.clear(),!1)}var Y=require("@walkeros/core"),F=1e4,G=65536,J=0;function z(e,t,n={transport:"fetch"}){switch(n.transport||"fetch"){case"beacon":return Z(e,t);case"xhr":return Q(e,t,n);default:return X(e,t,n)}}async function X(e,t,n={}){const o=(0,Y.getHeaders)(n.headers),r=(0,Y.transformData)(t),i=n.timeout,a="number"==typeof i&&Number.isFinite(i)&&i>0?i:F,s=new AbortController,c=setTimeout(()=>s.abort(),a),l=r?ee(r):0,u=J+l<=G;u&&(J+=l);try{let t;try{t=await fetch(e,{method:n.method||"POST",headers:o,keepalive:u,credentials:n.credentials||"same-origin",mode:n.noCors?"no-cors":"cors",body:r,signal:s.signal})}catch(e){if(s.signal.aborted)throw new Y.StepError(`Request timed out after ${a}ms`,{code:"timeout",cause:e});throw new Y.StepError((0,Y.networkErrorMessage)(e),{code:"transport",cause:e})}if(n.noCors)return{data:""};const i=await t.text();if(!t.ok)throw new Y.StepError(`HTTP ${t.status}`,{code:"transport",status:t.status,body:i});return{data:i}}finally{clearTimeout(c),u&&(J-=l)}}function Z(e,t){const n=(0,Y.transformData)(t);if(!navigator.sendBeacon(e,n)){const e=n?ee(n):0;throw new Y.StepError("Beacon rejected by the browser",{code:"beacon-rejected",retryable:e<=G})}return{}}function Q(e,t,n={}){const o=(0,Y.getHeaders)(n.headers),r=n.method||"POST",i=(0,Y.transformData)(t);let a;try{a=new XMLHttpRequest,a.open(r,e,!1);for(const e in o)a.setRequestHeader(e,o[e]);a.send(i)}catch(e){throw new Y.StepError((0,Y.networkErrorMessage)(e),{code:"transport",cause:e})}const s=(0,Y.tryCatch)(JSON.parse,()=>a.response)(a.response);if(a.status<200||a.status>=300)throw new Y.StepError(`HTTP ${a.status}`,{code:"transport",status:a.status||void 0,body:s});return{data:s}}function ee(e){let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);o<128?t+=1:o<2048?t+=2:o>=55296&&o<=56319?(t+=4,n++):t+=3}return t}var te=require("@walkeros/core");function ne(e,t=te.Const.Utils.Storage.Session,n,o){var r,i;try{switch(t){case te.Const.Utils.Storage.Cookie:re(e,"",0,t,n,o);break;case te.Const.Utils.Storage.Local:(null!=(r=null==o?void 0:o.window)?r:window).localStorage.removeItem(e);break;case te.Const.Utils.Storage.Session:(null!=(i=null==o?void 0:o.window)?i:window).sessionStorage.removeItem(e)}}catch(e){}}function oe(e,t=te.Const.Utils.Storage.Session,n){var o,r,i,a;function s(e){try{return JSON.parse(e||"")}catch(t){let n=1,o="";return e&&(n=0,o=e),{e:n,v:o}}}let c,l;try{switch(t){case te.Const.Utils.Storage.Cookie:c=decodeURIComponent((null==(r=(null!=(o=null==n?void 0:n.document)?o:document).cookie.split("; ").find(t=>t.startsWith(e+"=")))?void 0:r.split("=")[1])||"");break;case te.Const.Utils.Storage.Local:l=s((null!=(i=null==n?void 0:n.window)?i:window).localStorage.getItem(e));break;case te.Const.Utils.Storage.Session:l=s((null!=(a=null==n?void 0:n.window)?a:window).sessionStorage.getItem(e))}}catch(e){return(0,te.castValue)("")}return l&&(c=l.v,0!=l.e&&l.e<Date.now()&&(ne(e,t,void 0,n),c="")),(0,te.castValue)(c||"")}function re(e,t,n=30,o=te.Const.Utils.Storage.Session,r,i){var a,s,c;const l={e:Date.now()+6e4*n,v:String(t)},u=JSON.stringify(l);try{switch(o){case te.Const.Utils.Storage.Cookie:{t="object"==typeof t?JSON.stringify(t):t;let o=`${e}=${encodeURIComponent(t)}; max-age=${60*n}; path=/; SameSite=Lax; secure`;r&&(o+="; domain="+r),(null!=(a=null==i?void 0:i.document)?a:document).cookie=o;break}case te.Const.Utils.Storage.Local:(null!=(s=null==i?void 0:i.window)?s:window).localStorage.setItem(e,u);break;case te.Const.Utils.Storage.Session:(null!=(c=null==i?void 0:i.window)?c:window).sessionStorage.setItem(e,u)}}catch(e){return(0,te.castValue)("")}return oe(e,o,i)}var ie={},ae={},se={},ce={},le={};//# sourceMappingURL=index.js.map
1
+ "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a={};function i(e,t){return(e.getAttribute(t)||"").trim()}function s(e,t=";"){if(!e)return[];const n=new RegExp(`(?:\\\\[\\s\\S]?|'(?:\\\\[\\s\\S]|[^'\\\\])*'(?![\\w\\u0080-\\uffff])|[^${t}\\\\])+`,"g");return e.match(n)||[]}function c(e){const[,t=e,n=""]=e.match(/^((?:\\[\s\S]|[^\\:])*):([\s\S]*)$/)||[];return[l(t),l(n)]}function l(e){return e.replace(/^\s*'|\\([\s\S])|'\s*$/g,(e,t)=>t||"").trim()}function u(e){const t={};return s(e).forEach(e=>{const[n,o]=c(e);n&&("true"===o?t[n]=!0:"false"===o?t[n]=!1:o&&/^\d+$/.test(o)?t[n]=parseInt(o,10):o&&/^\d+\.\d+$/.test(o)?t[n]=parseFloat(o):t[n]=o||!0)}),t}function d(e){return e.language}function f(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function w(e){return`${e.screen.width}x${e.screen.height}`}((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(a,{DEFAULT_CONSENT_MODE_MAPPING:()=>g,DestinationWeb:()=>le,Elb:()=>de,SESSION_STORAGE_KEY:()=>q,SourceWeb:()=>ue,VENDOR_SCRIPT_MARKER:()=>k,Walker:()=>we,WebCollector:()=>fe,browserSwapActivator:()=>z,composedAncestors:()=>R,consentModeParameters:()=>p,deepElementFromPoint:()=>O,elb:()=>S,getAttribute:()=>i,getEnv:()=>v,getHashWeb:()=>E,getLanguage:()=>d,getScreenSize:()=>w,getTimezone:()=>f,isVisible:()=>_,loadVendor:()=>N,moin:()=>j,pageObserveSlot:()=>W,parseInlineConfig:()=>u,resolveConsentMode:()=>h,sendWeb:()=>ee,sendWebAsBeacon:()=>ne,sendWebAsFetch:()=>te,sendWebAsXhr:()=>oe,shadowHostsAbove:()=>A,splitAttribute:()=>s,splitKeyVal:()=>c,storageDelete:()=>ie,storageRead:()=>se,storageWrite:()=>ce}),module.exports=(e=a,((e,a,i,s)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of o(a))r.call(e,c)||c===i||t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e})(t({},"__esModule",{value:!0}),e));var g={marketing:["ad_storage","ad_user_data","ad_personalization"],analytics:["analytics_storage"]};function m(e){return Array.isArray(e)?e:[e]}function p(e){const t=new Set;return Object.values(e).forEach(e=>m(e).forEach(e=>t.add(e))),[...t]}function h(e,t,n){const o=new Map;Object.entries(e).forEach(([e,t])=>m(t).forEach(t=>{var n;o.set(t,[...null!=(n=o.get(t))?n:[],e])}));const r=n?new Set(Object.keys(n).flatMap(t=>Object.prototype.hasOwnProperty.call(e,t)?m(e[t]):[])):new Set(o.keys()),a={};return r.forEach(e=>{const n=o.get(e),r=!!n&&n.every(e=>!0===t[e]);a[e]=r?"granted":"denied"}),a}var S=function(){const e=window;(e.elbLayer=e.elbLayer||[]).push(arguments)},y=require("@walkeros/core");function v(e){const t={window:"undefined"!=typeof window?window:globalThis.window,document:"undefined"!=typeof document?document:globalThis.document,...e},n=e&&e[y.OBSERVE_ENV_KEY];if(("undefined"==typeof __WALKEROS_OBSERVE__||__WALKEROS_OBSERVE__)&&(0,y.isEnvObserve)(n)){delete t[y.OBSERVE_ENV_KEY];const e=(0,y.observeEnv)(t,n.paths,n.record).env,o=new Set;for(const e of n.paths){const n=(0,y.parseCallPath)(e)[0];if(void 0===n)continue;const r=t[n];null!==r&&"object"==typeof r&&o.add(n)}const r=Array.from(o,t=>[t,e[t]]);for(const[e,n]of r)t[e]=n}return t}var b=require("@walkeros/core");async function E(e,t){return(await async function(e){const t=(0,b.isDefined)(window)&&window.crypto?window.crypto:void 0;if(!t||!t.subtle||!TextEncoder)return;const n=(new TextEncoder).encode(e),o=await t.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)||"").slice(0,t)}function O(e,t,n){let o=e.elementFromPoint(t,n);for(;o&&o.shadowRoot;){const e=o.shadowRoot.elementFromPoint(t,n);if(!e||e===o)break;o=e}return o}function R(e,t){const n=[];let o=e;for(;o;){let e=o.parentElement;if(!e){const n=o.getRootNode();n instanceof t.self.ShadowRoot&&(e=n.host)}if(!e)break;n.push(e),o=e}return n}function A(e,t){const n=[];let o=e.getRootNode();for(;o instanceof t.self.ShadowRoot;)n.push(o.host),o=o.host.getRootNode();return n}function _(e,t,n){if(!function(e,t){const n=t.getComputedStyle(e);if("none"===n.display)return!1;if("visible"!==n.visibility)return!1;let o=e;for(;o;){const e=t.getComputedStyle(o).opacity;if(e&&Number(e)<.1)return!1;const n=o.parentElement;if(n){o=n;continue}const r=o.getRootNode();o=r instanceof t.self.ShadowRoot?r.host:null}return!0}(e,t))return!1;const o=e.getBoundingClientRect(),r=n.documentElement.clientWidth||t.innerWidth,a=n.documentElement.clientHeight||t.innerHeight,i=Math.max(o.left,0),s=Math.max(o.top,0),c=Math.min(o.right,r),l=Math.min(o.bottom,a);if(c<=i||l<=s)return!1;const u=O(n,(i+c)/2,(s+l)/2);return!!u&&(u===e||(!!R(u,t).includes(e)||!!A(e,t).includes(u)))}var P=require("@walkeros/core"),k="data-walkeros-vendor",C=new WeakMap;function $(e,t,n,o,r){const a=function(e,t){const n=e.querySelectorAll(`script[${k}]`);return Array.from(n).find(e=>e.getAttribute("src")===t)}(e,t),i=a&&C.get(a);if(i)return i;const s={state:"loading",expired:!1,timeout:n,waiting:[]};if(a&&r())return s.state="loaded",C.set(a,s),s;const c=null!=a?a:e.createElement("script"),l=e=>{const t=s.waiting;s.waiting=[],t.forEach(t=>t(e))},u=setTimeout(()=>{s.expired=!0,l("expired")},n);if(C.set(c,s),c.addEventListener("load",()=>{clearTimeout(u),s.state="loaded",l("loaded")}),c.addEventListener("error",()=>{clearTimeout(u),s.state="failed",l("failed")}),!a){for(const[e,t]of Object.entries(o))c.setAttribute(e,t);c.src=t,c.async=!0,c.setAttribute(k,""),e.head.appendChild(c)}return s}var T=()=>new P.StepError("Vendor script failed to load",{code:"vendor-not-loaded"}),I=()=>new P.StepError("Vendor not ready: its global is missing",{code:"vendor-not-ready"}),U=e=>new P.StepError(`Vendor script did not load within ${e}ms`,{code:"vendor-timeout"});function N(e,t,n={}){var o,r;const a=()=>{const e=t();return null!=e};let i;if(e){const t=null!=(o=n.document)?o:"undefined"!=typeof document?document:void 0;if(!t)throw new P.StepError(`Vendor script ${e} has no document to go into`,{code:"vendor-not-ready"});i=$(t,e,(0,P.resolveDestinationTimeout)(n.timeout),null!=(r=n.attributes)?r:{},a)}const s=()=>{const e=t();return null==e?Promise.reject(I()):Promise.resolve(e)};return{ready:()=>i?"failed"===i.state?Promise.reject(T()):"loaded"===i.state||i.expired?s():new Promise((e,t)=>{i.waiting.push(n=>{"failed"===n?t(T()):"expired"===n?t(U(i.timeout)):s().then(e,t)})}):s(),check(){if("failed"===(null==i?void 0:i.state))throw T()}}}var M=require("@walkeros/core");function V(e,t,n){return new Promise(o=>{let r,a,i=!1;const s=e=>{i||(i=!0,o(e),void 0!==a&&clearTimeout(a),!e&&(null==r?void 0:r.parentNode)&&r.parentNode.removeChild(r))};try{if("undefined"==typeof document)return void s(!1);r=document.createElement("script"),void 0!==n&&(a=setTimeout(()=>s(!1),n)),r.onload=()=>s(!0),r.onerror=()=>s(!1),r.setAttribute("integrity",t),r.setAttribute("crossorigin","anonymous"),r.async=!0,r.src=e,document.head.appendChild(r)}catch(e){s(!1)}})}var L=/^[A-Za-z0-9_-]{64}$/,x=Symbol.for("walkeros.moin");function j(e=M.MOIN_PRODUCTION){"undefined"!=typeof window&&function(e,t){try{if("undefined"==typeof URLSearchParams||e.top!==e||Reflect.get(e,x))return;let n=new URLSearchParams(e.location.search).has(M.MOIN_PARAM);try{const t=e.sessionStorage;n=n||"1"===t.getItem(M.MOIN_PARAM),n&&t.setItem(M.MOIN_PARAM,"1")}catch(e){}if(!n)return;Reflect.set(e,x,!0);const o=n=>{if(n.origin!==t.app)return;const r=n.data;if("object"!=typeof r||null===r)return;if(1!==Reflect.get(r,"elbMoin"))return;const a=Reflect.get(r,"file");"string"==typeof a&&L.test(a)&&(e.removeEventListener("message",o,!0),V(`${t.base}${a}.js`,`sha384-${a.replace(/-/g,"+").replace(/_/g,"/")}`))};e.addEventListener("message",o,!0)}catch(e){}}(window,e)}var D=require("@walkeros/core");function W(){return{read(){const e=function(){var e;try{const t=new URLSearchParams(window.location.search.replace(/^\?/,"")).getAll(D.OBSERVE_STORAGE_KEY);return t.length>0&&null!=(e=t[t.length-1])?e:null}catch(e){return null}}(),t=null!=e?e:function(){try{return window.localStorage.getItem(D.OBSERVE_STORAGE_KEY)}catch(e){return null}}();return t?{raw:t,fromUrl:null!==e}:null},keep(e,t){!function(e){try{window.localStorage.setItem(D.OBSERVE_STORAGE_KEY,e)}catch(e){}}(e),t&&function(){try{const e=window.location.href,t=e.indexOf("#"),n=t>=0?e.slice(t):"",o=t>=0?e.slice(0,t):e,r=o.indexOf("?"),a=r>=0?o.slice(0,r):o,i=new URLSearchParams(r>=0?o.slice(r+1):"");i.delete(D.OBSERVE_STORAGE_KEY);const s=i.toString();window.history.replaceState({},"",`${a}${s?`?${s}`:""}${n}`)}catch(e){}}()},clear(e){!function(e){try{window.localStorage.getItem(D.OBSERVE_STORAGE_KEY)===e&&window.localStorage.removeItem(D.OBSERVE_STORAGE_KEY)}catch(e){}}(e)}}}var B=require("@walkeros/core"),K="elbPreview",q="elbPreviewSession",H="[walkerOS:preview]",F=5e3;function Y(e){let t=null;return{get(){var n;try{return null!=(n=window.localStorage.getItem(e))?n:t}catch(e){return t}},set(n){try{window.localStorage.setItem(e,n)}catch(e){t=n}},clear(){t=null;try{window.localStorage.removeItem(e)}catch(e){}}}}function G(){if("undefined"!=typeof URLSearchParams)try{const e=window.location.href,t=e.indexOf("#"),n=t>=0?e.slice(t):"",o=t>=0?e.slice(0,t):e,r=o.indexOf("?"),a=r>=0?o.slice(0,r):o,i=new URLSearchParams(r>=0?o.slice(r+1):"");i.delete("elbPreview"),i.delete("elbPreviewSession"),i.delete("elbObserve");const s=i.toString();window.history.replaceState({},"",`${a}${s?`?${s}`:""}${n}`)}catch(e){}}async function z(e){var t,n,o,r;if("undefined"==typeof window||"undefined"==typeof document)return!1;const a=window,i=Y(K),s=Y(q),c=Y(B.OBSERVE_STORAGE_KEY),l=null!=(t=e.now)?t:()=>Date.now(),u=e=>console.warn(`${H} ${e}`);let d=null,f=null,w=null;if("undefined"!=typeof URLSearchParams)try{const e=new URLSearchParams(a.location.search.replace(/^\?/,"")),t=e.getAll("elbPreview");d=t.length>0&&null!=(n=t[t.length-1])?n:null;const i=e.getAll("elbPreviewSession");f=i.length>0&&null!=(o=i[i.length-1])?o:null;const s=e.getAll("elbObserve");w=s.length>0&&null!=(r=s[s.length-1])?r:null}catch(e){d=null,f=null,w=null}if("off"===d)return i.clear(),s.clear(),c.clear(),G(),!1;const g=i.get();if(!d&&!g)return!1;const m=(t,n)=>(0,B.verifyActivation)(t,{keyring:e.keyring,iss:e.iss,origin:a.location.origin,pb:e.pb,acceptForeign:e.acceptForeign,demoAllowlist:e.demoAllowlist,source:n,now:l(),crypto:e.crypto});let p=null;if(d){const e=await m(d,"url");e.ok?(p=e.grant,i.set(d),f?s.set(f):s.clear(),w?c.set(w):c.clear()):u(e.reason),G()}if(!p&&g){const e=await m(g,"storage");e.ok?p=e.grant:(u(e.reason),"no-subtle"!==e.reason&&(i.clear(),s.clear(),c.clear()))}if(!p)return!1;const h=`https://${e.previewOrigin}/preview/${p.art}.js`;return await V(h,p.sri,F)?(console.info(`${H} active ${p.art} ends ${new Date(1e3*p.sxp).toISOString()}`),!0):(u("swap-failed"),i.clear(),s.clear(),c.clear(),!1)}var J=require("@walkeros/core"),X=1e4,Z=65536,Q=0;function ee(e,t,n={transport:"fetch"}){switch(n.transport||"fetch"){case"beacon":return ne(e,t);case"xhr":return oe(e,t,n);default:return te(e,t,n)}}async function te(e,t,n={}){const o=(0,J.getHeaders)(n.headers),r=(0,J.transformData)(t),a=n.timeout,i="number"==typeof a&&Number.isFinite(a)&&a>0?a:X,s=new AbortController,c=setTimeout(()=>s.abort(),i),l=r?re(r):0,u=Q+l<=Z;u&&(Q+=l);try{let t;try{t=await fetch(e,{method:n.method||"POST",headers:o,keepalive:u,credentials:n.credentials||"same-origin",mode:n.noCors?"no-cors":"cors",body:r,signal:s.signal})}catch(e){if(s.signal.aborted)throw new J.StepError(`Request timed out after ${i}ms`,{code:"timeout",cause:e});throw new J.StepError((0,J.networkErrorMessage)(e),{code:"transport",cause:e})}if(n.noCors)return{data:""};const a=await t.text();if(!t.ok)throw new J.StepError(`HTTP ${t.status}`,{code:"transport",status:t.status,body:a});return{data:a}}finally{clearTimeout(c),u&&(Q-=l)}}function ne(e,t){const n=(0,J.transformData)(t);if(!navigator.sendBeacon(e,n)){const e=n?re(n):0;throw new J.StepError("Beacon rejected by the browser",{code:"beacon-rejected",retryable:e<=Z})}return{}}function oe(e,t,n={}){const o=(0,J.getHeaders)(n.headers),r=n.method||"POST",a=(0,J.transformData)(t);let i;try{i=new XMLHttpRequest,i.open(r,e,!1);for(const e in o)i.setRequestHeader(e,o[e]);i.send(a)}catch(e){throw new J.StepError((0,J.networkErrorMessage)(e),{code:"transport",cause:e})}const s=(0,J.tryCatch)(JSON.parse,()=>i.response)(i.response);if(i.status<200||i.status>=300)throw new J.StepError(`HTTP ${i.status}`,{code:"transport",status:i.status||void 0,body:s});return{data:s}}function re(e){let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);o<128?t+=1:o<2048?t+=2:o>=55296&&o<=56319?(t+=4,n++):t+=3}return t}var ae=require("@walkeros/core");function ie(e,t=ae.Const.Utils.Storage.Session,n,o){var r,a;try{switch(t){case ae.Const.Utils.Storage.Cookie:ce(e,"",0,t,n,o);break;case ae.Const.Utils.Storage.Local:(null!=(r=null==o?void 0:o.window)?r:window).localStorage.removeItem(e);break;case ae.Const.Utils.Storage.Session:(null!=(a=null==o?void 0:o.window)?a:window).sessionStorage.removeItem(e)}}catch(e){}}function se(e,t=ae.Const.Utils.Storage.Session,n){var o,r,a,i;function s(e){try{return JSON.parse(e||"")}catch(t){let n=1,o="";return e&&(n=0,o=e),{e:n,v:o}}}let c,l;try{switch(t){case ae.Const.Utils.Storage.Cookie:c=decodeURIComponent((null==(r=(null!=(o=null==n?void 0:n.document)?o:document).cookie.split("; ").find(t=>t.startsWith(e+"=")))?void 0:r.split("=")[1])||"");break;case ae.Const.Utils.Storage.Local:l=s((null!=(a=null==n?void 0:n.window)?a:window).localStorage.getItem(e));break;case ae.Const.Utils.Storage.Session:l=s((null!=(i=null==n?void 0:n.window)?i:window).sessionStorage.getItem(e))}}catch(e){return(0,ae.castValue)("")}return l&&(c=l.v,0!=l.e&&l.e<Date.now()&&(ie(e,t,void 0,n),c="")),(0,ae.castValue)(c||"")}function ce(e,t,n=30,o=ae.Const.Utils.Storage.Session,r,a){var i,s,c;const l={e:Date.now()+6e4*n,v:String(t)},u=JSON.stringify(l);try{switch(o){case ae.Const.Utils.Storage.Cookie:{t="object"==typeof t?JSON.stringify(t):t;let o=`${e}=${encodeURIComponent(t)}; max-age=${60*n}; path=/; SameSite=Lax; secure`;r&&(o+="; domain="+r),(null!=(i=null==a?void 0:a.document)?i:document).cookie=o;break}case ae.Const.Utils.Storage.Local:(null!=(s=null==a?void 0:a.window)?s:window).localStorage.setItem(e,u);break;case ae.Const.Utils.Storage.Session:(null!=(c=null==a?void 0:a.window)?c:window).sessionStorage.setItem(e,u)}}catch(e){return(0,ae.castValue)("")}return se(e,o,a)}var le={},ue={},de={},fe={},we={};//# sourceMappingURL=index.js.map