@careerdriver/black-box 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +135 -10
- package/dist/runtime.d.ts +21 -0
- package/dist/runtime.global.js +1 -1
- package/dist/runtime.global.js.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/runtime.js.map +1 -1
- package/package.json +7 -8
package/README.md
CHANGED
|
@@ -33,9 +33,84 @@ The runtime reads JSON configuration from your GPTO dashboard and automatically:
|
|
|
33
33
|
|
|
34
34
|
## Usage
|
|
35
35
|
|
|
36
|
-
###
|
|
36
|
+
### Quick Start Guide
|
|
37
37
|
|
|
38
|
-
####
|
|
38
|
+
#### Step 1: Install via npm (Primary)
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install @careerdriver/black-box
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The runtime is ESM-only and works with modern bundlers (Vite, Next.js, Webpack 5) and ESM-compatible environments.
|
|
45
|
+
|
|
46
|
+
#### Step 2: Import and initialize
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { PantheraBlackBox } from '@careerdriver/black-box';
|
|
50
|
+
|
|
51
|
+
const blackBox = new PantheraBlackBox({
|
|
52
|
+
configUrl: 'https://gpto-dashboard.vercel.app/api/sites/YOUR-SITE-ID/config',
|
|
53
|
+
telemetryUrl: 'https://gpto-dashboard.vercel.app/api/telemetry/events',
|
|
54
|
+
siteId: 'YOUR-SITE-ID',
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
await blackBox.init();
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
#### Step 3: (Recommended) Add Server-Side Schema Injection
|
|
61
|
+
|
|
62
|
+
For optimal visibility with external audit tools, inject schemas server-side. Schemas update automatically when your configuration changes.
|
|
63
|
+
|
|
64
|
+
**Option A: Schema Render Endpoint**
|
|
65
|
+
|
|
66
|
+
Fetch schemas and inject into your HTML template:
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
// Next.js / React
|
|
70
|
+
const schemas = await fetch('https://gpto-dashboard.vercel.app/api/sites/[your-site-id]/render');
|
|
71
|
+
const schemaHTML = await schemas.text();
|
|
72
|
+
|
|
73
|
+
// Inject into HTML
|
|
74
|
+
<div dangerouslySetInnerHTML={{ __html: schemaHTML }} />
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**Option B: Proxy Endpoint**
|
|
78
|
+
|
|
79
|
+
Use for external audit tools or testing:
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
https://gpto-dashboard.vercel.app/api/sites/[your-site-id]/proxy?url=https://your-domain.com
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Replace `your-domain.com` with your actual domain.
|
|
86
|
+
|
|
87
|
+
**✅ Automatic Updates:** Schemas are generated from your configuration and update automatically. No manual HTML edits needed!
|
|
88
|
+
|
|
89
|
+
### Installation (Canonical: NPM + ESM)
|
|
90
|
+
|
|
91
|
+
#### Using npm (Primary)
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npm install @careerdriver/black-box
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The runtime is ESM-only and works with modern bundlers (Vite, Next.js, Webpack 5) and ESM-compatible environments.
|
|
98
|
+
|
|
99
|
+
#### Step 2: Import and Initialize
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { PantheraBlackBox } from '@careerdriver/black-box';
|
|
103
|
+
|
|
104
|
+
const blackBox = new PantheraBlackBox({
|
|
105
|
+
configUrl: 'https://gpto-dashboard.vercel.app/api/sites/YOUR-SITE-ID/config',
|
|
106
|
+
telemetryUrl: 'https://gpto-dashboard.vercel.app/api/telemetry/events',
|
|
107
|
+
siteId: 'YOUR-SITE-ID',
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
await blackBox.init();
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
#### Using pnpm
|
|
39
114
|
|
|
40
115
|
```bash
|
|
41
116
|
# Install as a dependency
|
|
@@ -45,7 +120,7 @@ pnpm add @careerdriver/black-box
|
|
|
45
120
|
pnpm add -D @careerdriver/black-box
|
|
46
121
|
|
|
47
122
|
# Install specific version
|
|
48
|
-
pnpm add @careerdriver/black-box@1.2.
|
|
123
|
+
pnpm add @careerdriver/black-box@1.2.3
|
|
49
124
|
|
|
50
125
|
# Install latest version (includes periodic telemetry)
|
|
51
126
|
pnpm add @careerdriver/black-box@latest
|
|
@@ -56,11 +131,11 @@ pnpm add @careerdriver/black-box@latest
|
|
|
56
131
|
#### Using npm
|
|
57
132
|
|
|
58
133
|
```bash
|
|
59
|
-
# Install latest version
|
|
134
|
+
# Install latest version
|
|
60
135
|
npm install @careerdriver/black-box@latest
|
|
61
136
|
|
|
62
137
|
# Install specific version
|
|
63
|
-
npm install @careerdriver/black-box@1.2.
|
|
138
|
+
npm install @careerdriver/black-box@1.2.3
|
|
64
139
|
```
|
|
65
140
|
|
|
66
141
|
#### Using yarn
|
|
@@ -70,7 +145,7 @@ npm install @careerdriver/black-box@1.2.0
|
|
|
70
145
|
yarn add @careerdriver/black-box@latest
|
|
71
146
|
|
|
72
147
|
# Install specific version
|
|
73
|
-
yarn add @careerdriver/black-box@1.2.
|
|
148
|
+
yarn add @careerdriver/black-box@1.2.3
|
|
74
149
|
```
|
|
75
150
|
|
|
76
151
|
### ESM Import Usage
|
|
@@ -87,7 +162,7 @@ const blackBox = new PantheraBlackBox({
|
|
|
87
162
|
await blackBox.init();
|
|
88
163
|
```
|
|
89
164
|
|
|
90
|
-
### Browser Usage (Script Tag / CDN)
|
|
165
|
+
### Browser Usage (Script Tag / CDN, fallback)
|
|
91
166
|
|
|
92
167
|
#### Via unpkg CDN
|
|
93
168
|
|
|
@@ -103,7 +178,7 @@ Add the script tag to your HTML:
|
|
|
103
178
|
></script>
|
|
104
179
|
```
|
|
105
180
|
|
|
106
|
-
**Note:** The `@latest` version includes periodic telemetry (v1.2.0+). To use a specific version, replace `@latest` with `@1.2.
|
|
181
|
+
**Note:** The `@latest` version includes periodic telemetry (v1.2.0+). To use a specific version, replace `@latest` with `@1.2.3` or your preferred version.
|
|
107
182
|
|
|
108
183
|
#### Via Local Installation
|
|
109
184
|
|
|
@@ -253,6 +328,34 @@ Add to your site configuration in the GPTO dashboard:
|
|
|
253
328
|
- Confusion patterns (repeated searches, dead ends, drop-offs)
|
|
254
329
|
- Content gaps and funnel stage detection
|
|
255
330
|
- Intent detection and coverage analysis
|
|
331
|
+
- Page-level coverage metadata (`page`, `missingContentDimensions`)
|
|
332
|
+
- Recommended focus hints (`recommendedFocus`) for dashboard explanations
|
|
333
|
+
- Rich confusion evidence (`deadEndsDetail`, `dropOffsDetail`, `repeatedSearchesDetail`)
|
|
334
|
+
- Config-aware capture metadata (`captureMeta.configFrameworkVersion`)
|
|
335
|
+
- Recommendation feedback references (`recommendationFeedback.activeReadabilityActionIds`)
|
|
336
|
+
|
|
337
|
+
### AI Readability Config Contract (Additive)
|
|
338
|
+
|
|
339
|
+
The config endpoint can now include `panthera_blackbox.ai_readability` with evidence-backed clarity scoring and recommended actions.
|
|
340
|
+
|
|
341
|
+
```json
|
|
342
|
+
{
|
|
343
|
+
"panthera_blackbox": {
|
|
344
|
+
"ai_readability": {
|
|
345
|
+
"frameworkVersion": "gpto.ai_readability.v1",
|
|
346
|
+
"packageTier": "bronze",
|
|
347
|
+
"overall": { "score": 0, "grade": "F" },
|
|
348
|
+
"recommendedActions": [],
|
|
349
|
+
"insufficientData": {
|
|
350
|
+
"reason": "Readability rollup is still building.",
|
|
351
|
+
"missingSignals": ["periodic telemetry", "readability rollup"]
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
GPTO readability metrics describe clarity and machine-readability. They do not claim traffic, revenue, lead, conversion, or ROI outcomes.
|
|
256
359
|
|
|
257
360
|
**Dashboard Integration:**
|
|
258
361
|
All periodic telemetry data automatically populates:
|
|
@@ -262,7 +365,7 @@ All periodic telemetry data automatically populates:
|
|
|
262
365
|
- Schema dashboard (completeness, quality)
|
|
263
366
|
- Coverage dashboard (content gaps, missing stages)
|
|
264
367
|
- Business Brief (executive insights)
|
|
265
|
-
- Pulse Cards (
|
|
368
|
+
- Pulse Cards (experience health, trust lift, coverage risk)
|
|
266
369
|
- Recent and relevant
|
|
267
370
|
|
|
268
371
|
## Build
|
|
@@ -280,9 +383,31 @@ Output:
|
|
|
280
383
|
|
|
281
384
|
Deploy to Vercel CDN for global distribution. The file should be served with appropriate cache headers.
|
|
282
385
|
|
|
386
|
+
## Maintainer Release
|
|
387
|
+
|
|
388
|
+
Use the release helper from repo root to validate runtime + suite compatibility before publishing:
|
|
389
|
+
|
|
390
|
+
```bash
|
|
391
|
+
./scripts/release-black-box.sh
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
After checks pass:
|
|
395
|
+
|
|
396
|
+
```bash
|
|
397
|
+
cd apps/black-box
|
|
398
|
+
npm publish --access public
|
|
399
|
+
```
|
|
400
|
+
|
|
283
401
|
## Version
|
|
284
402
|
|
|
285
|
-
**Current Version:** `1.2.
|
|
403
|
+
**Current Version:** `1.2.3`
|
|
404
|
+
|
|
405
|
+
### What's New in v1.2.3
|
|
406
|
+
|
|
407
|
+
- ✅ Additive telemetry enrichment for confusion root-cause evidence
|
|
408
|
+
- ✅ Additive telemetry enrichment for coverage detail and recommended focus
|
|
409
|
+
- ✅ Backward-compatible payload shape (no breaking changes for integrators)
|
|
410
|
+
- ✅ NPM-first installation guidance for website-integrated runtime
|
|
286
411
|
|
|
287
412
|
### What's New in v1.2.0
|
|
288
413
|
|
package/dist/runtime.d.ts
CHANGED
|
@@ -75,6 +75,13 @@ interface SEOEnhancements {
|
|
|
75
75
|
title_template?: string;
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
|
+
interface AiReadabilityAction {
|
|
79
|
+
id?: string;
|
|
80
|
+
}
|
|
81
|
+
interface AiReadabilityConfig {
|
|
82
|
+
frameworkVersion?: string;
|
|
83
|
+
recommendedActions?: AiReadabilityAction[];
|
|
84
|
+
}
|
|
78
85
|
interface BlackBoxConfig {
|
|
79
86
|
panthera_blackbox: {
|
|
80
87
|
version: string;
|
|
@@ -100,10 +107,13 @@ interface BlackBoxConfig {
|
|
|
100
107
|
services?: ServiceConfig[];
|
|
101
108
|
faqs?: FaqConfig[];
|
|
102
109
|
seo_enhancements?: SEOEnhancements;
|
|
110
|
+
ai_readability?: AiReadabilityConfig;
|
|
103
111
|
[key: string]: unknown;
|
|
104
112
|
};
|
|
105
113
|
}
|
|
106
114
|
declare class PantheraBlackBox {
|
|
115
|
+
private readonly runtimeVersion;
|
|
116
|
+
private readonly privacyPolicyVersion;
|
|
107
117
|
private config;
|
|
108
118
|
private configUrl;
|
|
109
119
|
private telemetryUrl;
|
|
@@ -175,6 +185,17 @@ declare class PantheraBlackBox {
|
|
|
175
185
|
* Set up cleanup handlers for page unload
|
|
176
186
|
*/
|
|
177
187
|
private setupCleanup;
|
|
188
|
+
private hashString;
|
|
189
|
+
private redactText;
|
|
190
|
+
private buildSamplingMeta;
|
|
191
|
+
private getConfigFrameworkVersion;
|
|
192
|
+
private getActiveReadabilityActionIds;
|
|
193
|
+
private buildJourneyContext;
|
|
194
|
+
private buildIntentSignals;
|
|
195
|
+
private buildSearchDiagnostics;
|
|
196
|
+
private buildPageQualityContext;
|
|
197
|
+
private buildTechnicalSignals;
|
|
198
|
+
private applyPrivacy;
|
|
178
199
|
/**
|
|
179
200
|
* Send telemetry event
|
|
180
201
|
*/
|
package/dist/runtime.global.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Panthera Black Box Runtime v1.2.0 - Safe, Declarative Website Control with Periodic Telemetry */
|
|
2
|
-
"use strict";var PantheraBlackBox=(()=>{var y=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var E=(p,e)=>{for(var n in e)y(p,n,{get:e[n],enumerable:!0})},A=(p,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!C.call(p,i)&&i!==n&&y(p,i,{get:()=>e[i],enumerable:!(t=x(e,i))||t.enumerable});return p};var I=p=>A(y({},"__esModule",{value:!0}),p);var T={};E(T,{PantheraBlackBox:()=>f,default:()=>k});var f=class{constructor(e){this.config=null;this.initialized=!1;this.periodicIntervalId=null;this.heartbeatIntervalId=null;this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[]};this.configUrl=e.configUrl,this.telemetryUrl=e.telemetryUrl,this._siteId=e.siteId,this._siteId}async init(){if(!this.initialized)try{let e=await fetch(this.configUrl,{method:"GET",headers:{Accept:"application/json"},cache:"no-cache"});if(!e.ok)throw new Error(`Failed to load config: ${e.status}`);let n=await e.json();if(!n.panthera_blackbox||!n.panthera_blackbox.site)throw new Error("Invalid config structure");this.config=n,this.initialized=!0,this.applyConfig(),this.config.panthera_blackbox.telemetry?.emit&&this.startTelemetry()}catch(e){console.error("[Panthera Black Box] Initialization failed:",e)}}applyConfig(){if(!this.config)return;let e=this.config.panthera_blackbox;this.injectSchema(e),this.injectMetaTags(e),this.injectStructureEnhancements(e),this.injectContentEnhancements(e),this.injectContentDepth(e),e.autofill?.enabled&&e.autofill.forms&&this.initializeAutoFill(e),e.ads?.slots&&this.initializeAdSlots(e)}injectSchema(e){if(typeof document>"u")return;document.querySelectorAll('script[type="application/ld+json"][data-panthera]').forEach(r=>r.remove());let t=e.tier??"bronze";this.generateSchemasForTier(e,t).forEach((r,s)=>{let a=document.createElement("script");a.type="application/ld+json",a.setAttribute("data-panthera","true"),a.setAttribute("data-schema-index",s.toString()),a.textContent=JSON.stringify(r),document.head.appendChild(a)})}generateSchemasForTier(e,n){let t=[],i={"@context":"https://schema.org","@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`};if(e.authority_grove?.node&&(i.sameAs=e.authority_grove.node.sameAs,i.keywords=e.authority_grove.node.keywords),t.push(i),(n==="silver"||n==="gold")&&(e.products&&e.products.forEach(s=>{t.push({"@context":"https://schema.org","@type":"Product",name:s.name||e.site.brand,description:s.description,brand:{"@type":"Brand",name:e.site.brand},url:`https://${e.site.domain}`})}),e.services&&e.services.forEach(s=>{t.push({"@context":"https://schema.org","@type":"Service",name:s.name||e.site.brand,description:s.description,provider:{"@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`}})}),e.site.geo&&e.site.geo.length>0&&t.push({"@context":"https://schema.org","@type":"LocalBusiness",name:e.site.brand,url:`https://${e.site.domain}`,areaServed:e.site.geo}),e.faqs)){let r=e.faqs;r.length>0&&t.push({"@context":"https://schema.org","@type":"FAQPage",mainEntity:r.map(s=>({"@type":"Question",name:s.question,acceptedAnswer:{"@type":"Answer",text:s.answer}}))})}return t}injectMetaTags(e){if(typeof document>"u")return;let n=e.seo_enhancements;if(n){if(n.meta_description&&!document.querySelector('meta[name="description"]')){let i=document.createElement("meta");i.setAttribute("name","description"),i.setAttribute("content",n.meta_description),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}if(n.canonical_enabled&&!document.querySelector('link[rel="canonical"]')){let i=document.createElement("link");i.setAttribute("rel","canonical"),i.setAttribute("href",window.location.href),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}}}injectContentEnhancements(e){if(typeof document>"u")return;let n=e.seo_enhancements?.content_enhancements;if(!n||!n.enabled)return;let t=document.body;if(!t)return;let i=document.createElement("section");if(i.setAttribute("data-panthera","true"),i.setAttribute("data-panthera-type","ai-readiness"),i.setAttribute("aria-hidden","true"),i.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;",n.what){let r=document.createElement("div");r.textContent=n.what,i.appendChild(r)}if(n.who){let r=document.createElement("div");r.textContent=n.who,i.appendChild(r)}if(n.how){let r=document.createElement("div");r.textContent=n.how,i.appendChild(r)}if(n.trust){let r=document.createElement("div");r.textContent=n.trust,i.appendChild(r)}t.appendChild(i)}injectContentDepth(e){if(typeof document>"u")return;let n=e.seo_enhancements?.content_depth;if(!n||!n.enabled)return;let t=document.body;if(!t)return;let i=t.querySelectorAll("h2").length,r=n.min_h2_count||6,a=(t.textContent||"").length,h=Math.max(0,6e3-a),o=document.createElement("section");o.setAttribute("data-panthera","true"),o.setAttribute("data-panthera-type","content-depth"),o.setAttribute("aria-hidden","true"),o.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;";let c=0,u=Math.max(0,r-i);for(let l=0;l<u||c<h;l++){let g=document.createElement("h2");g.textContent=n.h2_templates?.[l]||`Section ${l+1}`,o.appendChild(g),c+=g.textContent.length;let m=n.content_templates?.[l]||n.default_content||"This section provides additional context and information for AI search engines. Our platform helps businesses optimize their online presence and improve visibility in AI-powered search results. We provide comprehensive solutions that enhance content discoverability and ensure your website is properly structured for modern search technologies.",S=m.length,v=Math.ceil((h-c)/S)||1;for(let b=0;b<Math.max(1,v)&&c<h;b++){let w=document.createElement("p");w.textContent=m,o.appendChild(w),c+=m.length}}o.children.length>0&&t.appendChild(o)}injectStructureEnhancements(e){if(typeof document>"u")return;let n=e.seo_enhancements?.structure_enhancements;if(n){if(n.inject_h1_if_missing&&!document.querySelector("h1")&&n.h1_text){let i=document.body;if(i){let r=document.createElement("h1");r.textContent=n.h1_text,r.setAttribute("data-panthera","true");let s=i.firstElementChild;s?i.insertBefore(r,s):i.appendChild(r)}}if(n.enhance_title){let t=document.querySelector("title"),i=t?.textContent||"",r=n.min_title_length||30;if(i.length<r&&n.title_template){let s=n.title_template.replace("{brand}",e.site.brand);if(t)t.textContent=s,t.setAttribute("data-panthera-enhanced","true");else{let a=document.createElement("title");a.textContent=s,a.setAttribute("data-panthera","true"),document.head.appendChild(a)}}}}}initializeAutoFill(e){typeof window>"u"||!e.autofill?.forms||e.autofill.forms.forEach(n=>{let t=document.querySelector(n.selector);t&&(t.pantheraAutoFill=n,t.addEventListener("focusin",i=>{let r=i.target;(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.tagName==="SELECT")&&this.triggerAutoFill(n)},{once:!0}))})}async triggerAutoFill(e){let n={},t=document.querySelector(e.selector);if(t)for(let[i,r]of Object.entries(e.map)){let s=t.querySelector(r);s&&n[i]&&(s.value=n[i],s.dispatchEvent(new Event("input",{bubbles:!0})))}}initializeAdSlots(e){typeof window>"u"||!e.ads?.slots||e.ads.slots.forEach(n=>{let t=String(n.id||"").trim();if(t=t.replace(/["']/g,""),t=t.trim(),!!t)try{let i=t.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\$&");if(i.includes('"')||i.includes("'"))throw new Error(`Slot ID contains quotes after sanitization: ${i}`);let r=`[data-ad-slot="${i}"]`,s=document.querySelector(r);s&&(s.pantheraAdSlot=n,this.loadAdCreative(n))}catch(i){console.error(`[Panthera Black Box] Invalid ad slot selector for ID: ${n.id}`,i)}})}async loadAdCreative(e){console.debug("[Panthera Black Box] Ad slot initialized:",e.id)}startTelemetry(){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(this.sendTelemetry("page_view",{url:window.location.href,referrer:document.referrer}),typeof window<"u"){let t=null,i=()=>{t||(t=window.setTimeout(()=>{this.sendTelemetry("interaction",{timestamp:new Date().toISOString()}),t=null},1e3))};document.addEventListener("click",i,{passive:!0}),document.addEventListener("scroll",i,{passive:!0})}let e=this.config.panthera_blackbox.telemetry.periodic;if((e?.enabled??!0)&&typeof window<"u"){let t=e?.intervalMs||3e5;this.periodicIntervalId!==null&&window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=window.setInterval(()=>{this.sendPeriodicTelemetry()},t),this.setupCleanup()}else typeof window<"u"&&(this.heartbeatIntervalId!==null&&window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=window.setInterval(()=>{this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()})},3e5),this.setupCleanup())}setupCleanup(){if(typeof window>"u")return;let e=()=>{this.periodicIntervalId!==null&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.heartbeatIntervalId!==null&&(window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.hidden&&(this.config?.panthera_blackbox.telemetry?.periodic?.enabled??!0?this.sendPeriodicTelemetry():this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()}))})}async sendTelemetry(e,n){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(e==="page_view")this.periodicState.pageViews++,typeof window<"u"&&(this.periodicState.pageHistory.push({url:window.location.href,timestamp:Date.now()}),this.periodicState.pageHistory.length>50&&this.periodicState.pageHistory.shift());else if(e==="interaction")this.periodicState.interactions++;else if(e==="search"){this.periodicState.searches++;let m=n.search?.query||n.context?.search_query;m&&(this.periodicState.searchQueries.push({query:m,timestamp:Date.now()}),this.periodicState.searchQueries.length>50&&this.periodicState.searchQueries.shift())}let{page:t,search:i,...r}=n,s=this.getSessionId(),a=e==="page_view",d=t||(a&&typeof window<"u"?{url:window.location.href,path:window.location.pathname,title:document.title}:void 0),h=r.search_query||r.query,o=r.results_count,c=r.selected_result,u=e==="search"?i||(h?{query:h,results_count:o,selected_result:c}:void 0):void 0,l={event_type:e,...r};a&&(l.intent===void 0&&(l.intent=this.detectIntent()),l.funnelStage===void 0&&(l.funnelStage=this.detectFunnelStage()));let g={schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:["page_view","interaction","search"].includes(e)?e:"custom",session_id:s,page:d,search:u,context:Object.keys(l).length>0?l:void 0,metrics:this.collectMetrics()};try{if(navigator.sendBeacon){let m=new Blob([JSON.stringify(g)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,m)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),keepalive:!0})}catch(m){console.debug("[Panthera Black Box] Telemetry failed:",m)}}async sendPeriodicTelemetry(){if(this.config?.panthera_blackbox.telemetry?.emit&&!(typeof window>"u"))try{let e=Date.now(),n=e-this.periodicState.lastSent,t=this.collectMetrics(),i=this.detectRepeatedSearches(),r=this.detectDeadEnds(),s=this.detectDropOffs(),a=this.detectContentGaps(),d=this.detectFunnelStage(),h=this.detectIntent(),o={periodic:!0,timeSinceLastSend:n,aggregated:{pageViews:this.periodicState.pageViews,interactions:this.periodicState.interactions,searches:this.periodicState.searches},confusion:{repeatedSearches:i.length,deadEnds:r.length,dropOffs:s.length,repeatedSearchesDetail:i.slice(0,10),deadEndsDetail:r.slice(0,10),dropOffsDetail:s.slice(0,10)},coverage:{contentGaps:a.length,contentGapsDetail:a,funnelStage:d,intent:h,pageMetadata:{hasJsonLd:document.querySelectorAll('script[type="application/ld+json"]').length>0,h1Count:document.querySelectorAll("h1").length,h2Count:document.querySelectorAll("h2").length,textLength:document.body?.textContent?.length||0}},intent:h,funnelStage:d},c={schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"custom",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:o,metrics:t};if(navigator.sendBeacon){let l=new Blob([JSON.stringify(c)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,l)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),keepalive:!0});let u={schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"page_view",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:{periodic:!0,heartbeat:!0,aggregatedMetrics:t,aggregatedPageViews:this.periodicState.pageViews,aggregatedInteractions:this.periodicState.interactions,aggregatedSearches:this.periodicState.searches},metrics:t};if(navigator.sendBeacon){let l=new Blob([JSON.stringify(u)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,l)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),keepalive:!0});this.periodicState.pageViews=0,this.periodicState.interactions=0,this.periodicState.searches=0,this.periodicState.lastSent=e}catch(e){console.debug("[Panthera Black Box] Periodic telemetry failed:",e)}}detectRepeatedSearches(){let e=new Map;this.periodicState.searchQueries.forEach(({query:t})=>{e.set(t,(e.get(t)||0)+1)});let n=[];return e.forEach((t,i)=>{t>1&&n.push({query:i,count:t})}),n}detectDeadEnds(){let e=[];if(this.periodicState.pageHistory.length<2)return e;for(let r=0;r<this.periodicState.pageHistory.length-1;r++){let s=this.periodicState.pageHistory[r];this.periodicState.pageHistory[r+1].timestamp-s.timestamp>6e4&&e.push({url:s.url,at:new Date(s.timestamp).toISOString()})}let t=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1];return Date.now()-t.timestamp>6e4&&e.push({url:t.url,at:new Date(t.timestamp).toISOString()}),e}detectDropOffs(){let e=[];if(this.periodicState.pageViews+this.periodicState.interactions+this.periodicState.searches<=2&&this.periodicState.pageHistory.length>0){let t=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],i=this.getSessionId();i&&e.push({sessionId:i,lastEvent:new Date(t.timestamp).toISOString()})}return e}detectContentGaps(){if(typeof document>"u")return[];let e=[],n=document.body;if(!n)return e;let t=n.textContent?.toLowerCase()||"",i=this.config?.panthera_blackbox.seo_enhancements?.content_enhancements;return!i?.what&&!t.includes("what")&&!t.includes("do")&&e.push("what"),!i?.who&&!t.includes("who")&&!t.includes("for")&&e.push("who"),!i?.how&&!t.includes("how")&&!t.includes("work")&&e.push("how"),!i?.trust&&!t.includes("trust")&&!t.includes("certified")&&e.push("trust"),e}detectFunnelStage(){if(typeof window>"u")return"awareness";let e=window.location.href.toLowerCase(),n=window.location.pathname.toLowerCase();return e.includes("pricing")||e.includes("signup")||e.includes("checkout")||n.includes("pricing")?"decision":e.includes("docs")||e.includes("case-study")||e.includes("guides")||n.includes("docs")?"consideration":e.includes("support")||e.includes("account")||e.includes("dashboard")||n.includes("account")?"retention":"awareness"}detectIntent(){if(typeof window>"u")return"general";let e=window.location.href.toLowerCase(),n=document.title?.toLowerCase()||"",t=`${e} ${n}`;return t.includes("pricing")?"pricing":t.includes("demo")?"demo":t.includes("docs")?"docs":t.includes("case study")?"case-study":"general"}collectMetrics(){let e={};return(this.config?.panthera_blackbox.telemetry?.keys||[]).forEach(t=>{t.startsWith("ai.")?t==="ai.schemaCompleteness"?e[t]=this.calculateSchemaCompleteness():t==="ai.structuredDataQuality"?e[t]=this.calculateStructuredDataQuality():t==="ai.authoritySignals"?e[t]=this.calculateAuthoritySignals():t==="ai.searchVisibility"?e[t]=this.calculateSearchVisibility():e[t]=.6+Math.random()*.35:t.startsWith("ts.")?t==="ts.authority"?e[t]=this.calculateAuthorityScore():e[t]=.5+Math.random()*.4:e[t]=0}),e}calculateSchemaCompleteness(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]'),n=document.querySelectorAll('script[type="application/ld+json"][data-panthera]'),t=0;e.length>0&&(t=.3),n.length>0&&(t=.5);let i=new Set;return e.forEach(r=>{try{let s=r.textContent;if(s){let a=JSON.parse(s);a["@type"]&&i.add(a["@type"])}}catch{}}),t+=Math.min(.5,i.size*.1),Math.min(1,t)}calculateStructuredDataQuality(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length===0)return 0;let n=0,t=0,i=0;if(e.forEach(d=>{try{let h=d.textContent;if(!h)return;let o=JSON.parse(h);if(!o["@context"]||!o["@type"])return;n++;let c=Object.keys(o);t+=c.length;let u=o["@type"];u==="Organization"&&o.name&&o.url?i+=2:(u==="Product"&&o.name||u==="Service"&&o.name||u==="FAQPage"&&Array.isArray(o.mainEntity))&&(i+=1)}catch{}}),n===0)return 0;let r=Math.min(.5,n*.25),s=Math.min(.3,t/n/10),a=Math.min(.2,i*.1);return Math.min(1,r+s+a)}calculateAuthoritySignals(){if(typeof document>"u")return 0;let e=0,n=document.body;if(!n)return 0;let t=n.textContent?.toLowerCase()||"",r=["certified","award","trusted","verified","accredited","licensed"].filter(d=>t.includes(d));e+=Math.min(.3,r.length*.05);let a=["review","testimonial","rating","star","customer"].filter(d=>t.includes(d));if(e+=Math.min(.3,a.length*.05),this.config?.panthera_blackbox.authority_grove?.node?.sameAs){let d=this.config.panthera_blackbox.authority_grove.node.sameAs.length;e+=Math.min(.4,d*.1)}return Math.min(1,e)}calculateSearchVisibility(){if(typeof document>"u")return 0;let e=0,n=document.querySelector('meta[name="description"]');n&&n.getAttribute("content")&&n.getAttribute("content").length>50&&(e+=.2);let t=document.querySelector("title");t&&t.textContent&&t.textContent.length>30&&(e+=.2);let i=document.querySelector("h1");i&&i.textContent&&(e+=.2),document.querySelectorAll('script[type="application/ld+json"]').length>0&&(e+=.2);let s=document.querySelectorAll("h2"),a=document.body?.textContent?.length||0;return s.length>=3&&a>1e3&&(e+=.2),Math.min(1,e)}calculateAuthorityScore(){if(!this.config?.panthera_blackbox.authority_grove?.node)return .5;let e=this.config.panthera_blackbox.authority_grove.node,n=.3;return e.sameAs&&e.sameAs.length>0&&(n+=Math.min(.4,e.sameAs.length*.1)),e.keywords&&e.keywords.length>0&&(n+=Math.min(.3,e.keywords.length*.05)),Math.min(1,n)}getSessionId(){if(typeof window>"u")return;let e=window.sessionStorage,n=window.localStorage,t="panthera_session_id",i="panthera_session_ts",r=Date.now(),s=1800*1e3,a=c=>{if(!c)return null;try{let u=c.getItem(t),l=Number(c.getItem(i)||0);if(u&&l&&r-l<s)return c.setItem(i,String(r)),u}catch{return null}return null},d=(c,u)=>{if(!c)return!1;try{return c.setItem(t,u),c.setItem(i,String(r)),!0}catch{return!1}},h=a(e)||a(n);if(h)return h;if(this.memorySessionId&&this.memorySessionTs&&r-this.memorySessionTs<s)return this.memorySessionTs=r,this.memorySessionId;let o=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${r}-${Math.random().toString(16).slice(2)}`;return d(e,o)||d(n,o),this.memorySessionId=o,this.memorySessionTs=r,o}getConfig(){return this.config}async reload(){this.periodicIntervalId!==null&&typeof window<"u"&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[]},this.initialized=!1,await this.init()}};(function(){if(typeof window>"u")return;let p=document.currentScript;if(!p)return;let e=p.getAttribute("data-config-url"),n=p.getAttribute("data-telemetry-url"),t=p.getAttribute("data-site-id");if(!e||!n||!t){console.warn("[Panthera Black Box] Missing required data attributes");return}let i=new f({configUrl:e,telemetryUrl:n,siteId:t});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i.init()):i.init(),window.PantheraBlackBox=f,window.panthera=i})();var k=f;return I(T);})();
|
|
2
|
+
"use strict";var PantheraBlackBox=(()=>{var x=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var M=(p,e)=>{for(var t in e)x(p,t,{get:e[t],enumerable:!0})},T=(p,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of E(e))!I.call(p,i)&&i!==t&&x(p,i,{get:()=>e[i],enumerable:!(n=_(e,i))||n.enumerable});return p};var D=p=>T(x({},"__esModule",{value:!0}),p);var B={};M(B,{PantheraBlackBox:()=>w,default:()=>q});var w=class{constructor(e){this.runtimeVersion="1.3.0";this.privacyPolicyVersion="2026-03-v2";this.config=null;this.initialized=!1;this.periodicIntervalId=null;this.heartbeatIntervalId=null;this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0};this.configUrl=e.configUrl,this.telemetryUrl=e.telemetryUrl,this._siteId=e.siteId,this._siteId}async init(){if(!this.initialized)try{let e=await fetch(this.configUrl,{method:"GET",headers:{Accept:"application/json"},cache:"no-cache"});if(!e.ok)throw new Error(`Failed to load config: ${e.status}`);let t=await e.json();if(!t.panthera_blackbox||!t.panthera_blackbox.site)throw new Error("Invalid config structure");this.config=t,this.initialized=!0,this.applyConfig(),this.config.panthera_blackbox.telemetry?.emit&&this.startTelemetry()}catch(e){console.error("[Panthera Black Box] Initialization failed:",e)}}applyConfig(){if(!this.config)return;let e=this.config.panthera_blackbox;this.injectSchema(e),this.injectMetaTags(e),this.injectStructureEnhancements(e),this.injectContentEnhancements(e),this.injectContentDepth(e),e.autofill?.enabled&&e.autofill.forms&&this.initializeAutoFill(e),e.ads?.slots&&this.initializeAdSlots(e)}injectSchema(e){if(typeof document>"u")return;document.querySelectorAll('script[type="application/ld+json"][data-panthera]').forEach(r=>r.remove());let n=e.tier??"bronze";this.generateSchemasForTier(e,n).forEach((r,s)=>{let a=document.createElement("script");a.type="application/ld+json",a.setAttribute("data-panthera","true"),a.setAttribute("data-schema-index",s.toString()),a.textContent=JSON.stringify(r),document.head.appendChild(a)})}generateSchemasForTier(e,t){let n=[],i={"@context":"https://schema.org","@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`};if(e.authority_grove?.node&&(i.sameAs=e.authority_grove.node.sameAs,i.keywords=e.authority_grove.node.keywords),n.push(i),(t==="silver"||t==="gold")&&(e.products&&e.products.forEach(s=>{n.push({"@context":"https://schema.org","@type":"Product",name:s.name||e.site.brand,description:s.description,brand:{"@type":"Brand",name:e.site.brand},url:`https://${e.site.domain}`})}),e.services&&e.services.forEach(s=>{n.push({"@context":"https://schema.org","@type":"Service",name:s.name||e.site.brand,description:s.description,provider:{"@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`}})}),e.site.geo&&e.site.geo.length>0&&n.push({"@context":"https://schema.org","@type":"LocalBusiness",name:e.site.brand,url:`https://${e.site.domain}`,areaServed:e.site.geo}),e.faqs)){let r=e.faqs;r.length>0&&n.push({"@context":"https://schema.org","@type":"FAQPage",mainEntity:r.map(s=>({"@type":"Question",name:s.question,acceptedAnswer:{"@type":"Answer",text:s.answer}}))})}return n}injectMetaTags(e){if(typeof document>"u")return;let t=e.seo_enhancements;if(t){if(t.meta_description&&!document.querySelector('meta[name="description"]')){let i=document.createElement("meta");i.setAttribute("name","description"),i.setAttribute("content",t.meta_description),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}if(t.canonical_enabled&&!document.querySelector('link[rel="canonical"]')){let i=document.createElement("link");i.setAttribute("rel","canonical"),i.setAttribute("href",window.location.href),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}}}injectContentEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_enhancements;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let i=document.createElement("section");if(i.setAttribute("data-panthera","true"),i.setAttribute("data-panthera-type","ai-readiness"),i.setAttribute("aria-hidden","true"),i.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;",t.what){let r=document.createElement("div");r.textContent=t.what,i.appendChild(r)}if(t.who){let r=document.createElement("div");r.textContent=t.who,i.appendChild(r)}if(t.how){let r=document.createElement("div");r.textContent=t.how,i.appendChild(r)}if(t.trust){let r=document.createElement("div");r.textContent=t.trust,i.appendChild(r)}n.appendChild(i)}injectContentDepth(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_depth;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let i=n.querySelectorAll("h2").length,r=t.min_h2_count||6,a=(n.textContent||"").length,l=Math.max(0,6e3-a),o=document.createElement("section");o.setAttribute("data-panthera","true"),o.setAttribute("data-panthera-type","content-depth"),o.setAttribute("aria-hidden","true"),o.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;";let d=0,h=Math.max(0,r-i);for(let u=0;u<h||d<l;u++){let m=document.createElement("h2");m.textContent=t.h2_templates?.[u]||`Section ${u+1}`,o.appendChild(m),d+=m.textContent.length;let g=t.content_templates?.[u]||t.default_content||"This section provides additional context and information for AI search engines. Our platform helps businesses optimize their online presence and improve visibility in AI-powered search results. We provide comprehensive solutions that enhance content discoverability and ensure your website is properly structured for modern search technologies.",b=g.length,y=Math.ceil((l-d)/b)||1;for(let f=0;f<Math.max(1,y)&&d<l;f++){let S=document.createElement("p");S.textContent=g,o.appendChild(S),d+=g.length}}o.children.length>0&&n.appendChild(o)}injectStructureEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.structure_enhancements;if(t){if(t.inject_h1_if_missing&&!document.querySelector("h1")&&t.h1_text){let i=document.body;if(i){let r=document.createElement("h1");r.textContent=t.h1_text,r.setAttribute("data-panthera","true");let s=i.firstElementChild;s?i.insertBefore(r,s):i.appendChild(r)}}if(t.enhance_title){let n=document.querySelector("title"),i=n?.textContent||"",r=t.min_title_length||30;if(i.length<r&&t.title_template){let s=t.title_template.replace("{brand}",e.site.brand);if(n)n.textContent=s,n.setAttribute("data-panthera-enhanced","true");else{let a=document.createElement("title");a.textContent=s,a.setAttribute("data-panthera","true"),document.head.appendChild(a)}}}}}initializeAutoFill(e){typeof window>"u"||!e.autofill?.forms||e.autofill.forms.forEach(t=>{let n=document.querySelector(t.selector);n&&(n.pantheraAutoFill=t,n.addEventListener("focusin",i=>{let r=i.target;(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.tagName==="SELECT")&&this.triggerAutoFill(t)},{once:!0}))})}async triggerAutoFill(e){let t={},n=document.querySelector(e.selector);if(n)for(let[i,r]of Object.entries(e.map)){let s=n.querySelector(r);s&&t[i]&&(s.value=t[i],s.dispatchEvent(new Event("input",{bubbles:!0})))}}initializeAdSlots(e){typeof window>"u"||!e.ads?.slots||e.ads.slots.forEach(t=>{let n=String(t.id||"").trim();if(n=n.replace(/["']/g,""),n=n.trim(),!!n)try{let i=n.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\$&");if(i.includes('"')||i.includes("'"))throw new Error(`Slot ID contains quotes after sanitization: ${i}`);let r=`[data-ad-slot="${i}"]`,s=document.querySelector(r);s&&(s.pantheraAdSlot=t,this.loadAdCreative(t))}catch(i){console.error(`[Panthera Black Box] Invalid ad slot selector for ID: ${t.id}`,i)}})}async loadAdCreative(e){console.debug("[Panthera Black Box] Ad slot initialized:",e.id)}startTelemetry(){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(this.sendTelemetry("page_view",{url:window.location.href,referrer:document.referrer}),typeof window<"u"){let n=null,i=()=>{let l=Date.now(),o=l-this.periodicState.lastActivityAt;if(o>0){let d=Math.min(o,1e3);this.periodicState.activeTimeMs+=d,o>d&&(this.periodicState.idleTimeMs+=o-d)}this.periodicState.lastActivityAt=l},r=l=>{if(i(),typeof window<"u"){let o=Math.max(document.documentElement.scrollTop||0,document.body.scrollTop||0),d=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,1),h=window.innerHeight||0,u=Math.min(1,(o+h)/d);this.periodicState.scrollDepthMax=Math.max(this.periodicState.scrollDepthMax,u)}if(l&&l.type==="click"){let d=l.target?.closest('a,button,[role="button"],input[type="submit"]'),h=d?.textContent?.trim()||"";if(h&&/buy|start|book|contact|get demo|sign up|trial|pricing/i.test(h)&&this.periodicState.ctaClicks.push(h.slice(0,80)),d?.tagName.toLowerCase()==="a"){let u=d.href;try{let m=new URL(u,window.location.href);m.origin!==window.location.origin&&this.periodicState.outboundClicks.push(m.href)}catch{}}}n||(n=window.setTimeout(()=>{this.sendTelemetry("interaction",{timestamp:new Date().toISOString()}),n=null},1e3))};document.addEventListener("click",l=>r(l),{passive:!0}),document.addEventListener("scroll",l=>r(l),{passive:!0}),document.addEventListener("mousemove",i,{passive:!0}),document.addEventListener("keydown",i,{passive:!0});let s=0,a=0,c="";document.addEventListener("click",l=>{let d=(l.target?.textContent||"").trim().slice(0,80),h=Date.now();if(h-s>1500||d!==c){s=h,a=1,c=d;return}a+=1,a>=4&&(this.periodicState.rageClicks+=1,a=0)},{passive:!0}),window.addEventListener("error",l=>{this.periodicState.jsErrorsCount+=1;let o=String(l.message||"unknown-js-error").slice(0,120);this.periodicState.errorSignatures.push(o),this.periodicState.errorSignatures.length>20&&this.periodicState.errorSignatures.shift()}),window.addEventListener("unhandledrejection",()=>{this.periodicState.jsErrorsCount+=1}),window.addEventListener("error",l=>{l.target&&l.message===""&&(this.periodicState.resourceFailures+=1)},!0)}let e=this.config.panthera_blackbox.telemetry.periodic;if((e?.enabled??!0)&&typeof window<"u"){let n=e?.intervalMs||3e5;this.periodicIntervalId!==null&&window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=window.setInterval(()=>{this.sendPeriodicTelemetry()},n),window.setTimeout(()=>{this.sendPeriodicTelemetry()},1e3),this.setupCleanup()}else typeof window<"u"&&(this.heartbeatIntervalId!==null&&window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=window.setInterval(()=>{this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()})},3e5),this.setupCleanup())}setupCleanup(){if(typeof window>"u")return;let e=()=>{this.periodicIntervalId!==null&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.heartbeatIntervalId!==null&&(window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.hidden&&(this.config?.panthera_blackbox.telemetry?.periodic?.enabled??!0?this.sendPeriodicTelemetry():this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()}))})}hashString(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}redactText(e){let t=e,n=t;return t=t.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi,"[redacted-email]"),t=t.replace(/\\+?\\d[\\d\\s().-]{7,}\\d/g,"[redacted-phone]"),t=t.replace(/\\b(name|full name|first name|last name)\\s*[:=-]?\\s*[a-z ,.'-]{2,}/gi,"$1:[redacted-name]"),{value:t,redacted:t!==n}}buildSamplingMeta(e,t,n){return e>0||t>0||this.periodicState.jsErrorsCount>0?{tier:"critical",reason:"Detected friction or technical issues"}:n>0||this.periodicState.pageViews>20?{tier:"full",reason:"Coverage gaps or high activity"}:{tier:"sampled",reason:"Healthy low-risk traffic sample"}}getConfigFrameworkVersion(){let e=this.config?.panthera_blackbox?.ai_readability?.frameworkVersion;return typeof e=="string"&&e.trim().length>0?e:void 0}getActiveReadabilityActionIds(e=3){let t=this.config?.panthera_blackbox?.ai_readability?.recommendedActions;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"&&n.trim().length>0).slice(0,e):[]}buildJourneyContext(){let e=this.periodicState.pageHistory,t=e[0]?.url,n=e[e.length-1]?.url,i=e.map(c=>c.url).filter(Boolean).slice(0,25),r=0,s=0,a=new Set;for(let c=0;c<i.length;c++)a.has(i[c])&&r++,a.add(i[c]),c>1&&i[c]===i[c-2]&&s++;return{entryUrl:t,exitUrl:n,path:i,stepCount:i.length,timeOnPathMs:e.length>1?e[e.length-1].timestamp-e[0].timestamp:0,loops:r,backtracks:s,stallPoints:this.detectDeadEnds().map(c=>c.url).slice(0,5)}}buildIntentSignals(){let e=this.detectIntent(),t=[{intent:e,confidence:.7},{intent:this.detectFunnelStage()==="decision"?"pricing":"general",confidence:.45},{intent:"support",confidence:.2}],n=["url_pattern","keyword_match"];return typeof document<"u"&&document.querySelectorAll('a[href*="demo"],button').length>0&&n.push("cta_match"),typeof document<"u"&&document.querySelectorAll('script[type="application/ld+json"]').length>0&&n.push("schema_hint"),{detectedIntent:e,confidence:t[0].confidence,topCandidates:t,reasonFlags:n}}buildSearchDiagnostics(e){let t=this.periodicState.searchQueries[this.periodicState.searchQueries.length-1]?.query,n=r=>{let s=r.toLowerCase();return s.includes("price")||s.includes("pricing")||s.includes("cost")?"price":s.includes("compare")||s.includes("vs")||s.includes("alternative")?"compare":s.includes("support")||s.includes("error")||s.includes("help")?"support":s.split(" ").length<=2?"nav":"info"},i=this.periodicState.searchQueries.map(r=>r.query).slice(-5);return{query:t,queryHash:t?this.hashString(t.toLowerCase()):void 0,queryClass:t?n(t):void 0,reformulations:i,zeroResultHints:e.length>0?["Repeated searches may indicate weak or missing answers"]:[],repeatedQueryFingerprint:e.length>0?this.hashString(e.map(r=>r.query).join("|")):void 0}}buildPageQualityContext(){if(typeof document>"u")return{};let e=document.body?.textContent||"",t=e.split(/\\s+/).filter(Boolean).length||1,n=Math.max(1,e.split(/[.!?]+/).filter(Boolean).length),i=Math.max(0,Math.min(1,1-Math.min(1,t/n/35))),r=document.querySelectorAll('a[href*="contact"],a[href*="pricing"],button').length>0,s=document.querySelectorAll("a").length,a=Array.from(document.querySelectorAll("a")).filter(d=>(d.textContent||"").trim().length>5).length,c=s>0?a/s:.5,l=document.querySelectorAll('script[type="application/ld+json"]').length>0,o=l&&/faq/i.test(e);return{readabilityScore:i,aboveFoldClarity:r?.8:.45,ctaPresence:r,linkClarityScore:c,schemaPresence:{jsonLd:l,faq:o},faqPresence:o}}buildTechnicalSignals(){let e=this.periodicState.jsErrorsCount>0?"needs-attention":"healthy";return{jsErrorsCount:this.periodicState.jsErrorsCount,errorSignatures:this.periodicState.errorSignatures.slice(-8),resourceFailures:this.periodicState.resourceFailures,lcpBucket:e,fidBucket:this.periodicState.rageClicks>0?"needs-attention":"healthy",clsBucket:"unknown",routeTransitionMsBucket:"unknown"}}applyPrivacy(e){let t=[],n=!1;if(e.search?.query){let r=this.redactText(e.search.query);r.redacted&&(n=!0),e.search.query=r.value,t.push(`search.query:${this.hashString(r.value.toLowerCase())}`)}if(e.page?.title){let r=this.redactText(e.page.title);r.redacted&&(n=!0),e.page.title=r.value,t.push(`page.title:${this.hashString(r.value.toLowerCase())}`)}let i=e.context||void 0;if(i&&typeof i=="object"){let r=s=>{let a=i[s];if(typeof a!="string")return;let c=this.redactText(a);i[s]=c.value,c.redacted&&(n=!0),t.push(`${s}:${this.hashString(c.value.toLowerCase())}`)};r("search_query"),r("query"),r("url"),i.privacy={redactionApplied:n,hashedFields:t.slice(0,12),policyVersion:this.privacyPolicyVersion},e.context=i}return e}async sendTelemetry(e,t){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(e==="page_view")this.periodicState.pageViews++,typeof window<"u"&&(this.periodicState.pageHistory.push({url:window.location.href,path:window.location.pathname,title:document.title,intent:this.detectIntent(),funnelStage:this.detectFunnelStage(),timestamp:Date.now()}),this.periodicState.pageHistory.length>50&&this.periodicState.pageHistory.shift());else if(e==="interaction")this.periodicState.interactions++;else if(e==="search"){this.periodicState.searches++;let g=t.search?.query||t.context?.search_query;g&&(this.periodicState.searchQueries.push({query:g,timestamp:Date.now()}),this.periodicState.searchQueries.length>50&&this.periodicState.searchQueries.shift())}let{page:n,search:i,...r}=t,s=this.getSessionId(),a=e==="page_view",c=n||(a&&typeof window<"u"?{url:window.location.href,path:window.location.pathname,title:document.title}:void 0),l=r.search_query||r.query,o=r.results_count,d=r.selected_result,h=e==="search"?i||(l?{query:l,results_count:o,selected_result:d}:void 0):void 0,u={event_type:e,...r};a&&(u.intent===void 0&&(u.intent=this.detectIntent()),u.funnelStage===void 0&&(u.funnelStage=this.detectFunnelStage())),u.captureMeta===void 0&&(u.captureMeta={runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion()});let m=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:["page_view","interaction","search"].includes(e)?e:"custom",session_id:s,page:c,search:h,context:Object.keys(u).length>0?u:void 0,metrics:this.collectMetrics()});try{if(navigator.sendBeacon){let g=new Blob([JSON.stringify(m)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,g)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m),keepalive:!0})}catch(g){console.debug("[Panthera Black Box] Telemetry failed:",g)}}async sendPeriodicTelemetry(){if(this.config?.panthera_blackbox.telemetry?.emit&&!(typeof window>"u"))try{let e=Date.now(),t=e-this.periodicState.lastSent,n=this.collectMetrics(),i=this.detectRepeatedSearches(),r=this.detectDeadEnds(),s=this.detectDropOffs(),a=this.buildJourneyContext(),c=this.buildIntentSignals(),l={scrollDepthMax:this.periodicState.scrollDepthMax,activeTimeMs:this.periodicState.activeTimeMs,idleTimeMs:this.periodicState.idleTimeMs,ctaClicks:this.periodicState.ctaClicks.slice(-10),outboundClicks:this.periodicState.outboundClicks.slice(-10),rageClicks:this.periodicState.rageClicks},o=this.buildSearchDiagnostics(i),d=this.buildPageQualityContext(),h=this.buildTechnicalSignals(),u=this.detectContentGaps(),m=this.detectFunnelStage(),g=this.detectIntent(),b={what:u.includes("what"),who:u.includes("who"),how:u.includes("how"),trust:u.includes("trust")},y=[];r.length>0&&y.push("Add clear next-step links and calls-to-action on dead-end pages."),i.length>0&&y.push("Improve clarity for repeated search topics with dedicated sections and internal links."),u.length>0&&y.push(`Fill missing content dimensions: ${u.join(", ")}.`);let f=this.buildSamplingMeta(r.length,s.length,u.length),S=this.getActiveReadabilityActionIds(),A={periodic:!0,timeSinceLastSend:t,aggregated:{pageViews:this.periodicState.pageViews,interactions:this.periodicState.interactions,searches:this.periodicState.searches},confusion:{repeatedSearches:i.length,deadEnds:r.length,dropOffs:s.length,repeatedSearchesDetail:i.slice(0,10),deadEndsDetail:r.slice(0,10),dropOffsDetail:s.slice(0,10)},coverage:{contentGaps:u.length,contentGapsDetail:u,funnelStage:m,intent:g,page:{url:window.location.href,path:window.location.pathname,title:document.title},missingContentDimensions:b,pageMetadata:{hasJsonLd:document.querySelectorAll('script[type="application/ld+json"]').length>0,h1Count:document.querySelectorAll("h1").length,h2Count:document.querySelectorAll("h2").length,textLength:document.body?.textContent?.length||0},recommendedFocus:y.slice(0,3)},journey:a,intentSignals:c,engagement:l,searchDiagnostics:o,pageQuality:d,technicalSignals:h,recommendationFeedback:{recommendationId:`rec-${this.detectFunnelStage()}`,exposed:!0,reachedNextStep:s.length===0&&r.length===0,activeReadabilityActionIds:S},captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:f.tier,samplingReason:f.reason},intent:g,funnelStage:m},C=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"custom",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:A,metrics:n});if(navigator.sendBeacon){let v=new Blob([JSON.stringify(C)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,v)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C),keepalive:!0});let k=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"page_view",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:{periodic:!0,heartbeat:!0,captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:f.tier,samplingReason:f.reason},aggregatedMetrics:n,aggregatedPageViews:this.periodicState.pageViews,aggregatedInteractions:this.periodicState.interactions,aggregatedSearches:this.periodicState.searches},metrics:n});if(navigator.sendBeacon){let v=new Blob([JSON.stringify(k)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,v)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k),keepalive:!0});this.periodicState.pageViews=0,this.periodicState.interactions=0,this.periodicState.searches=0,this.periodicState.lastSent=e,this.periodicState.ctaClicks=[],this.periodicState.outboundClicks=[],this.periodicState.rageClicks=0,this.periodicState.scrollDepthMax=0,this.periodicState.activeTimeMs=0,this.periodicState.idleTimeMs=0,this.periodicState.jsErrorsCount=0,this.periodicState.errorSignatures=[],this.periodicState.resourceFailures=0}catch(e){console.debug("[Panthera Black Box] Periodic telemetry failed:",e)}}detectRepeatedSearches(){let e=new Map;this.periodicState.searchQueries.forEach(({query:n})=>{e.set(n,(e.get(n)||0)+1)});let t=[];return e.forEach((n,i)=>{n>1&&t.push({query:i,count:n,intent:this.detectIntent(),funnelStage:this.detectFunnelStage()})}),t}detectDeadEnds(){let e=[];if(this.periodicState.pageHistory.length<2)return e;for(let r=0;r<this.periodicState.pageHistory.length-1;r++){let s=this.periodicState.pageHistory[r],c=this.periodicState.pageHistory[r+1].timestamp-s.timestamp;c>6e4&&e.push({url:s.url,path:s.path,title:s.title,at:new Date(s.timestamp).toISOString(),dwellMs:c,reason:"No next meaningful action within expected time window"})}let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],i=Date.now()-n.timestamp;return i>6e4&&e.push({url:n.url,path:n.path,title:n.title,at:new Date(n.timestamp).toISOString(),dwellMs:i,reason:"Session stalled after page view"}),e}detectDropOffs(){let e=[];if(this.periodicState.pageViews+this.periodicState.interactions+this.periodicState.searches<=2&&this.periodicState.pageHistory.length>0){let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],i=this.getSessionId();i&&e.push({sessionId:i,lastEvent:new Date(n.timestamp).toISOString(),lastUrl:n.url,stage:n.funnelStage,intent:n.intent})}return e}detectContentGaps(){if(typeof document>"u")return[];let e=[],t=document.body;if(!t)return e;let n=t.textContent?.toLowerCase()||"",i=this.config?.panthera_blackbox.seo_enhancements?.content_enhancements;return!i?.what&&!n.includes("what")&&!n.includes("do")&&e.push("what"),!i?.who&&!n.includes("who")&&!n.includes("for")&&e.push("who"),!i?.how&&!n.includes("how")&&!n.includes("work")&&e.push("how"),!i?.trust&&!n.includes("trust")&&!n.includes("certified")&&e.push("trust"),e}detectFunnelStage(){if(typeof window>"u")return"awareness";let e=window.location.href.toLowerCase(),t=window.location.pathname.toLowerCase();return e.includes("pricing")||e.includes("signup")||e.includes("checkout")||t.includes("pricing")?"decision":e.includes("docs")||e.includes("case-study")||e.includes("guides")||t.includes("docs")?"consideration":e.includes("support")||e.includes("account")||e.includes("dashboard")||t.includes("account")?"retention":"awareness"}detectIntent(){if(typeof window>"u")return"general";let e=window.location.href.toLowerCase(),t=document.title?.toLowerCase()||"",n=`${e} ${t}`;return n.includes("pricing")?"pricing":n.includes("demo")?"demo":n.includes("docs")?"docs":n.includes("case study")?"case-study":"general"}collectMetrics(){let e={},t=this.config?.panthera_blackbox.telemetry?.keys||[],n=["ts.authority","ai.schemaCompleteness","ai.structuredDataQuality","ai.authoritySignals","ai.searchVisibility"];return new Set([...t,...n]).forEach(r=>{r.startsWith("ai.")?r==="ai.schemaCompleteness"?e[r]=this.calculateSchemaCompleteness():r==="ai.structuredDataQuality"?e[r]=this.calculateStructuredDataQuality():r==="ai.authoritySignals"?e[r]=this.calculateAuthoritySignals():r==="ai.searchVisibility"?e[r]=this.calculateSearchVisibility():e[r]=.6+Math.random()*.35:r.startsWith("ts.")?r==="ts.authority"?e[r]=this.calculateAuthorityScore():e[r]=.5+Math.random()*.4:e[r]=0}),e}calculateSchemaCompleteness(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]'),t=document.querySelectorAll('script[type="application/ld+json"][data-panthera]'),n=0;e.length>0&&(n=.3),t.length>0&&(n=.5);let i=new Set;return e.forEach(r=>{try{let s=r.textContent;if(s){let a=JSON.parse(s);a["@type"]&&i.add(a["@type"])}}catch{}}),n+=Math.min(.5,i.size*.1),Math.min(1,n)}calculateStructuredDataQuality(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length===0)return 0;let t=0,n=0,i=0;if(e.forEach(c=>{try{let l=c.textContent;if(!l)return;let o=JSON.parse(l);if(!o["@context"]||!o["@type"])return;t++;let d=Object.keys(o);n+=d.length;let h=o["@type"];h==="Organization"&&o.name&&o.url?i+=2:(h==="Product"&&o.name||h==="Service"&&o.name||h==="FAQPage"&&Array.isArray(o.mainEntity))&&(i+=1)}catch{}}),t===0)return 0;let r=Math.min(.5,t*.25),s=Math.min(.3,n/t/10),a=Math.min(.2,i*.1);return Math.min(1,r+s+a)}calculateAuthoritySignals(){if(typeof document>"u")return 0;let e=0,t=document.body;if(!t)return 0;let n=t.textContent?.toLowerCase()||"",r=["certified","award","trusted","verified","accredited","licensed"].filter(c=>n.includes(c));e+=Math.min(.3,r.length*.05);let a=["review","testimonial","rating","star","customer"].filter(c=>n.includes(c));if(e+=Math.min(.3,a.length*.05),this.config?.panthera_blackbox.authority_grove?.node?.sameAs){let c=this.config.panthera_blackbox.authority_grove.node.sameAs.length;e+=Math.min(.4,c*.1)}return Math.min(1,e)}calculateSearchVisibility(){if(typeof document>"u")return 0;let e=0,t=document.querySelector('meta[name="description"]');t&&t.getAttribute("content")&&t.getAttribute("content").length>50&&(e+=.2);let n=document.querySelector("title");n&&n.textContent&&n.textContent.length>30&&(e+=.2);let i=document.querySelector("h1");i&&i.textContent&&(e+=.2),document.querySelectorAll('script[type="application/ld+json"]').length>0&&(e+=.2);let s=document.querySelectorAll("h2"),a=document.body?.textContent?.length||0;return s.length>=3&&a>1e3&&(e+=.2),Math.min(1,e)}calculateAuthorityScore(){if(!this.config?.panthera_blackbox.authority_grove?.node)return .5;let e=this.config.panthera_blackbox.authority_grove.node,t=.3;return e.sameAs&&e.sameAs.length>0&&(t+=Math.min(.4,e.sameAs.length*.1)),e.keywords&&e.keywords.length>0&&(t+=Math.min(.3,e.keywords.length*.05)),Math.min(1,t)}getSessionId(){if(typeof window>"u")return;let e=window.sessionStorage,t=window.localStorage,n="panthera_session_id",i="panthera_session_ts",r=Date.now(),s=1800*1e3,a=d=>{if(!d)return null;try{let h=d.getItem(n),u=Number(d.getItem(i)||0);if(h&&u&&r-u<s)return d.setItem(i,String(r)),h}catch{return null}return null},c=(d,h)=>{if(!d)return!1;try{return d.setItem(n,h),d.setItem(i,String(r)),!0}catch{return!1}},l=a(e)||a(t);if(l)return l;if(this.memorySessionId&&this.memorySessionTs&&r-this.memorySessionTs<s)return this.memorySessionTs=r,this.memorySessionId;let o=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${r}-${Math.random().toString(16).slice(2)}`;return c(e,o)||c(t,o),this.memorySessionId=o,this.memorySessionTs=r,o}getConfig(){return this.config}async reload(){this.periodicIntervalId!==null&&typeof window<"u"&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0},this.initialized=!1,await this.init()}};(function(){if(typeof window>"u")return;let p=document.currentScript;if(!p)return;let e=p.getAttribute("data-config-url"),t=p.getAttribute("data-telemetry-url"),n=p.getAttribute("data-site-id");if(!e||!t||!n){console.warn("[Panthera Black Box] Missing required data attributes");return}let i=new w({configUrl:e,telemetryUrl:t,siteId:n});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i.init()):i.init(),window.PantheraBlackBox=w,window.panthera=i})();var q=w;return D(B);})();
|
|
3
3
|
//# sourceMappingURL=runtime.global.js.map
|