@databrainhq/mcp-server 0.3.0-rc.2 → 0.3.0-rc.4

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.
@@ -1,314 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- APP_MIME,
4
- CHART_URI,
5
- DatabrainClient,
6
- KPI_URI,
7
- MCP_SERVER_VERSION,
8
- READ_ONLY,
9
- chartResult,
10
- createServiceBundle,
11
- enableChartApps,
12
- pageSchema,
13
- referenceSchema,
14
- registerAllPrompts,
15
- registerAllResources,
16
- registerAllTools,
17
- toolContext,
18
- viewSchema
19
- } from "./chunk-3AFT7S6E.js";
20
-
21
- // src/apps/server.ts
22
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
23
-
24
- // src/apps/registry.ts
25
- import { z } from "zod";
26
-
27
- // src/apps/backend.ts
28
- var RENDER_PATH = "/api/v2/dashboard/mcp-chart";
29
- var UncachedChartClient = class extends DatabrainClient {
30
- constructor(delegate) {
31
- super({ apiUrl: delegate.getApiUrl(), demoDomain: delegate.getDemoDomain() });
32
- this.delegate = delegate;
33
- }
34
- request(options) {
35
- return this.delegate.request({ ...options, cacheKey: void 0, cacheTtlMs: void 0 });
36
- }
37
- };
38
- function createChartBackend(client) {
39
- const services = createServiceBundle(new UncachedChartClient(client));
40
- return {
41
- async execute(action, rawReference, rawView) {
42
- const reference = referenceSchema.parse(rawReference);
43
- const view = viewSchema.parse(rawView);
44
- const app = await services.widgetService.resolveDataAppName(void 0, reference.embedId);
45
- if (!app.ok) throw new Error("Chart scope unavailable");
46
- const scope = await services.widgetService.ensureReadableDashboardScope({
47
- embedId: reference.embedId,
48
- clientId: reference.clientId,
49
- dataAppName: app.value
50
- });
51
- if (!scope.ok) throw new Error("Chart scope denied");
52
- const { token } = await services.guestTokenService.generateToken({
53
- clientId: reference.clientId,
54
- dataAppName: app.value,
55
- allowedEmbeds: [reference.embedId],
56
- permissions: {
57
- isDisableMetricCreation: true,
58
- isEnableManageMetrics: false,
59
- isEnableMetricUpdation: false,
60
- isEnableArchiveMetrics: false
61
- }
62
- });
63
- if (!token) throw new Error("Guest scope unavailable");
64
- const page = await client.request({
65
- method: "POST",
66
- path: RENDER_PATH,
67
- auth: "none",
68
- token,
69
- body: {
70
- action,
71
- embedId: reference.embedId,
72
- widgetId: reference.widgetId,
73
- ...view,
74
- pageSize: 50,
75
- width: 600,
76
- height: 320,
77
- animation: false
78
- },
79
- skipDataUnwrap: true
80
- });
81
- return pageSchema.parse(page);
82
- }
83
- };
84
- }
85
-
86
- // src/apps/tile.ts
87
- var TILE_SCRIPT = String.raw`(()=>{
88
- const $=id=>document.getElementById(id),root=document.documentElement,pending=new Map();
89
- let seq=0,origin='*',ready=false,closed=false,ref=null,view={},next=null,context={},busy=false,revision=0,rawSvg=null;
90
- function send(message){if(!closed)parent.postMessage({jsonrpc:'2.0',...message},origin)}
91
- function rpc(method,params){return new Promise((resolve,reject)=>{const id=++seq;
92
- const timer=setTimeout(()=>{pending.delete(id);reject(Error('timeout'))},30000);
93
- pending.set(id,{resolve,reject,timer});send({id,method,params})})}
94
- function status(text,bad){const s=$('status');s.textContent=text;s.toggleAttribute('data-error',!!bad);if(bad)$('plot').dataset.state='off'}
95
- function paint(){const img=$('chart-image');if(img&&rawSvg)img.src='data:image/svg+xml,'+encodeURIComponent(rawSvg.replace(/<\/svg>\s*$/i,'<style>text{fill:'+getComputedStyle(document.body).color+'!important}</style></svg>'))}
96
- function controls(){document.querySelectorAll('button,input,select').forEach(e=>{e.disabled=busy});
97
- $('refresh').hidden=!ref;$('next').hidden=!next;$('range').hidden=!ref;$('plot').toggleAttribute('data-busy',busy);
98
- $('expand').hidden=!context.availableDisplayModes?.includes('fullscreen');
99
- root.toggleAttribute('data-deep',context.displayMode==='fullscreen'||$('expand').hidden)}
100
- function host(change){context={...context,...change};if(change.theme==='dark'||change.theme==='light')root.style.colorScheme=change.theme;
101
- const vars=change.styles?.variables||{};for(const [key,value] of Object.entries(vars)){
102
- if(/^--(?:color-|font-|border-|shadow-)/.test(key)&&typeof value==='string'&&!/url\s*\(|@import/i.test(value))root.style.setProperty(key,value)}
103
- const face=change.styles?.css?.fonts;if(typeof face==='string'&&face.length<4000&&!/@import|javascript:/i.test(face))$('hostfont').textContent=face;
104
- const insets=change.safeAreaInsets;if(insets)for(const edge of ['top','right','bottom','left']){
105
- const n=insets[edge];if(Number.isFinite(n))root.style.setProperty('--safe-'+edge,Math.max(0,Math.min(n,200))+'px')}
106
- root.dataset.mode=context.displayMode==='fullscreen'?'full':'inline';
107
- $('expand').textContent=context.displayMode==='fullscreen'?'Back to conversation':'Expand';paint();controls()}
108
- function resize(){if(ready)send({method:'ui/notifications/size-changed',params:{width:document.body.scrollWidth,height:document.body.scrollHeight}})}
109
- function table(rows,columns){$('rows').replaceChildren();$('data').hidden=!rows?.length;if(!rows?.length)return;
110
- $('count').textContent=rows.length===1?'Show the 1 row behind this':'Show the '+rows.length+' rows behind this';
111
- const t=document.createElement('table');
112
- const header=document.createElement('tr');for(const name of columns){const th=document.createElement('th');th.scope='col';th.textContent=name;header.append(th)}
113
- const head=document.createElement('thead');head.append(header);t.append(head);const body=document.createElement('tbody');
114
- for(const row of rows.slice(0,50)){const tr=document.createElement('tr');for(const key of columns){const td=document.createElement('td');td.textContent=String(row[key]??'');tr.append(td)}body.append(tr)}t.append(body);$('rows').append(t)}
115
- async function display(mode){try{const answer=await rpc('ui/request-display-mode',{mode});
116
- host({displayMode:answer.mode||context.displayMode});if(root.dataset.mode==='full'&&!$('data').hidden)$('data').open=true;resize()}
117
- catch{status('Expanded view is unavailable in this host.',1)}}
118
- function wait(){busy=true;if(!$('plot').firstChild)$('plot').dataset.state='wait';status('Loading chart…');controls()}
119
- async function call(name,extra={}){if(!ready||!ref||busy)return;wait();const rev=++revision;
120
- try{const result=await rpc('tools/call',{name,arguments:{reference:ref,view:{...view,...extra},context:'User is interacting with the chart tile.'}});
121
- if(rev===revision)render(result)}catch{if(rev===revision)status('Could not load the chart. Select Refresh to try again.',1)}finally{busy=false;controls()}}
122
- function render(result){busy=false;controls();
123
- if(result?.isError){status('Chart unavailable. Check your access to this dashboard, then select Refresh.',1);return}
124
- const p=result?.structuredContent;if(!p||typeof p!=='object'){status('No chart data came back for this result.',1);return}
125
- revision++;rawSvg=null;$('plot').replaceChildren();$('plot').dataset.state='ready';$('choices').replaceChildren();$('tip').textContent='';delete $('tip').dataset.value;
126
- ref=p.reference||null;view=p.view||{};next=p.nextCursor||null;
127
- $('title').textContent=p.title||'Analytics';$('description').textContent=p.description||'';
128
- if(p.kind==='dashboard'){$('plot').dataset.state='off';
129
- for(const item of p.widgets||[]){const b=document.createElement('button');b.textContent=item.name||'Untitled widget';b.onclick=()=>{ref=item.reference;view={};call('render_chart')};$('choices').append(b)}
130
- status(p.widgets?.length?'Choose a chart to explore.':'This dashboard has no charts yet.');
131
- }else if(p.kind==='kpi'){
132
- const number=document.createElement('p');number.className='kpi';number.textContent=String(p.value??'—');$('plot').append(number);status('');
133
- }else if(p.svg){
134
- const box=document.createElement('div');box.className='chart';box.style.aspectRatio=p.width+'/'+p.height;
135
- const img=document.createElement('img');img.id='chart-image';rawSvg=p.svg;img.alt=p.title||'Chart';img.onerror=()=>{status('Chart image unavailable. The data is in the table below.',1);$('data').open=$('data').toggleAttribute('data-only',true)};box.append(img);
136
- for(const point of p.points||[]){const b=document.createElement('button');b.className='point';b.setAttribute('aria-label',point.label+': '+point.value);b.setAttribute('aria-pressed','false');
137
- b.style.left=100*point.x/p.width+'%';b.style.top=100*point.y/p.height+'%';b.style.width=100*point.width/p.width+'%';b.style.height=100*point.height/p.height+'%';
138
- const hover=()=>{$('tip').textContent=point.label+': '+point.value;$('tip').dataset.value='1'};b.onmouseenter=hover;b.onfocus=hover;
139
- b.onclick=()=>{box.querySelectorAll('.point').forEach(e=>e.setAttribute('aria-pressed','false'));b.setAttribute('aria-pressed','true');hover();
140
- $('choices').replaceChildren();if(point.drillId){const drill=document.createElement('button');drill.className='primary';drill.textContent='Explore selected data';drill.onclick=()=>call('drill_down',{drillId:point.drillId,cursor:undefined});$('choices').append(drill)}};box.append(b)}$('plot').append(box);
141
- status(p.rows?.length?'':'This chart has no data for the current view.');if(p.points?.length)$('tip').textContent='Select part of the chart to read its value.';
142
- }else{$('plot').dataset.state='off';status(p.rows?.length?'Chart preview is unavailable. The data is in the table below.':'No data for this view.',!p.rows?.length)}
143
- paint();table(p.rows||[],p.columns||Object.keys(p.rows?.[0]||{}));
144
- const only=!p.svg&&p.value===undefined;$('data').open=only;$('data').toggleAttribute('data-only',only);controls();resize()}
145
- $('refresh').onclick=()=>call('refresh_widget',{cursor:undefined});$('next').onclick=()=>call('render_chart',{cursor:next});
146
- $('expand').onclick=()=>display(context.displayMode==='fullscreen'?'inline':'fullscreen');
147
- $('dates').onclick=()=>{const from=$('from').value,to=$('to').value;if(!from||!to||from>to){status('Choose a start date on or before the end date.',1);return}call('change_date_range',{dateRange:{from,to},cursor:undefined,drillId:undefined})};
148
- function receive(event){if(event.source!==parent||closed)return;const m=event.data;
149
- if(!m||Array.isArray(m)||m.jsonrpc!=='2.0'||(origin!=='*'&&event.origin!==origin))return;
150
- if(!m.method&&pending.has(m.id)&&('result'in m||'error'in m)){if(origin==='*'&&event.origin!=='null')origin=event.origin;
151
- const p=pending.get(m.id);pending.delete(m.id);clearTimeout(p.timer);m.error?p.reject(Error('host error')):p.resolve(m.result);return}
152
- if(m.method==='ping'&&m.id!==undefined){send({id:m.id,result:{}});return}
153
- if(m.method==='ui/resource-teardown'){send({id:m.id,result:{}});closed=true;revision++;for(const p of pending.values()){clearTimeout(p.timer);p.reject(Error('closed'))}pending.clear();observer.disconnect();removeEventListener('message',receive);return}
154
- if(!ready||m.id!==undefined)return;
155
- if(m.method==='ui/notifications/tool-result'){render(m.params)}
156
- else if(m.method==='ui/notifications/tool-input'){wait()}
157
- else if(m.method==='ui/notifications/host-context-changed'){host(m.params||{});resize()}
158
- else if(m.method==='ui/notifications/tool-cancelled'){revision++;busy=false;$('plot').dataset.state='off';status('Chart request cancelled.');controls()}}
159
- addEventListener('message',receive);const observer=new ResizeObserver(resize);observer.observe(document.body);controls();
160
- rpc('ui/initialize',{protocolVersion:'2026-01-26',appInfo:{name:'Databrain chart tile',version:'1.0.0'},appCapabilities:{availableDisplayModes:['inline','fullscreen']}})
161
- .then(r=>{if(r.protocolVersion!=='2026-01-26')throw Error('version');host(r.hostContext||{});ready=true;send({method:'ui/notifications/initialized'});resize()})
162
- .catch(()=>status('This chart needs a host that supports MCP Apps.',1));
163
- })();`;
164
- function tileHtml(kind = "chart") {
165
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
166
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'">
167
- <title>Databrain ${kind} tile</title><style id="hostfont"></style><style>
168
- /* Host tokens are the Claude MCP Apps style-variable names. Every one carries a fallback:
169
- hosts may ship any subset, so nothing here may depend on a token existing. */
170
- :root{color-scheme:light dark;
171
- --dbn-bg:var(--color-background-primary,Canvas);--dbn-text:var(--color-text-primary,CanvasText);
172
- --dbn-mute:var(--color-text-secondary,GrayText);--dbn-faint:var(--color-text-tertiary,GrayText);
173
- --dbn-edge:var(--color-border-secondary,ButtonBorder);--dbn-line:var(--color-border-tertiary,var(--dbn-edge));
174
- --dbn-accent:var(--color-text-info,LinkText);--dbn-ring:var(--color-ring-primary,var(--dbn-accent));
175
- --dbn-bad:var(--color-text-danger,var(--dbn-text));--dbn-bad-edge:var(--color-border-danger,currentColor);
176
- --dbn-quiet:color-mix(in srgb,currentColor 6%,transparent);
177
- --bw:var(--border-width-regular,1px);--r-s:var(--border-radius-sm,6px);--r-m:var(--border-radius-md,8px);--r-l:var(--border-radius-lg,10px);
178
- --med:var(--font-weight-medium,500);--semi:var(--font-weight-semibold,600);
179
- /* One curve. Quick / standard / display-mode. Corporate: no overshoot. */
180
- --e:cubic-bezier(.2,0,0,1);--q:120ms;--s:300ms;--l:400ms}
181
- *{box-sizing:border-box}
182
- body{margin:0;padding:var(--safe-top,0px) var(--safe-right,0px) var(--safe-bottom,0px) var(--safe-left,0px);background:var(--dbn-bg);color:var(--dbn-text);
183
- font:var(--font-text-sm-size,14px)/var(--font-text-sm-line-height,1.4) var(--font-sans,system-ui)}
184
- main{padding:20px;max-width:1200px;margin:auto;transition:padding var(--l) var(--e)}
185
- header{display:flex;align-items:start;justify-content:space-between;gap:12px}header>div{min-width:0}
186
- h1{font-size:var(--font-heading-md-size,18px);line-height:var(--font-heading-md-line-height,1.4);margin:0 0 6px;font-weight:var(--semi);letter-spacing:-.01em;overflow-wrap:anywhere;transition:font-size var(--l) var(--e)}
187
- p{margin:6px 0;color:var(--dbn-mute);overflow-wrap:anywhere}#expand{flex:none}
188
- button,input{font:inherit;color:inherit;background:var(--dbn-bg);border:var(--bw) solid var(--dbn-edge);border-radius:var(--r-s);padding:7px 10px}
189
- button{cursor:pointer;transition:background-color var(--q) var(--e),border-color var(--q) var(--e)}
190
- input{max-width:160px;min-width:0}button:hover:not(:disabled){background:var(--dbn-quiet)}button:disabled{color:var(--dbn-faint);cursor:default}
191
- button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--dbn-ring);outline-offset:2px}
192
- #choices button.primary{border-color:var(--dbn-accent);font-weight:var(--med)}
193
- #status:empty{margin:0}
194
- #status[data-error]{color:var(--dbn-bad);font-weight:var(--med);border-left:2px solid var(--dbn-bad-edge);background:var(--color-background-danger,transparent);border-radius:0 var(--r-s) var(--r-s) 0;padding:8px 10px;margin:8px 0}
195
- /* Reserved plot. The skeleton is a static bar silhouette matching the 15:8 backend render:
196
- Claude's guidance asks for a skeleton that matches the final layout, and bans nothing here,
197
- but shimmer is banned by our own motion budget - so this paints once and never repaints. */
198
- #plot{position:relative;transition:opacity var(--q) var(--e)}#plot[data-busy]{opacity:.55}
199
- #plot[data-state=wait]{aspect-ratio:15/8}
200
- #plot[data-state=wait]::before,#plot[data-state=ready]::before{content:'';position:absolute;pointer-events:none;inset:16% 6% 13%;
201
- border-bottom:var(--bw) solid var(--dbn-line);transition:opacity var(--s) var(--e);
202
- background:linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 0 100%/11% 44% no-repeat,
203
- linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 22% 100%/11% 71% no-repeat,
204
- linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 44% 100%/11% 57% no-repeat,
205
- linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 66% 100%/11% 86% no-repeat,
206
- linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 88% 100%/11% 33% no-repeat}
207
- #plot[data-state=ready]::before{opacity:0}
208
- .chart{position:relative;width:100%;margin:12px 0}.chart img{width:100%;height:100%;display:block}
209
- .point{position:absolute;padding:0;border:0;background:transparent;border-radius:var(--border-radius-xs,4px);
210
- outline:2px solid transparent;outline-offset:1px;transition:background-color var(--q) var(--e),outline-color var(--q) var(--e)}
211
- .point:hover{background:color-mix(in srgb,currentColor 12%,transparent)}
212
- .point[aria-pressed=true]{outline-color:var(--dbn-accent);background:color-mix(in srgb,var(--dbn-accent) 18%,transparent)}
213
- .kpi{font-size:clamp(34px,10vw,44px);line-height:1.1;font-weight:var(--semi);letter-spacing:-.025em;font-variant-numeric:tabular-nums;color:var(--dbn-text);margin:14px 0 6px;transition:font-size var(--l) var(--e)}
214
- #tip{color:var(--dbn-mute);font-size:var(--font-text-xs-size,12px);overflow-wrap:anywhere;min-height:1.4em}
215
- #tip[data-value]{color:var(--dbn-text);font-weight:var(--med);font-variant-numeric:tabular-nums}
216
- #choices,footer,.dates{display:flex;gap:8px;flex-wrap:wrap;align-items:center}#choices{margin:10px 0 0}footer{margin-top:12px}.dates{margin:8px 0 2px}
217
- label{display:flex;align-items:center;gap:6px;color:var(--dbn-mute)}
218
- #range{margin-top:10px}#data{margin-top:2px}#data[hidden],#range[hidden]{display:none}
219
- html:not([data-deep]) #range,html:not([data-deep]) #data:not([data-only]){display:none}
220
- summary{cursor:pointer;color:var(--dbn-mute);font-size:var(--font-text-xs-size,12px);padding:5px 0;width:fit-content;transition:color var(--q) var(--e)}summary:hover{color:var(--dbn-text)}
221
- #rows{overflow:auto;max-height:260px;border-radius:var(--r-s)}
222
- table{border-collapse:collapse;width:100%;font-size:var(--font-text-xs-size,12px)}
223
- th,td{text-align:left;padding:8px;border-bottom:var(--bw) solid var(--dbn-line);overflow-wrap:anywhere}
224
- td:last-child{font-variant-numeric:tabular-nums}th{font-weight:var(--semi);position:sticky;top:0;background:var(--dbn-bg);color:var(--dbn-mute)}
225
- /* Inline to fullscreen is a layout morph, not a new screen: main widens over 400ms on the
226
- one curve and every dependent box follows it. Fullscreen is the detailed view, so the
227
- table loses its inline height cap. */
228
- /* The SVG is rendered at 600x320 and scaled by width, so an unbounded fullscreen column
229
- makes the chart's own axis type larger than the tile's heading. Hold a measure. */
230
- [data-mode=full] main{padding:28px 32px;max-width:900px}
231
- [data-mode=full] h1{font-size:var(--font-heading-xl-size,24px);line-height:var(--font-heading-xl-line-height,1.25)}
232
- [data-mode=full] .kpi{font-size:clamp(44px,7vw,72px)}
233
- [data-mode=full] #rows{max-height:none}
234
- /* Touch: the host gives vertical pan to the conversation, so a nested scroller is a trap. */
235
- @media(pointer:coarse){button,input{min-height:44px}summary{padding:12px 0}#rows{max-height:none;overflow:visible}}
236
- @media(max-width:480px){main{padding:14px}}
237
- /* Entrance. Content first, chrome 60ms later: 300+60 = 360ms, inside the 400ms budget.
238
- No stagger past two groups - a chat tile that cascades reads as lag, not luxury. */
239
- @keyframes rise{from{opacity:0;transform:translateY(6px)}}
240
- @keyframes land{from{opacity:0;transform:translateY(4px) scale(.995)}}
241
- header,#status,#plot{animation:rise var(--s) var(--e) both}
242
- #tip,#choices,footer,#range,#data{animation:rise var(--s) var(--e) 60ms both}
243
- .chart,.kpi{animation:land var(--s) var(--e) both}
244
- @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}
245
- </style></head><body><main id="tile"><header><div><h1 id="title">Analytics</h1><p id="description"></p></div><button id="expand" hidden>Expand</button></header>
246
- <p id="status" role="status">Loading chart\u2026</p><div id="plot" data-state="wait"></div><div id="tip"></div><div id="choices"></div>
247
- <footer><button id="refresh" hidden>Refresh</button><button id="next" hidden>Next page</button></footer>
248
- <details id="range" hidden><summary>Change the date range</summary><div class="dates"><label>From <input id="from" type="date"></label><label>To <input id="to" type="date"></label><button id="dates" type="button">Apply dates</button></div></details>
249
- <details id="data" hidden><summary id="count">Show the data behind this</summary><div id="rows" tabindex="0" role="region" aria-label="Chart data"></div></details></main><script>${TILE_SCRIPT}</script></body></html>`;
250
- }
251
-
252
- // src/apps/registry.ts
253
- var actions = {
254
- render_chart: "Render one authorized chart page as SVG with point metadata. Cursor pagination stays within the same guest scope.",
255
- refresh_widget: "Refresh a chart in the current guest scope. Revalidates access before returning data.",
256
- drill_down: "Explore a server-issued drill identifier within the current chart and guest scope.",
257
- change_date_range: "Render a chart for an ordered date range within the current guest scope."
258
- };
259
- function registerChartApps(server, client, backend = createChartBackend(client)) {
260
- for (const [name, description] of Object.entries(actions)) {
261
- const action = name;
262
- const tool = server.tool(name, description, {
263
- reference: referenceSchema,
264
- view: viewSchema.default({}),
265
- context: z.string().max(200).optional().describe("Chart interaction context")
266
- }, READ_ONLY, async ({ reference, view }) => {
267
- try {
268
- if (action === "drill_down" && !view.drillId || action === "change_date_range" && !view.dateRange) throw new Error("Missing view selector");
269
- const page = pageSchema.parse(await toolContext.run(
270
- { tool: name, category: "embedding", workflowIntent: "chart_app", inputMode: "app" },
271
- () => backend.execute(action, reference, view)
272
- ));
273
- if (page.svg && (!/^\s*<svg\b/i.test(page.svg) || /<\s*(?:script|foreignObject|iframe|image|animate\w*|set)\b|<!DOCTYPE|<!ENTITY|\bon\w+\s*=|@(?:import|keyframes)|\banimation\s*:|(?:href\s*=\s*["'](?!#)|url\s*\(\s*["']?(?!#))/i.test(page.svg))) {
274
- throw new Error("Unsafe SVG");
275
- }
276
- return chartResult(`${page.kind === "kpi" ? "KPI" : "Chart"} ready. ${page.rows.length} rows in this page.`, {
277
- ...page,
278
- reference,
279
- view
280
- });
281
- } catch {
282
- return { isError: true, content: [{
283
- type: "text",
284
- text: "Chart unavailable. Check dashboard access and the chart renderer integration, then retry."
285
- }] };
286
- }
287
- });
288
- tool.update({ _meta: { ui: { resourceUri: CHART_URI, visibility: ["app"] } } });
289
- }
290
- for (const [uri, kind] of [[CHART_URI, "chart"], [KPI_URI, "kpi"]]) {
291
- server.resource(`Databrain ${kind} tile`, uri, { mimeType: APP_MIME, description: `Interactive ${kind} using host theme and scoped server tools` }, async () => ({
292
- contents: [{ uri, mimeType: APP_MIME, text: tileHtml(kind), _meta: { ui: { prefersBorder: true } } }]
293
- }));
294
- }
295
- }
296
-
297
- // src/apps/server.ts
298
- function createChartAppServer(config, backend) {
299
- const client = new DatabrainClient(config);
300
- const server = new McpServer({ name: "databrain-chart-apps", version: MCP_SERVER_VERSION }, {
301
- instructions: "Use read-only chart previews to inspect analytics. Chart interactions inherit guest scope. Never request or expose credentials. Mutation tools retain their existing dry-run and confirmation requirements."
302
- });
303
- enableChartApps(server);
304
- registerAllTools(server, client);
305
- registerAllResources(server);
306
- registerAllPrompts(server);
307
- registerChartApps(server, client, backend);
308
- return server;
309
- }
310
-
311
- export {
312
- createChartAppServer
313
- };
314
- //# sourceMappingURL=chunk-SG7F7PRY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/apps/server.ts","../src/apps/registry.ts","../src/apps/backend.ts","../src/apps/tile.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { DatabrainClient } from '../client/databrain-client.js';\nimport type { Config } from '../utils/config.js';\nimport { registerAllTools } from '../tools/registry.js';\nimport { registerAllResources } from '../resources/registry.js';\nimport { registerAllPrompts } from '../prompts/registry.js';\nimport { MCP_SERVER_VERSION } from '../version.js';\nimport { enableChartApps } from './feature.js';\nimport { registerChartApps } from './registry.js';\nimport type { ChartBackend } from './backend.js';\n\n/** Reviewable composition seam; hosted owners must retain their principal-bound client/policy. */\nexport function createChartAppServer(config: Config, backend?: ChartBackend): McpServer {\n const client = new DatabrainClient(config);\n const server = new McpServer({ name: 'databrain-chart-apps', version: MCP_SERVER_VERSION }, {\n instructions: 'Use read-only chart previews to inspect analytics. Chart interactions inherit guest scope. ' +\n 'Never request or expose credentials. Mutation tools retain their existing dry-run and confirmation requirements.',\n });\n enableChartApps(server);\n registerAllTools(server, client);\n registerAllResources(server);\n registerAllPrompts(server);\n registerChartApps(server, client, backend);\n return server;\n}\n","import { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { DatabrainClient } from '../client/databrain-client.js';\nimport { READ_ONLY } from '../tools/annotations.js';\nimport { toolContext } from '../utils/tool-context.js';\nimport { createChartBackend, type ChartBackend, type ChartAction } from './backend.js';\nimport { APP_MIME, CHART_URI, KPI_URI, pageSchema, referenceSchema, viewSchema } from './contract.js';\nimport { chartResult } from './feature.js';\nimport { tileHtml } from './tile.js';\n\nconst actions: Record<ChartAction, string> = {\n render_chart: 'Render one authorized chart page as SVG with point metadata. Cursor pagination stays within the same guest scope.',\n refresh_widget: 'Refresh a chart in the current guest scope. Revalidates access before returning data.',\n drill_down: 'Explore a server-issued drill identifier within the current chart and guest scope.',\n change_date_range: 'Render a chart for an ordered date range within the current guest scope.',\n};\n\n/** Call after registerAllTools so existing registration policy/instrumentation remains active. */\nexport function registerChartApps(server: McpServer, client: DatabrainClient, backend: ChartBackend = createChartBackend(client)): void {\n for (const [name, description] of Object.entries(actions)) {\n const action = name as ChartAction;\n const tool = server.tool(name, description, {\n reference: referenceSchema, view: viewSchema.default({}),\n context: z.string().max(200).optional().describe('Chart interaction context'),\n }, READ_ONLY, async ({ reference, view }) => {\n try {\n if ((action === 'drill_down' && !view.drillId) || (action === 'change_date_range' && !view.dateRange)) throw new Error('Missing view selector');\n const page = pageSchema.parse(await toolContext.run({ tool: name, category: 'embedding', workflowIntent: 'chart_app', inputMode: 'app' },\n () => backend.execute(action, reference, view)));\n // SVG is rendered as an isolated image, never inserted into the HTML DOM.\n // Reject active/external/animated constructs as a further contract check.\n if (page.svg && (!/^\\s*<svg\\b/i.test(page.svg) ||\n /<\\s*(?:script|foreignObject|iframe|image|animate\\w*|set)\\b|<!DOCTYPE|<!ENTITY|\\bon\\w+\\s*=|@(?:import|keyframes)|\\banimation\\s*:|(?:href\\s*=\\s*[\"'](?!#)|url\\s*\\(\\s*[\"']?(?!#))/i.test(page.svg))) {\n throw new Error('Unsafe SVG');\n }\n return chartResult(`${page.kind === 'kpi' ? 'KPI' : 'Chart'} ready. ${page.rows.length} rows in this page.`, {\n ...page, reference, view,\n });\n } catch {\n return { isError: true, content: [{ type: 'text' as const,\n text: 'Chart unavailable. Check dashboard access and the chart renderer integration, then retry.' }] };\n }\n });\n tool.update({ _meta: { ui: { resourceUri: CHART_URI, visibility: ['app'] } } });\n }\n for (const [uri, kind] of [[CHART_URI, 'chart'], [KPI_URI, 'kpi']] as const) {\n server.resource(`Databrain ${kind} tile`, uri, { mimeType: APP_MIME, description: `Interactive ${kind} using host theme and scoped server tools` }, async () => ({\n contents: [{ uri, mimeType: APP_MIME, text: tileHtml(kind), _meta: { ui: { prefersBorder: true } } }],\n }));\n }\n}\n","import { DatabrainClient } from '../client/databrain-client.js';\nimport type { RequestOptions } from '../client/types.js';\nimport { createServiceBundle } from '../services/factory.js';\nimport { pageSchema, referenceSchema, viewSchema, type ChartPage, type ChartReference, type ChartView } from './contract.js';\n\nexport const RENDER_PATH = '/api/v2/dashboard/mcp-chart';\nexport type ChartAction = 'render_chart' | 'refresh_widget' | 'drill_down' | 'change_date_range';\nexport interface ChartBackend {\n execute(action: ChartAction, reference: ChartReference, view: ChartView): Promise<ChartPage>;\n}\n\nclass UncachedChartClient extends DatabrainClient {\n constructor(private readonly delegate: DatabrainClient) {\n super({ apiUrl: delegate.getApiUrl(), demoDomain: delegate.getDemoDomain() });\n }\n override request<T>(options: RequestOptions): Promise<T> {\n return this.delegate.request<T>({ ...options, cacheKey: undefined, cacheTtlMs: undefined });\n }\n}\n\n/** Proposed backend route; no local renderer, ambient service fallback, or UI credentials. */\nexport function createChartBackend(client: DatabrainClient): ChartBackend {\n // The general embed lookup caches for five minutes. Authorization must not.\n const services = createServiceBundle(new UncachedChartClient(client));\n return {\n async execute(action, rawReference, rawView) {\n const reference = referenceSchema.parse(rawReference);\n const view = viewSchema.parse(rawView);\n // Every page/refresh/drill re-reads the embed live, so a revoked tenant stops working at once.\n const app = await services.widgetService.resolveDataAppName(undefined, reference.embedId);\n if (!app.ok) throw new Error('Chart scope unavailable');\n const scope = await services.widgetService.ensureReadableDashboardScope({\n embedId: reference.embedId, clientId: reference.clientId, dataAppName: app.value });\n if (!scope.ok) throw new Error('Chart scope denied');\n const { token } = await services.guestTokenService.generateToken({\n clientId: reference.clientId, dataAppName: app.value, allowedEmbeds: [reference.embedId],\n permissions: { isDisableMetricCreation: true, isEnableManageMetrics: false,\n isEnableMetricUpdation: false, isEnableArchiveMetrics: false },\n });\n if (!token) throw new Error('Guest scope unavailable');\n const page = await client.request<unknown>({\n method: 'POST', path: RENDER_PATH, auth: 'none', token,\n body: { action, embedId: reference.embedId, widgetId: reference.widgetId, ...view,\n pageSize: 50, width: 600, height: 320, animation: false },\n skipDataUnwrap: true,\n });\n return pageSchema.parse(page);\n },\n };\n}\n","/** Deliberately no imports in the iframe. All requests go through the host bridge. */\nexport const TILE_SCRIPT = String.raw`(()=>{\nconst $=id=>document.getElementById(id),root=document.documentElement,pending=new Map();\nlet seq=0,origin='*',ready=false,closed=false,ref=null,view={},next=null,context={},busy=false,revision=0,rawSvg=null;\nfunction send(message){if(!closed)parent.postMessage({jsonrpc:'2.0',...message},origin)}\nfunction rpc(method,params){return new Promise((resolve,reject)=>{const id=++seq;\nconst timer=setTimeout(()=>{pending.delete(id);reject(Error('timeout'))},30000);\npending.set(id,{resolve,reject,timer});send({id,method,params})})}\nfunction status(text,bad){const s=$('status');s.textContent=text;s.toggleAttribute('data-error',!!bad);if(bad)$('plot').dataset.state='off'}\nfunction paint(){const img=$('chart-image');if(img&&rawSvg)img.src='data:image/svg+xml,'+encodeURIComponent(rawSvg.replace(/<\\/svg>\\s*$/i,'<style>text{fill:'+getComputedStyle(document.body).color+'!important}</style></svg>'))}\nfunction controls(){document.querySelectorAll('button,input,select').forEach(e=>{e.disabled=busy});\n$('refresh').hidden=!ref;$('next').hidden=!next;$('range').hidden=!ref;$('plot').toggleAttribute('data-busy',busy);\n$('expand').hidden=!context.availableDisplayModes?.includes('fullscreen');\nroot.toggleAttribute('data-deep',context.displayMode==='fullscreen'||$('expand').hidden)}\nfunction host(change){context={...context,...change};if(change.theme==='dark'||change.theme==='light')root.style.colorScheme=change.theme;\nconst vars=change.styles?.variables||{};for(const [key,value] of Object.entries(vars)){\nif(/^--(?:color-|font-|border-|shadow-)/.test(key)&&typeof value==='string'&&!/url\\s*\\(|@import/i.test(value))root.style.setProperty(key,value)}\nconst face=change.styles?.css?.fonts;if(typeof face==='string'&&face.length<4000&&!/@import|javascript:/i.test(face))$('hostfont').textContent=face;\nconst insets=change.safeAreaInsets;if(insets)for(const edge of ['top','right','bottom','left']){\nconst n=insets[edge];if(Number.isFinite(n))root.style.setProperty('--safe-'+edge,Math.max(0,Math.min(n,200))+'px')}\nroot.dataset.mode=context.displayMode==='fullscreen'?'full':'inline';\n$('expand').textContent=context.displayMode==='fullscreen'?'Back to conversation':'Expand';paint();controls()}\nfunction resize(){if(ready)send({method:'ui/notifications/size-changed',params:{width:document.body.scrollWidth,height:document.body.scrollHeight}})}\nfunction table(rows,columns){$('rows').replaceChildren();$('data').hidden=!rows?.length;if(!rows?.length)return;\n$('count').textContent=rows.length===1?'Show the 1 row behind this':'Show the '+rows.length+' rows behind this';\nconst t=document.createElement('table');\nconst header=document.createElement('tr');for(const name of columns){const th=document.createElement('th');th.scope='col';th.textContent=name;header.append(th)}\nconst head=document.createElement('thead');head.append(header);t.append(head);const body=document.createElement('tbody');\nfor(const row of rows.slice(0,50)){const tr=document.createElement('tr');for(const key of columns){const td=document.createElement('td');td.textContent=String(row[key]??'');tr.append(td)}body.append(tr)}t.append(body);$('rows').append(t)}\nasync function display(mode){try{const answer=await rpc('ui/request-display-mode',{mode});\nhost({displayMode:answer.mode||context.displayMode});if(root.dataset.mode==='full'&&!$('data').hidden)$('data').open=true;resize()}\ncatch{status('Expanded view is unavailable in this host.',1)}}\nfunction wait(){busy=true;if(!$('plot').firstChild)$('plot').dataset.state='wait';status('Loading chart…');controls()}\nasync function call(name,extra={}){if(!ready||!ref||busy)return;wait();const rev=++revision;\ntry{const result=await rpc('tools/call',{name,arguments:{reference:ref,view:{...view,...extra},context:'User is interacting with the chart tile.'}});\nif(rev===revision)render(result)}catch{if(rev===revision)status('Could not load the chart. Select Refresh to try again.',1)}finally{busy=false;controls()}}\nfunction render(result){busy=false;controls();\nif(result?.isError){status('Chart unavailable. Check your access to this dashboard, then select Refresh.',1);return}\nconst p=result?.structuredContent;if(!p||typeof p!=='object'){status('No chart data came back for this result.',1);return}\nrevision++;rawSvg=null;$('plot').replaceChildren();$('plot').dataset.state='ready';$('choices').replaceChildren();$('tip').textContent='';delete $('tip').dataset.value;\nref=p.reference||null;view=p.view||{};next=p.nextCursor||null;\n$('title').textContent=p.title||'Analytics';$('description').textContent=p.description||'';\nif(p.kind==='dashboard'){$('plot').dataset.state='off';\nfor(const item of p.widgets||[]){const b=document.createElement('button');b.textContent=item.name||'Untitled widget';b.onclick=()=>{ref=item.reference;view={};call('render_chart')};$('choices').append(b)}\nstatus(p.widgets?.length?'Choose a chart to explore.':'This dashboard has no charts yet.');\n}else if(p.kind==='kpi'){\nconst number=document.createElement('p');number.className='kpi';number.textContent=String(p.value??'—');$('plot').append(number);status('');\n}else if(p.svg){\nconst box=document.createElement('div');box.className='chart';box.style.aspectRatio=p.width+'/'+p.height;\nconst img=document.createElement('img');img.id='chart-image';rawSvg=p.svg;img.alt=p.title||'Chart';img.onerror=()=>{status('Chart image unavailable. The data is in the table below.',1);$('data').open=$('data').toggleAttribute('data-only',true)};box.append(img);\nfor(const point of p.points||[]){const b=document.createElement('button');b.className='point';b.setAttribute('aria-label',point.label+': '+point.value);b.setAttribute('aria-pressed','false');\nb.style.left=100*point.x/p.width+'%';b.style.top=100*point.y/p.height+'%';b.style.width=100*point.width/p.width+'%';b.style.height=100*point.height/p.height+'%';\nconst hover=()=>{$('tip').textContent=point.label+': '+point.value;$('tip').dataset.value='1'};b.onmouseenter=hover;b.onfocus=hover;\nb.onclick=()=>{box.querySelectorAll('.point').forEach(e=>e.setAttribute('aria-pressed','false'));b.setAttribute('aria-pressed','true');hover();\n$('choices').replaceChildren();if(point.drillId){const drill=document.createElement('button');drill.className='primary';drill.textContent='Explore selected data';drill.onclick=()=>call('drill_down',{drillId:point.drillId,cursor:undefined});$('choices').append(drill)}};box.append(b)}$('plot').append(box);\nstatus(p.rows?.length?'':'This chart has no data for the current view.');if(p.points?.length)$('tip').textContent='Select part of the chart to read its value.';\n}else{$('plot').dataset.state='off';status(p.rows?.length?'Chart preview is unavailable. The data is in the table below.':'No data for this view.',!p.rows?.length)}\npaint();table(p.rows||[],p.columns||Object.keys(p.rows?.[0]||{}));\nconst only=!p.svg&&p.value===undefined;$('data').open=only;$('data').toggleAttribute('data-only',only);controls();resize()}\n$('refresh').onclick=()=>call('refresh_widget',{cursor:undefined});$('next').onclick=()=>call('render_chart',{cursor:next});\n$('expand').onclick=()=>display(context.displayMode==='fullscreen'?'inline':'fullscreen');\n$('dates').onclick=()=>{const from=$('from').value,to=$('to').value;if(!from||!to||from>to){status('Choose a start date on or before the end date.',1);return}call('change_date_range',{dateRange:{from,to},cursor:undefined,drillId:undefined})};\nfunction receive(event){if(event.source!==parent||closed)return;const m=event.data;\nif(!m||Array.isArray(m)||m.jsonrpc!=='2.0'||(origin!=='*'&&event.origin!==origin))return;\nif(!m.method&&pending.has(m.id)&&('result'in m||'error'in m)){if(origin==='*'&&event.origin!=='null')origin=event.origin;\nconst p=pending.get(m.id);pending.delete(m.id);clearTimeout(p.timer);m.error?p.reject(Error('host error')):p.resolve(m.result);return}\nif(m.method==='ping'&&m.id!==undefined){send({id:m.id,result:{}});return}\nif(m.method==='ui/resource-teardown'){send({id:m.id,result:{}});closed=true;revision++;for(const p of pending.values()){clearTimeout(p.timer);p.reject(Error('closed'))}pending.clear();observer.disconnect();removeEventListener('message',receive);return}\nif(!ready||m.id!==undefined)return;\nif(m.method==='ui/notifications/tool-result'){render(m.params)}\nelse if(m.method==='ui/notifications/tool-input'){wait()}\nelse if(m.method==='ui/notifications/host-context-changed'){host(m.params||{});resize()}\nelse if(m.method==='ui/notifications/tool-cancelled'){revision++;busy=false;$('plot').dataset.state='off';status('Chart request cancelled.');controls()}}\naddEventListener('message',receive);const observer=new ResizeObserver(resize);observer.observe(document.body);controls();\nrpc('ui/initialize',{protocolVersion:'2026-01-26',appInfo:{name:'Databrain chart tile',version:'1.0.0'},appCapabilities:{availableDisplayModes:['inline','fullscreen']}})\n.then(r=>{if(r.protocolVersion!=='2026-01-26')throw Error('version');host(r.hostContext||{});ready=true;send({method:'ui/notifications/initialized'});resize()})\n.catch(()=>status('This chart needs a host that supports MCP Apps.',1));\n})();`;\n\nexport function tileHtml(kind: 'chart' | 'kpi' = 'chart'): string {\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'\">\n<title>Databrain ${kind} tile</title><style id=\"hostfont\"></style><style>\n/* Host tokens are the Claude MCP Apps style-variable names. Every one carries a fallback:\n hosts may ship any subset, so nothing here may depend on a token existing. */\n:root{color-scheme:light dark;\n--dbn-bg:var(--color-background-primary,Canvas);--dbn-text:var(--color-text-primary,CanvasText);\n--dbn-mute:var(--color-text-secondary,GrayText);--dbn-faint:var(--color-text-tertiary,GrayText);\n--dbn-edge:var(--color-border-secondary,ButtonBorder);--dbn-line:var(--color-border-tertiary,var(--dbn-edge));\n--dbn-accent:var(--color-text-info,LinkText);--dbn-ring:var(--color-ring-primary,var(--dbn-accent));\n--dbn-bad:var(--color-text-danger,var(--dbn-text));--dbn-bad-edge:var(--color-border-danger,currentColor);\n--dbn-quiet:color-mix(in srgb,currentColor 6%,transparent);\n--bw:var(--border-width-regular,1px);--r-s:var(--border-radius-sm,6px);--r-m:var(--border-radius-md,8px);--r-l:var(--border-radius-lg,10px);\n--med:var(--font-weight-medium,500);--semi:var(--font-weight-semibold,600);\n/* One curve. Quick / standard / display-mode. Corporate: no overshoot. */\n--e:cubic-bezier(.2,0,0,1);--q:120ms;--s:300ms;--l:400ms}\n*{box-sizing:border-box}\nbody{margin:0;padding:var(--safe-top,0px) var(--safe-right,0px) var(--safe-bottom,0px) var(--safe-left,0px);background:var(--dbn-bg);color:var(--dbn-text);\nfont:var(--font-text-sm-size,14px)/var(--font-text-sm-line-height,1.4) var(--font-sans,system-ui)}\nmain{padding:20px;max-width:1200px;margin:auto;transition:padding var(--l) var(--e)}\nheader{display:flex;align-items:start;justify-content:space-between;gap:12px}header>div{min-width:0}\nh1{font-size:var(--font-heading-md-size,18px);line-height:var(--font-heading-md-line-height,1.4);margin:0 0 6px;font-weight:var(--semi);letter-spacing:-.01em;overflow-wrap:anywhere;transition:font-size var(--l) var(--e)}\np{margin:6px 0;color:var(--dbn-mute);overflow-wrap:anywhere}#expand{flex:none}\nbutton,input{font:inherit;color:inherit;background:var(--dbn-bg);border:var(--bw) solid var(--dbn-edge);border-radius:var(--r-s);padding:7px 10px}\nbutton{cursor:pointer;transition:background-color var(--q) var(--e),border-color var(--q) var(--e)}\ninput{max-width:160px;min-width:0}button:hover:not(:disabled){background:var(--dbn-quiet)}button:disabled{color:var(--dbn-faint);cursor:default}\nbutton:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--dbn-ring);outline-offset:2px}\n#choices button.primary{border-color:var(--dbn-accent);font-weight:var(--med)}\n#status:empty{margin:0}\n#status[data-error]{color:var(--dbn-bad);font-weight:var(--med);border-left:2px solid var(--dbn-bad-edge);background:var(--color-background-danger,transparent);border-radius:0 var(--r-s) var(--r-s) 0;padding:8px 10px;margin:8px 0}\n/* Reserved plot. The skeleton is a static bar silhouette matching the 15:8 backend render:\n Claude's guidance asks for a skeleton that matches the final layout, and bans nothing here,\n but shimmer is banned by our own motion budget - so this paints once and never repaints. */\n#plot{position:relative;transition:opacity var(--q) var(--e)}#plot[data-busy]{opacity:.55}\n#plot[data-state=wait]{aspect-ratio:15/8}\n#plot[data-state=wait]::before,#plot[data-state=ready]::before{content:'';position:absolute;pointer-events:none;inset:16% 6% 13%;\nborder-bottom:var(--bw) solid var(--dbn-line);transition:opacity var(--s) var(--e);\nbackground:linear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 0 100%/11% 44% no-repeat,\nlinear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 22% 100%/11% 71% no-repeat,\nlinear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 44% 100%/11% 57% no-repeat,\nlinear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 66% 100%/11% 86% no-repeat,\nlinear-gradient(var(--dbn-quiet),var(--dbn-quiet)) 88% 100%/11% 33% no-repeat}\n#plot[data-state=ready]::before{opacity:0}\n.chart{position:relative;width:100%;margin:12px 0}.chart img{width:100%;height:100%;display:block}\n.point{position:absolute;padding:0;border:0;background:transparent;border-radius:var(--border-radius-xs,4px);\noutline:2px solid transparent;outline-offset:1px;transition:background-color var(--q) var(--e),outline-color var(--q) var(--e)}\n.point:hover{background:color-mix(in srgb,currentColor 12%,transparent)}\n.point[aria-pressed=true]{outline-color:var(--dbn-accent);background:color-mix(in srgb,var(--dbn-accent) 18%,transparent)}\n.kpi{font-size:clamp(34px,10vw,44px);line-height:1.1;font-weight:var(--semi);letter-spacing:-.025em;font-variant-numeric:tabular-nums;color:var(--dbn-text);margin:14px 0 6px;transition:font-size var(--l) var(--e)}\n#tip{color:var(--dbn-mute);font-size:var(--font-text-xs-size,12px);overflow-wrap:anywhere;min-height:1.4em}\n#tip[data-value]{color:var(--dbn-text);font-weight:var(--med);font-variant-numeric:tabular-nums}\n#choices,footer,.dates{display:flex;gap:8px;flex-wrap:wrap;align-items:center}#choices{margin:10px 0 0}footer{margin-top:12px}.dates{margin:8px 0 2px}\nlabel{display:flex;align-items:center;gap:6px;color:var(--dbn-mute)}\n#range{margin-top:10px}#data{margin-top:2px}#data[hidden],#range[hidden]{display:none}\nhtml:not([data-deep]) #range,html:not([data-deep]) #data:not([data-only]){display:none}\nsummary{cursor:pointer;color:var(--dbn-mute);font-size:var(--font-text-xs-size,12px);padding:5px 0;width:fit-content;transition:color var(--q) var(--e)}summary:hover{color:var(--dbn-text)}\n#rows{overflow:auto;max-height:260px;border-radius:var(--r-s)}\ntable{border-collapse:collapse;width:100%;font-size:var(--font-text-xs-size,12px)}\nth,td{text-align:left;padding:8px;border-bottom:var(--bw) solid var(--dbn-line);overflow-wrap:anywhere}\ntd:last-child{font-variant-numeric:tabular-nums}th{font-weight:var(--semi);position:sticky;top:0;background:var(--dbn-bg);color:var(--dbn-mute)}\n/* Inline to fullscreen is a layout morph, not a new screen: main widens over 400ms on the\n one curve and every dependent box follows it. Fullscreen is the detailed view, so the\n table loses its inline height cap. */\n/* The SVG is rendered at 600x320 and scaled by width, so an unbounded fullscreen column\n makes the chart's own axis type larger than the tile's heading. Hold a measure. */\n[data-mode=full] main{padding:28px 32px;max-width:900px}\n[data-mode=full] h1{font-size:var(--font-heading-xl-size,24px);line-height:var(--font-heading-xl-line-height,1.25)}\n[data-mode=full] .kpi{font-size:clamp(44px,7vw,72px)}\n[data-mode=full] #rows{max-height:none}\n/* Touch: the host gives vertical pan to the conversation, so a nested scroller is a trap. */\n@media(pointer:coarse){button,input{min-height:44px}summary{padding:12px 0}#rows{max-height:none;overflow:visible}}\n@media(max-width:480px){main{padding:14px}}\n/* Entrance. Content first, chrome 60ms later: 300+60 = 360ms, inside the 400ms budget.\n No stagger past two groups - a chat tile that cascades reads as lag, not luxury. */\n@keyframes rise{from{opacity:0;transform:translateY(6px)}}\n@keyframes land{from{opacity:0;transform:translateY(4px) scale(.995)}}\nheader,#status,#plot{animation:rise var(--s) var(--e) both}\n#tip,#choices,footer,#range,#data{animation:rise var(--s) var(--e) 60ms both}\n.chart,.kpi{animation:land var(--s) var(--e) both}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n</style></head><body><main id=\"tile\"><header><div><h1 id=\"title\">Analytics</h1><p id=\"description\"></p></div><button id=\"expand\" hidden>Expand</button></header>\n<p id=\"status\" role=\"status\">Loading chart…</p><div id=\"plot\" data-state=\"wait\"></div><div id=\"tip\"></div><div id=\"choices\"></div>\n<footer><button id=\"refresh\" hidden>Refresh</button><button id=\"next\" hidden>Next page</button></footer>\n<details id=\"range\" hidden><summary>Change the date range</summary><div class=\"dates\"><label>From <input id=\"from\" type=\"date\"></label><label>To <input id=\"to\" type=\"date\"></label><button id=\"dates\" type=\"button\">Apply dates</button></div></details>\n<details id=\"data\" hidden><summary id=\"count\">Show the data behind this</summary><div id=\"rows\" tabindex=\"0\" role=\"region\" aria-label=\"Chart data\"></div></details></main><script>${TILE_SCRIPT}</script></body></html>`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;;;ACA1B,SAAS,SAAS;;;ACKX,IAAM,cAAc;AAM3B,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EAChD,YAA6B,UAA2B;AACtD,UAAM,EAAE,QAAQ,SAAS,UAAU,GAAG,YAAY,SAAS,cAAc,EAAE,CAAC;AADjD;AAAA,EAE7B;AAAA,EACS,QAAW,SAAqC;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