From dff769b0d589832804e62529f2a0b9ac9fc9068d Mon Sep 17 00:00:00 2001 From: jelkes1 Date: Sat, 14 Nov 2026 22:04:53 -0800 Subject: [PATCH 1/5] Measure consented gallery demo use and verified operation outcomes --- .gitignore | 2 + README-analytics.md | 9 +++ analytics/demo-analytics.js | 56 +++++++++++++++++++ .../client/src/components/ChatPanel.tsx | 5 ++ .../client/src/components/DocumentEditor.tsx | 3 +- .../TrackedChangesControls.tsx | 6 +- .../src/demo/components/topbar/Topbar.tsx | 8 ++- .../src/superdoc/SuperDocEditor.tsx | 5 +- dist-landing/index.html | 1 + rag/apps/web/App.tsx | 11 ++++ rag/apps/web/components/ChatPanel.tsx | 13 +++++ scripts/assemble-release.mjs | 3 + scripts/build-gallery.mjs | 3 + scripts/demo-analytics.test.mjs | 15 +++++ scripts/install-demo-analytics.mjs | 6 ++ .../src/App.vue | 14 +++-- version-history/src/App.tsx | 5 +- version-history/src/useVersionHistory.ts | 6 +- 18 files changed, 159 insertions(+), 12 deletions(-) create mode 100644 README-analytics.md create mode 100644 analytics/demo-analytics.js create mode 100644 scripts/demo-analytics.test.mjs create mode 100644 scripts/install-demo-analytics.mjs diff --git a/.gitignore b/.gitignore index 650bc6d..6daa9b3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ node_modules/ /dist-gallery/ **/test-results/ **/playwright-report/ + +.private/ diff --git a/README-analytics.md b/README-analytics.md new file mode 100644 index 0000000..072d7b3 --- /dev/null +++ b/README-analytics.md @@ -0,0 +1,9 @@ +# Optional demo analytics + +Production release assembly installs one shared, consented GA4 adapter for the gallery and all five demo apps. Local quickstarts and preview hosts do not transmit measurements. The adapter reuses SuperDoc's existing `G-E4T80WRJGS` property and preference format. It never loads identified CRM tracking. + +Public events use fixed demo/action/capability values only. Query values, rooms, filenames, documents, prompts, error text and citation text are excluded. Refusal, withdrawal, DNT, GPC, opt-out and private URLs suppress transport. Change or withdraw the choice through Privacy settings. Events deduplicate per page and action category, rather than counting keystrokes or polling. + +Readiness comes from the editor callback. Review, fields, agent jobs, Q&A and saved versions use actual completion/failure callbacks. Browser export completion does not establish successful Word rendering or a completed developer evaluation. Gallery cards and source/Build this use measure discovery and implementation interest separately. Do not sum per-demo users or compare new collection with an untracked baseline. + +`node --test scripts/*.test.mjs` checks the release scripts and bounded consent contract. Build all affected apps and verify actual deployed ingestion before calling tracking live. Growth's existing Analytics and weekly metrics report own reporting; this adds no schedule or provider. Public content and private room semantics are unchanged. diff --git a/analytics/demo-analytics.js b/analytics/demo-analytics.js new file mode 100644 index 0000000..a10e9e5 --- /dev/null +++ b/analytics/demo-analytics.js @@ -0,0 +1,56 @@ +/* Public, consented demo measurements. No document or session data is read. */ +(() => { + const w = window, d = document, KEY = 'superdoc_cookie_preferences', ID = 'G-E4T80WRJGS'; + const routes = {'/':'gallery','/custom-word-editor/':'custom-word-editor','/collab/':'agentic-collaboration','/builder/':'template-builder-api-v2','/docrag/':'docrag','/version-history/':'version-history'}; + const path = w.location.pathname.replace(/\/*$/, '/'), example = routes[path]; + const actions = new Set(['exposed','option_exposed','selected','load_started','ready','load_failed','explored','edit_observed','review_action','field_edited','ai_started','ai_succeeded','ai_failed','export_requested','export_completed','export_failed','task_started','task_succeeded','task_failed','source_clicked','docs_clicked','build_opened','build_copied','citation_opened']); + const capabilities = new Set(['none','document','review','fields','ai','collaboration','version_history','answer']); + const seen = new Set(); let loaded = false, granted = false, exposureTimer; let origin='builtin_example'; + const privateSignal = () => w.navigator.globalPrivacyControl === true || w.superdocAnalyticsOptOut === true || [w.navigator.doNotTrack,w.doNotTrack].some(v=>['1','yes'].includes(String(v).toLowerCase())); + const publicSurface = () => w.location.hostname === 'demos.superdoc.dev' && w.location.pathname.replace(/\/*$/, '/')===path && example && !w.location.hash && [...new URLSearchParams(w.location.search)].every(([k,v])=>k==='demo_entry'&&['homepage','gallery'].includes(v)); + const preference = () => {try{const c=JSON.parse(w.localStorage.getItem(KEY)),age=Date.now()-c.savedAt;return c.version===1&&age>=0&&age<180*86400000&&typeof c.analytics==='boolean'?c:null;}catch{return null;}}; + function emit(action, capability='none', target=example) { + if (!granted || privateSignal() || !publicSurface() || !actions.has(action) || !capabilities.has(capability) || !Object.values(routes).includes(target)) return false; + const key=[target,action,capability].join(':'); if(seen.has(key))return false; + w.gtag('event','superdoc_demo_event',{send_to:ID,event_version:'demo-gallery-v1',source_project:'demos',page_id:example==='gallery'?'demo_gallery':'demo_app',example_id:target,document_origin:origin,entry:new URLSearchParams(w.location.search).get('demo_entry')==='homepage'?'homepage':new URLSearchParams(w.location.search).get('demo_entry')==='gallery'?'selection':'direct_link',action,capability,format:action.startsWith('export_')?'docx':'none',page_location:'https://demos.superdoc.dev'+path,page_title:'SuperDoc / '+example,page_referrer:''}); + seen.add(key);return true; + } + function apply(c) { + granted=!!c?.analytics&&!privateSignal()&&!!publicSurface(); + if(!granted){if(loaded){w.gtag?.('consent','update',{analytics_storage:'denied'});w.location.reload();}return;} + if(loaded)return;loaded=true;w.dataLayer=w.dataLayer||[];w.gtag=function(){w.dataLayer.push(arguments);}; + w.gtag('consent','default',{analytics_storage:'granted',ad_storage:'denied',ad_user_data:'denied',ad_personalization:'denied'});w.gtag('js',new Date()); + w.gtag('config',ID,{send_page_view:false,allow_google_signals:false,allow_ad_personalization_signals:false,page_location:'https://demos.superdoc.dev'+path,page_referrer:'',page_title:'SuperDoc / '+example}); + const s=d.createElement('script');s.async=true;s.src='https://www.googletagmanager.com/gtag/js?id='+ID;d.head.append(s); + emit('load_started'); if(d.visibilityState==='visible')exposureTimer=setTimeout(()=>{if(d.visibilityState==='visible')emit('exposed');},1000); + } + // A single per-origin settings surface; never inherit another person's consent. + function settings(force=false){ + if(!publicSurface())return; + if(!force&&preference())return; + if(d.getElementById('superdoc-demo-consent'))return; + const panel=d.createElement('section');panel.id='superdoc-demo-consent';panel.setAttribute('aria-label','Optional demo analytics'); + panel.style.cssText='position:fixed;bottom:12px;right:12px;max-width:min(360px,calc(100vw - 24px));padding:16px;background:white;color:#242424;border:1px solid #ccc;border-radius:12px;z-index:99999;font:14px/1.5 system-ui;box-shadow:0 4px 24px #0002'; + const text=d.createElement('p');text.textContent='Help us improve these demos with optional usage analytics. Document contents, prompts and filenames are excluded.';panel.append(text); + for(const [label,value] of [['Allow analytics',true],['Decline',false]]){const b=d.createElement('button');b.textContent=label;b.style.cssText='padding:8px;margin:4px';b.onclick=()=>{const choice={version:1,savedAt:Date.now(),analytics:value&&!privateSignal(),identification:false};try{w.localStorage.setItem(KEY,JSON.stringify(choice));}catch{}panel.remove();apply(choice);};panel.append(b);} + const privacy=d.createElement('a');privacy.href='https://superdocportal.dev/privacy';privacy.textContent='Privacy policy';panel.append(privacy);d.body.append(panel); + } + function start(){ + if(!publicSurface())return; + apply(preference());settings(); + const b=d.createElement('button');b.textContent='Privacy settings';b.style.cssText='position:fixed;left:8px;bottom:8px;z-index:9998;font:12px system-ui;padding:5px';b.onclick=()=>settings(true);d.body.append(b); + d.addEventListener('click',e=>{ + if(!e.isTrusted)return;const a=e.target.closest?.('a'); + if(a){try{const url=new URL(a.href,w.location.href),target=routes[url.pathname.replace(/\/*$/, '/')];if(url.origin===w.location.origin&&target&&target!=='gallery'){emit('selected','none',target);if(!url.search&&!url.hash){url.searchParams.set('demo_entry','gallery');a.href=url.href;}}else if(url.hostname==='github.com'||url.hostname==='docs.superdoc.dev'){const card=a.closest('.demo-card'),live=card?.querySelector('.card-main-link');let id=example;try{if(live)id=routes[new URL(live.href).pathname.replace(/\/*$/, '/')];}catch{}emit(url.hostname==='github.com'?'source_clicked':'docs_clicked','none',id);}}catch{}} + const button=e.target.closest?.('button');if(button){if(button.hasAttribute('data-build-dialog')||button.textContent.trim()==='Build this')emit('build_opened','none',button.getAttribute('data-build-dialog')?.replace(/^build-/, '')||example);} + }); + d.addEventListener('visibilitychange',()=>{clearTimeout(exposureTimer);if(d.visibilityState==='visible')exposureTimer=setTimeout(()=>emit('exposed'),1000);}); + d.addEventListener('change',e=>{if(e.isTrusted&&e.target?.type==='file')origin='visitor_file';}); + d.addEventListener('input',e=>{if(e.isTrusted&&e.target.closest?.('[contenteditable="true"],[data-editor-host="v2"][role="textbox"]'))emit('edit_observed','document');}); + if(example==='gallery'&&w.IntersectionObserver){const timers=new Map();const observer=new IntersectionObserver(entries=>{for(const item of entries){clearTimeout(timers.get(item.target));if(item.isIntersecting&&item.intersectionRatio>=.5)timers.set(item.target,setTimeout(()=>{if(d.visibilityState==='visible'){const a=item.target.querySelector('a[href]');try{emit('option_exposed','none',routes[new URL(a.href).pathname.replace(/\/*$/, '/')]);}catch{}}},1000));}},{threshold:[0,.5]});d.querySelectorAll('.demo-card').forEach(el=>observer.observe(el));d.addEventListener('visibilitychange',()=>{if(d.visibilityState!=='visible')for(const t of timers.values())clearTimeout(t);});} + } + w.addEventListener('superdoc:demo',e=>{try{emit(e.detail?.action,e.detail?.capability,e.detail?.example||example);}catch{}}); + w.addEventListener('storage',e=>{if(e.key===KEY||e.key===null)apply(preference());}); + w.addEventListener('pageshow',e=>{if(e.persisted)apply(preference());}); + if(d.readyState==='loading')d.addEventListener('DOMContentLoaded',start,{once:true});else start(); +})(); diff --git a/canonical-collaboration-demo/client/src/components/ChatPanel.tsx b/canonical-collaboration-demo/client/src/components/ChatPanel.tsx index bdcf64b..cce4bc7 100644 --- a/canonical-collaboration-demo/client/src/components/ChatPanel.tsx +++ b/canonical-collaboration-demo/client/src/components/ChatPanel.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { FormEvent, KeyboardEvent, PointerEvent, useEffect, useLayoutEffect, useRef, useState } from 'react'; import Markdown from 'react-markdown'; import type { SuperDoc } from 'superdoc'; @@ -146,7 +147,9 @@ export function ChatPanel({ roomId, disabled, unavailableReason, width, onWidthC async function finishJob(job: Job) { onDocumentUpdated?.(); + if (job.status === 'failed') demoMetric('ai_failed', 'collaboration'); if (job.status === 'completed') { + demoMetric('ai_succeeded', 'collaboration'); const history = await api.getChatHistory(roomId); setMessages(history); setJobs((current) => current.filter((candidate) => candidate.id !== job.id)); @@ -208,10 +211,12 @@ export function ChatPanel({ roomId, disabled, unavailableReason, width, onWidthC promptNavigationRef.current = null; setPrompt(''); try { + demoMetric('ai_started', 'collaboration'); const job = await api.createJob(roomId, message, isSuggesting, selectedText || undefined); setJobs((current) => [...current, job]); await watchJob(job); } catch (caught) { + demoMetric('ai_failed', 'collaboration'); setError(caught instanceof Error ? caught.message : String(caught)); } } diff --git a/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx b/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx index 31c3788..646735c 100644 --- a/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx +++ b/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { SuperDocEditor, type SuperDocEditorProps } from '@superdoc/react'; import type { SuperDoc } from 'superdoc'; @@ -123,7 +124,7 @@ export const DocumentEditor = memo(function DocumentEditor({ room, mode, onActiv instance.current = superdoc; mountedEditor.current = true; setEditorReady(true); - onReady(superdoc); + onReady(superdoc); demoMetric('ready', 'collaboration'); }} onException={(event) => { console.error('SuperDoc error', event); diff --git a/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx b/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx index d56e9f3..0926eb2 100644 --- a/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx +++ b/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Optional analytics. */ } }; import { useState } from 'react'; import { useSuperDocCommand } from 'superdoc/ui/react'; import './TrackedChangesControls.css'; @@ -16,11 +17,14 @@ export function TrackedChangesControls() { setPending(action); setError(''); try { + demoMetric('task_started', 'review'); const result = await command.executeAsync(); if (result === false || (typeof result === 'object' && result !== null && 'success' in result && !result.success)) { + demoMetric('task_failed', 'review'); setError(`Could not ${action} all tracked changes.`); - } + } else { demoMetric('task_succeeded', 'review'); } } catch { + demoMetric('task_failed', 'review'); setError(`Could not ${action} all tracked changes.`); } finally { setPending(null); diff --git a/custom-word-editor/src/demo/components/topbar/Topbar.tsx b/custom-word-editor/src/demo/components/topbar/Topbar.tsx index d58a3a1..ec04262 100644 --- a/custom-word-editor/src/demo/components/topbar/Topbar.tsx +++ b/custom-word-editor/src/demo/components/topbar/Topbar.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { useRef, useState, type ReactNode } from 'react'; import { BlankDOCX } from 'superdoc'; import { useSuperDocDocument, useSuperDocHost, useSuperDocUI } from 'superdoc/ui/react'; @@ -20,8 +21,11 @@ export function Topbar({ viewControls, onDocumentReplaced }: { viewControls?: Re const exportDocument = async (exportedName = 'reviewed-contract') => { if (!host || !('export' in host) || typeof host.export !== 'function') return; setSaving(true); + demoMetric('export_requested'); try { await host.export({ exportType: ['docx'], exportedName }); + demoMetric('export_completed'); + } catch (error) { demoMetric('export_failed'); throw error; } finally { setSaving(false); } @@ -83,13 +87,15 @@ export function Topbar({ viewControls, onDocumentReplaced }: { viewControls?: Re }], }); setSaving(true); + demoMetric('export_requested'); const result = await ui.document.export({ exportType: ['docx'], triggerDownload: false }); if (!(result instanceof Blob)) throw new Error('SuperDoc did not return a DOCX file.'); const writable = await handle.createWritable(); await writable.write(result); - await writable.close(); + await writable.close(); demoMetric('export_completed'); } catch (error) { if (error instanceof DOMException && error.name === 'AbortError') return; + demoMetric('export_failed'); console.error(error); setImportError('The document could not be saved.'); } finally { diff --git a/custom-word-editor/src/superdoc/SuperDocEditor.tsx b/custom-word-editor/src/superdoc/SuperDocEditor.tsx index 0e591aa..b352756 100644 --- a/custom-word-editor/src/superdoc/SuperDocEditor.tsx +++ b/custom-word-editor/src/superdoc/SuperDocEditor.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Optional analytics. */ } }; import { useCallback, useEffect, useRef, useState } from 'react'; import type { RefObject } from 'react'; import { SuperDoc } from 'superdoc'; @@ -63,7 +64,7 @@ export function SuperDocEditor({ contentControls: true, }, onReady: ({ superdoc: readySuperDoc }) => { - ready = true; + ready = true; demoMetric('ready'); setError(''); setSuperDoc(readySuperDoc); }, @@ -71,7 +72,7 @@ export function SuperDocEditor({ // Protected edits are expected rejections, not document-open failures. if ('code' in exception && exception.code === 'edit-rejected') return; console.error(exception.error); - if (!ready) setError('The review document could not be opened.'); + if (!ready) { demoMetric('load_failed'); setError('The review document could not be opened.'); } }, }); diff --git a/dist-landing/index.html b/dist-landing/index.html index d2a6132..e59e95c 100644 --- a/dist-landing/index.html +++ b/dist-landing/index.html @@ -123,6 +123,7 @@ try { await navigator.clipboard.writeText(dialog.querySelector('code').textContent); copy.textContent = 'Copied'; + window.dispatchEvent(new CustomEvent('superdoc:demo', {detail:{action:'build_copied',capability:'none',example:dialog.id.replace(/^build-/, '')}})); status.textContent = 'Commands copied to clipboard.'; } catch { status.textContent = 'Could not access the clipboard. Select the commands above and copy them.'; diff --git a/rag/apps/web/App.tsx b/rag/apps/web/App.tsx index 3a2202a..01a66d7 100644 --- a/rag/apps/web/App.tsx +++ b/rag/apps/web/App.tsx @@ -1,3 +1,13 @@ +const demoMetric = (action: string, capability = "document") => { + try { + window.dispatchEvent( + new CustomEvent("superdoc:demo", { detail: { action, capability } }), + ); + } catch { + /* Analytics must not affect the demo. */ + } +}; + import { useCallback, useState } from "react"; import { createRoot } from "react-dom/client"; import { ChatPanel } from "./components/ChatPanel"; @@ -24,6 +34,7 @@ function App() { const doc = resp.documents.find((d) => d.id === citation.documentId); if (doc) setActiveFilename(doc.filename); } + demoMetric("citation_opened", "answer"); setActiveCitation(null); requestAnimationFrame(() => setActiveCitation(citation)); }, diff --git a/rag/apps/web/components/ChatPanel.tsx b/rag/apps/web/components/ChatPanel.tsx index 33a8531..2922903 100644 --- a/rag/apps/web/components/ChatPanel.tsx +++ b/rag/apps/web/components/ChatPanel.tsx @@ -1,3 +1,13 @@ +const demoMetric = (action: string, capability = "document") => { + try { + window.dispatchEvent( + new CustomEvent("superdoc:demo", { detail: { action, capability } }), + ); + } catch { + /* Analytics must not affect the demo. */ + } +}; + import { useEffect, useRef, useState } from "react"; import { type Citation, queryDocuments } from "../lib/api"; import { ChatMessage } from "./ChatMessage"; @@ -56,7 +66,9 @@ export function ChatPanel({ onCitationClick, disabled }: Props) { setLoading(true); try { + demoMetric("ai_started", "answer"); const result = await queryDocuments(q); + demoMetric("ai_succeeded", "answer"); setMessages((m) => m.map((msg) => msg.id === loadingMsg.id @@ -70,6 +82,7 @@ export function ChatPanel({ onCitationClick, disabled }: Props) { ), ); } catch (err) { + demoMetric("ai_failed", "answer"); setMessages((m) => m.map((msg) => msg.id === loadingMsg.id diff --git a/scripts/assemble-release.mjs b/scripts/assemble-release.mjs index 2dd1058..661ebd4 100644 --- a/scripts/assemble-release.mjs +++ b/scripts/assemble-release.mjs @@ -1,3 +1,4 @@ +import { installDemoAnalytics } from './install-demo-analytics.mjs'; import { cp, mkdir, readFile, rm } from "node:fs/promises"; import path from "node:path"; import { renderGallery } from "./render-gallery.mjs"; @@ -36,3 +37,5 @@ await collabAssets(output); // Attach the version-history API and WebSocket proxy to the static release. await assembleVersionHistory({ output, backendUrl: process.env.VERSION_HISTORY_BACKEND_URL }); console.log(`Assembled ${manifest.length} demos from demos.json`); + +await installDemoAnalytics(output, manifest.map(d=>d.liveDemoUri.replace(/^\/+|\/+$/g,''))); diff --git a/scripts/build-gallery.mjs b/scripts/build-gallery.mjs index c90d18e..952af0b 100644 --- a/scripts/build-gallery.mjs +++ b/scripts/build-gallery.mjs @@ -1,3 +1,4 @@ +import { installDemoAnalytics } from './install-demo-analytics.mjs'; import { cp, mkdir, readFile, rm } from "node:fs/promises"; import { spawnSync } from "node:child_process"; import path from "node:path"; @@ -62,3 +63,5 @@ await cp( await renderGallery({ mode: "local", output: path.join(output, "index.html") }); console.log(`Built local gallery in ${path.relative(root, output)}/`); + +await installDemoAnalytics(output, [...demos.map(d=>d.route),'collab']); diff --git a/scripts/demo-analytics.test.mjs b/scripts/demo-analytics.test.mjs new file mode 100644 index 0000000..6bb4761 --- /dev/null +++ b/scripts/demo-analytics.test.mjs @@ -0,0 +1,15 @@ +import {test} from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';import {readFile} from 'node:fs/promises'; +const code=await readFile(new URL('../analytics/demo-analytics.js',import.meta.url),'utf8'); +function fixture({consent=true,host='demos.superdoc.dev',search='',hash='',dnt='0',gpc=false}={}){ + const listeners={},events=[],scripts=[],nodes=[],storage=new Map();let reloads=0; + if(consent!==null)storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:consent,identification:false})); + const el=()=>({style:{},setAttribute(){},append(...v){nodes.push(...v)},remove(){}}); + const document={readyState:'complete',visibilityState:'visible',head:{append:s=>scripts.push(s)},body:el(),createElement:el,getElementById:()=>null,addEventListener:(k,f)=>{listeners['d:'+k]=f;},querySelectorAll:()=>[]}; + const window={document,location:{hostname:host,pathname:'/custom-word-editor/',search,hash,origin:'https://'+host,href:'https://'+host+'/custom-word-editor/'+search+hash,reload:()=>reloads++},navigator:{doNotTrack:dnt,globalPrivacyControl:gpc},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},addEventListener:(k,f)=>{listeners[k]=f;}}; + vm.runInNewContext(code,{window,document,URL,URLSearchParams,Date,Set,Map,setTimeout,clearTimeout}); + return {window,scripts,nodes,events:()=>window.dataLayer?.filter(x=>x[0]==='event')??[],emit:(detail)=>listeners['superdoc:demo']?.({detail}),withdraw:()=>{storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:false}));listeners.storage({key:'superdoc_cookie_preferences'});return reloads;}}; +} +test('production events are bounded and deduplicated, without private caller properties',()=>{const f=fixture();f.emit({action:'task_succeeded',capability:'review',prompt:'secret',room:'secret'});f.emit({action:'task_succeeded',capability:'review'});f.emit({action:'arbitrary',capability:'review'});assert.equal(f.scripts.length,1);assert.equal(f.events().filter(x=>x[2].action==='task_succeeded').length,1);assert.ok(!JSON.stringify(f.events()).includes('secret'));assert.equal(f.events()[0][2].page_location,'https://demos.superdoc.dev/custom-word-editor/');}); +for(const opts of [{consent:false},{consent:null},{dnt:'1'},{gpc:true},{host:'preview.pages.dev'},{search:'?room=private'},{hash:'#token'},{search:'?demo_entry=private'}])test('no provider or events for '+JSON.stringify(opts),()=>{const f=fixture(opts);f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.scripts.length,0);assert.equal(f.events().length,0);}); +test('consent withdrawal stops custom events and reloads the loaded vendor',()=>{const f=fixture();assert.equal(f.withdraw(),1);const n=f.events().length;f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.events().length,n);}); +test('task failures and successful operations remain distinct',()=>{const f=fixture();f.emit({action:'task_failed',capability:'review'});f.emit({action:'task_succeeded',capability:'review'});assert.equal(f.events().filter(x=>x[2].action.startsWith('task_')).length,2);}); diff --git a/scripts/install-demo-analytics.mjs b/scripts/install-demo-analytics.mjs new file mode 100644 index 0000000..1e518c1 --- /dev/null +++ b/scripts/install-demo-analytics.mjs @@ -0,0 +1,6 @@ +import {copyFile,readFile,writeFile} from 'node:fs/promises'; +import path from 'node:path'; +export async function installDemoAnalytics(output,routes){ + await copyFile(new URL('../analytics/demo-analytics.js',import.meta.url),path.join(output,'demo-analytics.js')); + for(const route of ['',...routes]){const file=path.join(output,route,'index.html'),html=await readFile(file,'utf8');if(!html.includes('src="/demo-analytics.js"'))await writeFile(file,html.replace('','\n'));} +} diff --git a/template-builder-document-api-v2-demo/src/App.vue b/template-builder-document-api-v2-demo/src/App.vue index 262deb9..9abfa4d 100644 --- a/template-builder-document-api-v2-demo/src/App.vue +++ b/template-builder-document-api-v2-demo/src/App.vue @@ -1,4 +1,6 @@