@holistics/anfra-sdk 0.13.5 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/app.d.ts +4 -3
- package/dist/app.js +17 -7
- package/dist/{bootstrap-BbsNvZ8s.d.ts → bootstrap-MhTSkiA1.d.ts} +96 -3
- package/dist/build.d.ts +2 -0
- package/dist/chunk-7IHICYVH.js +10 -0
- package/dist/chunk-CYZQ7ZTJ.js +237 -0
- package/dist/chunk-DITKCHFQ.js +166 -0
- package/dist/chunk-F6MRA7J4.js +65 -0
- package/dist/chunk-GBXK7F2V.js +431 -0
- package/dist/chunk-GOUDXWG4.js +750 -0
- package/dist/chunk-GV7SVWEK.js +84 -0
- package/dist/chunk-H52PO7MP.js +105 -0
- package/dist/chunk-HI3ZAXJK.js +8 -0
- package/dist/{chunk-KI5CAVAR.js → chunk-HZEECB6R.js} +477 -25
- package/dist/chunk-K633QHGO.js +51 -0
- package/dist/chunk-KFD6CHLI.js +38 -0
- package/dist/{chunk-OJ5WIKWE.js → chunk-NOFPRSSI.js} +1 -1
- package/dist/{chunk-ADWBOQW2.js → chunk-S6XLP6U4.js} +31 -1
- package/dist/{chunk-TQ7S5DRE.js → chunk-WI5VJ2Z6.js} +1 -1
- package/dist/common.d.ts +1 -1
- package/dist/common.js +14 -4
- package/dist/data-UCCW2VWH.js +233 -0
- package/dist/declaration-GVDOGQY6.js +218 -0
- package/dist/host.d.ts +42 -4
- package/dist/host.js +412 -9
- package/dist/menu-CdGVKc4_.d.ts +151 -0
- package/dist/overview-3DNXEQNY.js +358 -0
- package/dist/plugin-BmIDirTx.d.ts +303 -0
- package/dist/plugins.d.ts +6 -8
- package/dist/plugins.js +98 -69
- package/dist/queries-2OHKMTPC.js +661 -0
- package/dist/structure-WRDUXHD4.js +256 -0
- package/dist/tab-HMQOITVM.js +932 -0
- package/dist/testing.js +4 -4
- package/package.json +1 -1
- package/dist/bridge-WC7GliCH.d.ts +0 -73
- package/dist/chunk-33B2D4U5.js +0 -6
- package/dist/plugin-056-SKwd.d.ts +0 -132
- /package/dist/{chunk-52LXBYQM.js → chunk-UUKXJSE4.js} +0 -0
package/dist/host.js
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
checkTarget
|
|
3
|
+
} from "./chunk-KFD6CHLI.js";
|
|
1
4
|
import {
|
|
2
5
|
checkPlugin,
|
|
3
6
|
definePlugin
|
|
4
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-WI5VJ2Z6.js";
|
|
5
8
|
import {
|
|
6
|
-
createEndpoint
|
|
7
|
-
|
|
9
|
+
createEndpoint,
|
|
10
|
+
eventShortcut,
|
|
11
|
+
isTyping,
|
|
12
|
+
normalizeShortcut
|
|
13
|
+
} from "./chunk-S6XLP6U4.js";
|
|
8
14
|
import {
|
|
9
|
-
PROVISION_ELEMENT_ID
|
|
10
|
-
|
|
15
|
+
PROVISION_ELEMENT_ID,
|
|
16
|
+
applyTheme,
|
|
17
|
+
resolveTheme
|
|
18
|
+
} from "./chunk-F6MRA7J4.js";
|
|
11
19
|
import {
|
|
12
20
|
PermissionError,
|
|
13
21
|
TransportError,
|
|
@@ -16,12 +24,18 @@ import {
|
|
|
16
24
|
import "./chunk-PKBMQBKP.js";
|
|
17
25
|
|
|
18
26
|
// anfra-sdk:anfra-sdk:frame-script
|
|
19
|
-
var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var N=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(t,n,e)=>n in t?N(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>N(t,"name",{value:n,configurable:!0});var ft=(t,n)=>{for(var e in n)N(t,e,{get:n[e],enumerable:!0})},mt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ct(n))!pt.call(t,i)&&i!==e&&N(t,i,{get:()=>n[i],enumerable:!(r=dt(n,i))||r.enumerable});return t};var ht=t=>mt(N({},"__esModule",{value:!0}),t);var c=(t,n,e)=>ut(t,typeof n!="symbol"?n+"":n,e);var rn={};ft(rn,{bootstrap:()=>at});var Se="anfra-provision";var U=class U extends Error{constructor(e,r){super(e);c(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};o(U,"DataAppError");var S=U,H=class H extends S{};o(H,"ValidationError");var u=H,Y=class Y extends S{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(Y,"QueryError");var D=Y,W=class W extends S{};o(W,"PermissionError");var R=W,X=class X extends S{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(X,"TransportError");var C=X;function Ce(){let t=new Error("Aborted");return t.name="AbortError",t}o(Ce,"abortError");function gt(t){return t?.name==="AbortError"}o(gt,"isAbortError");var yt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function bt(t){let n=t;return n instanceof Error&&yt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}o(bt,"toBridgeError");function wt(t){switch(t?.name){case"PermissionError":return new R(t.message);case"TransportError":return new C(t.message);case"ValidationError":return new u(t.message);default:return new D(t?.message||"The call failed.")}}o(wt,"fromBridgeError");function Ae(t,n){let e=new Map,r=new Map,i=1,s=o((l,a,d)=>{let p=new AbortController;r.set(l,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(g=>{p.signal.aborted||t({type:"anfra:result",id:l,ok:!0,result:g})}).catch(g=>{p.signal.aborted||gt(g)||t({type:"anfra:result",id:l,ok:!1,error:bt(g)})}).finally(()=>{r.get(l)===p&&r.delete(l)})},"answer");return{call(l,a,d){return new Promise((p,g)=>{if(d?.aborted){g(Ce());return}let x=i++;e.set(x,{resolve:p,reject:g}),d?.addEventListener("abort",()=>{e.delete(x)&&(t({type:"anfra:cancel",id:x}),g(Ce()))},{once:!0}),t({type:"anfra:call",id:x,name:l,request:a})})},emit(l,a){t({type:"anfra:event",name:l,payload:a})},receive(l){switch(l?.type){case"anfra:call":return s(l.id,l.name,l.request),!0;case"anfra:result":{let a=e.get(l.id);return a&&(e.delete(l.id),l.ok?a.resolve(l.result):a.reject(wt(l.error))),!0}case"anfra:cancel":return r.get(l.id)?.abort(),r.delete(l.id),!0;case"anfra:event":return n.event(l.name,l.payload),!0;default:return!1}},close(l){r.forEach(a=>a.abort()),r.clear(),e.forEach(({reject:a})=>a(l)),e.clear()}}}o(Ae,"createEndpoint");var Z=class Z{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};o(Z,"Observable");var $=Z;var De=["year","quarter","month","week","day","hour","minute"];function xt(t,n){if(!De.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${De.join(", ")}.`,t)}o(xt,"assertGrain");function Re(t,n){return n?(xt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(Re,"drillCondition");function kt(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}o(kt,"inferType");function Et(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(Et,"sameCondition");var ee=class ee extends ${constructor(e,r,i){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=e,this.app=r,this.initial=i,this.pending=i}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!Et(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(ee,"Control");var O=ee,te=class te extends O{constructor(e,r,i,s,l){super(e,r,i.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=i,this.backend=l,i.field){if(!s)throw new u(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=s.resolve(i.field,e),this.datasetName=s.descriptor.name,this.type=i.type??kt(this.resolved.type)}else{if(!i.type)throw new u(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=i.type}this.assertValues(this.condition.values??[]),this.assertValues(i.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(i=>typeof i=="number");if(r!==void 0)throw new u(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let i=this.resolved?.modelName;if(!this.resolved||!i||!this.backend||!this.datasetName)return this.options;let s=await this.backend.fieldSuggestions({dataset:this.datasetName,model:i,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...s??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};o(te,"Filter");var P=te,ne=class ne extends O{constructor(e,r,i={}){super(e,r,Re(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Re(this.name,e))}toJSON(){return this.declaration}};o(ne,"DateDrillControl");var z=ne;var v={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},_e=`[${v.container}],[${v.block}],[${v.query}],[${v.control}]`;function $e(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o($e,"parseRef");var Oe=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Te(t,n,e,r){let i=n==="query"?v.query:v.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>Oe(s.getAttribute(i)).some(l=>{let a=$e(l);return a?.app===e&&a.name===r}))}o(Te,"markersFor");var vt=o((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function Fe(t,n){var x;let e=[],r=new Map,i=new Map,s=new Map,l=new Map,a={container:new Set,block:new Set},d={},p=o((h,E,m)=>{let y=h?s.get(h).children:e,f=h?`${s.get(h).key}.`:"",b={...E,key:`${f}${y.length}`,children:[]};return y.push(b),r.set(b.key,m),i.set(m,[...i.get(m)??[],b.key]),b},"place");for(let h of t.querySelectorAll(_e)){let E=h.parentElement?.closest(_e)??null,m=h.getAttribute(v.container),y=h.getAttribute(v.block),f=h.getAttribute(v.label)??void 0,b=E&&(l.get(E)==="block"?E:E.closest(`[${v.block}]`)),_;if(m!==null||y!==null){let k=m!==null?"container":"block",A=(m??y??"").trim(),w=[];m!==null&&y!==null&&w.push("This element is marked as a container and as a block. It counts as a container."),A?a[k].has(A)?w.push(`Another ${k} already has the id "${A}".`):a[k].add(A):w.push(`This ${k} has no id.`),b&&w.push(`A block can\'t hold a ${k}. This one is inside the block "${b.getAttribute(v.block)}".`),_=p(E,{kind:k,id:A,...f!==void 0?{label:f}:{},problems:w},h),s.set(h,_),l.set(h,k)}let M=_?h:E;for(let k of["query","control"])for(let A of Oe(h.getAttribute(k==="query"?v.query:v.control))){let w=$e(A),L=[];if(w?vt(n,k,w)||L.push(n[w.app]?`No ${k} is called "${w.name}" in app ${w.app}.`:`The page has no app ${w.app}.`):L.push(`Can\'t read "${A}". Write the ${k}\'s name, or app/name when the page has several apps.`),p(M,{kind:k,name:w?.name??A,app:w?.app??0,problems:L},h),w&&!L.length){let lt=`${w.app}/${w.name}`,Ee=d[x=`${k}:${lt}`]??(d[x]={elements:new Set,blocks:new Set});Ee.elements.add(h);let ve=_?.kind==="block"?_.id:b?.getAttribute(v.block);ve&&Ee.blocks.add(ve)}}}let g=Object.fromEntries(Object.entries(d).map(([h,E])=>[h,{markers:E.elements.size,blocks:[...E.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:i}}o(Fe,"buildStructure");var Me="data-anfra-layer",St="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function Ct(t){let n=t.querySelector(`[${Me}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");return e.setAttribute(Me,""),e.setAttribute("style",St),(t.body??t.documentElement).appendChild(e),e}o(Ct,"layerOf");function Q(t,n){let e=Ct(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let i=t.createElement("div");return i.setAttribute("data-part",n),e.appendChild(i),i.attachShadow({mode:"open"})}o(Q,"layerRoot");var Ne="anfra-overlay",At=1500,Dt="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Rt="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",_t={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ie=class ie{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",o(()=>this.draw(),"reposition"));let e=Q(n,"anfra"),r=e.getElementById(Ne);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Ne,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||Q(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=At){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Dt}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let i=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),l=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Rt}left:${l}px;top:${Math.min(s,i-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",_t[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(ie,"Overlay");var re=ie,Qe=new WeakMap;function V(t){let n=Qe.get(t);return n||(n=new re(t),Qe.set(t,n)),n}o(V,"overlayFor");function Ie(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Ie,"scrollTo");function oe(t,n,e,r,i){if(r in n||t.has(r))throw new u(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,i)}o(oe,"addExtension");function j(t,n){return n?.forEach((e,r)=>{let i=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return i||(s=e(t),i=!0),s}})}),t}o(j,"applyExtensions");var $t="anfra.body",se="__anfraBodyExports",Ot={DataAppError:S,ValidationError:u,QueryError:D,PermissionError:R,TransportError:C};function Tt(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(se)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let i=e[se];if(delete e[se],!i)throw new u("The host sent a plugin body that did not run.");return i.default??i}o(Tt,"runBody");function Be(t,n,e){let{window:r,sdk:i,endpoint:s}=n,l;return{plugin:t,window:r,sdk:i,errors:Ot,get overlay(){return V(r.document)},structure:o(()=>Fe(r.document,i.apps),"structure"),call:o((a,d,p)=>s.call(a,d??null,p),"call"),emit:o((a,d)=>s.emit(`${t}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${t}.${a}`,d)},on(a,d){let p=`${t}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),i.apps.forEach(d=>a(d))},provide(a){if(t in i)throw new u(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(i,t,{value:a,enumerable:!0})},provideOnQuery:o(a=>oe(i.extensions.query,e.Query.prototype,"query",t,a),"provideOnQuery"),provideOnControl:o(a=>oe(i.extensions.control,e.Control.prototype,"control",t,a),"provideOnControl"),layer:o(()=>Q(r.document,t),"layer"),body(){return l??(l=s.call($t,{plugin:t}).then(a=>Tt(r,a)).catch(a=>{throw l=void 0,a})),l}}}o(Be,"createKernel");var ae=class ae extends ${constructor(e,r,i){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!i.aql?.trim())throw new u(`Query \'${e}\' declares no AQL.`,e);let{pageSize:s}=i;if(s!==void 0&&!(Number.isInteger(s)&&s>=1))throw new u(`Query \'${e}\' declares pageSize ${s}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=i,this.dataset=r.datasetIndex(i.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this._result.meta.hasMore??this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,i)=>r.field.localeCompare(i.field)||JSON.stringify(r).localeCompare(JSON.stringify(i)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new u(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let i=o(l=>JSON.stringify(e.fields.map(a=>l[a]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(l=>s.has(i(l)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,i){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,i&&this._result){let s=[...this._result.rows,...e.rows];this._result={...e,rows:s,meta:{...e.meta,numRows:s.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};o(ae,"Query");var T=ae;var le=class le{constructor(n,e,r,i){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=i}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};o(le,"Mapping");var J=le,de=class de{constructor(n,e){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};o(de,"CrossFilter");var q=de;var ce=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Ft(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,l)=>l);for(let s=1;s<e;s++){let l=[s];for(let a=1;a<r;a++)l[a]=Math.min(i[a]+1,l[a-1]+1,i[a-1]+(t[s-1]===n[a-1]?0:1));i=l}return i[r-1]}o(Ft,"editDistance");function Mt(t,n){let e,r=1/0;n.forEach(s=>{let l=Ft(t.toLowerCase(),s.toLowerCase());l<r&&(r=l,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(Mt,"suggest");function F(t,n,e){let r=Mt(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(F,"withSuggestion");var pe=class pe{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let i=String(e.name);this.fields.set(`${i}.${r.name}`,{modelName:i,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new u(F(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(pe,"DatasetIndex");var G=pe;function Le(t,n,e){let r=t[n];if(r)return r;throw new u(F(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Le,"resolveDataset");function Pe(t,n){if(!ce.includes(t))throw new u(F(`Invalid filter aggregation \'${t}\'.`,t,[...ce]),n)}o(Pe,"assertValidFilterAggregation");function ze(t,n,e){if(!n)throw new u(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new u(`\'${n}\' is already declared in this app.`,n)}o(ze,"assertUniqueName");function Nt(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}o(Nt,"toFilter");function Qt(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}o(Qt,"toDateDrill");function It(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let l={};return e.forEach((a,d)=>{l[a.name]=s[d]}),l}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(It,"toResult");function Ve(t,n,e,r){let i=n.map(d=>Nt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>Qt(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...l],conditions:a,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ve,"buildQuery");function Bt(t,n,e,r){return{...Ve(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(Bt,"buildRequest");function Lt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(Lt,"defaultExportFilename");function je(t,n,e,r,i){let s=i.format??"csv",l=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ve(t,n,e,r),format:s,...l?{formatOptions:l}:{},filename:i.filename?.trim()||Lt(t,r.title)}}o(je,"buildExportRequest");async function ue(t,n,e,r,i){let s=Bt(t,n,e,r),l=await r.backend.submitQuery(s,i);return It(t,l)}o(ue,"runQuery");function Pt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return jt(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}o(Pt,"literal");function Je(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${Pt(n,e)}`}o(Je,"equals");var zt=new Set(["NaN","Infinity","-Infinity"]),Vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function jt(t){let n=Vt.exec(t);if(!n)throw zt.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,i="",s]=n;if(s===void 0)return t;let l=r+i,a=r.length+Number(s),d;return a<=0?d=`0.${"0".repeat(-a)}${l}`:a>=l.length?d=l+"0".repeat(a-l.length):d=`${l.slice(0,a)}.${l.slice(a)}`,e+d.replace(/^0+(?=\\d)/,"")}o(jt,"numberLiteral");function qe(t,n,e){return`${t} matches @(${n} until ${e})`}o(qe,"dateRange");function Ge(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}o(Ge,"combine");var Ke=o(t=>Ge("and",t),"and"),Ue=o(t=>Ge("or",t),"or");var Jt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,qt={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function He(t){if(typeof t!="string")return;let n=Jt.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}o(He,"parseStamp");function I(t,n){let e=new Date(t),r=o(s=>String(s).padStart(2,"0"),"pad"),i=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${i} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:i}o(I,"format");function Ye(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(Ye,"toMs");function fe(t){let n=He(t);if(n)return I(Ye(n),n.hasTime)}o(fe,"normalise");function me(t,n){let e=He(t);if(!e)return;let{year:r,month:i,day:s,hour:l,minute:a,second:d,hasTime:p}=e;return I(n==="year"?Date.UTC(r+1,i,s,l,a,d):n==="quarter"?Date.UTC(r,i+3,s,l,a,d):n==="month"?Date.UTC(r,i+1,s,l,a,d):Ye(e)+qt[n],p)}o(me,"addGrain");function We(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(We,"grainOf");function Gt(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}o(Gt,"distinct");function Kt(t,n){let e=t.map(fe);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(me(r[i-1],n)!==r[i])return!1;return!0}o(Kt,"isContiguous");function Ut(t,n,e){let r=n.map(fe);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],l=me(i[i.length-1],e);if(!l)return;let a=Kt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${l}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}o(Ut,"dateRange");function Ht(t,n,e){let r=e.filter(a=>a!=null),i=Gt(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,l=We(n);if(l){let a=Ut(t,i,l);if(a)return{...a,lossy:a.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o(Ht,"deriveOne");function Xe(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(Xe,"fieldReferenceOf");function Yt(t,n,e,r){try{let i=e.map(s=>Ke(n.map(l=>{let a=t.get(l),d=Xe(a),p=s[l]??null,g=We(r[d]);if(g&&typeof p=="string"){let x=fe(p),h=me(p,g);if(x&&h)return qe(d,x,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Je(d,p,a.semantic_type)})));return Ue(i)}catch{return}}o(Yt,"selectionExpression");function Ze(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(f=>[f.name,f]));e?.forEach(f=>{let b=s.get(f);if(b){if(b.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${f}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(b.isMeasure)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${f}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(F(`Query \'${t.name}\' has no column \'${f}\' in its last result.`,f,[...s.keys()]),t.name)});let l=i.filter(f=>!f.isMeasure),a=l.filter(f=>!f.adhoc).map(f=>f.name),d=e?[...e]:a;if(!n.length||!d.length)return;let p=[],g=1,x=!e&&a.length!==l.length,h=!1;d.forEach(f=>{let b=s.get(f),_=Xe(b),M=Ht(_,r[_],n.map(k=>k[f]));p.push(M.condition),g*=M.admits,h=h||M.lossy});let E=new Set(n.map(f=>JSON.stringify(d.map(b=>f[b]??null))));g>E.size&&(h=!0);let m=p.sort((f,b)=>f.field.localeCompare(b.field)),y={source:t.name,rows:[...n],fields:d};if(h){let f=Yt(s,d,n,r);if(f)return{...y,conditions:[],expression:f,lossy:x}}return{...y,conditions:m,lossy:x||h}}o(Ze,"deriveSelection");var he=Object.freeze([]);function ge(t){return t instanceof Error&&t.name==="AbortError"}o(ge,"isAbort");function et(t,n){return t.controller!==n}o(et,"superseded");function Wt(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}o(Wt,"inspectError");function Xt(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Wt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Xt,"inspectQuery");function Zt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Zt,"inspectControl");function tt(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}o(tt,"inspectSelection");function nt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(nt,"selectionKey");function rt(t,n){return t instanceof S?t:new D(t?.message??"The query failed.",n,t)}o(rt,"toDataAppError");function en(t,n){if(t instanceof S&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof R?new R(e,n):t instanceof C?new C(e,t.status,n):t instanceof u?new u(e,n):new D(e,n,t)}o(en,"toExportError");var ye=class ye extends ${constructor(e,r,i,s,l){super();c(this,"extensions",l);c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=i,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let i=j(new T(e,this,r),this.extensions?.query);return this._queries.set(e,i),this.notify(),i}createFilter(e,r){this.assertNameFree(e,"filter");let i=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),s=j(new P(e,this,r,i,this.backend),this.extensions?.control);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new u(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let i=j(new z(e,this,r),this.extensions?.control);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof O))throw new u("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new u(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);i.aggregation&&Pe(i.aggregation,e.name);let s=new J(e,r,i.field,i.aggregation);if(this._mappings.some(l=>l.id===s.id))throw new u(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof T)||!(r instanceof T))throw new u("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new u(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new u(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let i=new q(e,r);if(this._crossFilters.some(s=>s.id===i.id))throw new u(`Cross-filter \'${i.id}\' is already declared.`,e.name);return this._crossFilters.push(i),this.notify(),i}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return Le(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?void 0:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?he:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i.conditions:he}drillTransformations(e){let r={};return this._mappings.forEach(i=>{if(i.to!==e)return;let s=i.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[l]=s.values??[];typeof l=="string"&&(r[i.field]=l)}),r}select(e,r,i){if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=Ze(e,r,i,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?nt(this._selection)!==nt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(e.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],l=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let g=await ue(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},i,d.signal);if(et(a,d))return;a.markSuccess(g,p,!1),s.push(a.name)}catch(g){if(et(a,d)||ge(g))return;a.markError(rt(g,a.name)),l.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:s,failed:l}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let i=e.signature();e.markExecuting();try{let s=await ue(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(s,i,!0)}catch(s){if(e.rewindPage(),ge(s))return;let l=rt(s,e.name);throw e.markError(l),l}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,i){let s=je(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await i(s,r.signal??new AbortController().signal)}catch(l){throw ge(l)?l:en(l,e.name)}}toJSON(){let e=o(r=>Object.fromEntries([...this._controls.entries()].filter(([,i])=>i.kind===r).map(([i,s])=>[i,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,i])=>[r,i.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,Xt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Zt(r)])),...this._selection?{selection:tt(this._selection)}:{},...this._appliedSelection?{appliedSelection:tt(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Te(i,e,this.index,r);return s.length?(Ie(s[0]),V(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ze([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let i=Object.keys(this.datasets);if(i.length===1)return this.datasets[i[0]];throw new u(i.length?`Filter \'${e}\' names a field but the environment has ${i.length} datasets. Say which one: ${i.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],i=new Map;r.forEach(d=>{let p=d.from.name;i.set(p,[...i.get(p)??[],d.to.name])});let s=new Set,l=new Set,a=o(d=>{if(s.has(d))return!0;if(l.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(a);return s.delete(d),l.add(d),p},"walk");if([...i.keys()].some(a))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(ye,"App");var K=ye;var it="0.13.5";var xe=class xe{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};o(xe,"InstalledPlugins");var be=xe,nn=it,ke=class ke{constructor(n){c(this,"version",nn);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new u("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new u("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new u("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new G(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new be(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new K(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};o(ke,"Sdk");var we=ke;function ot(t){return new we(t)}o(ot,"createSdk");var B="Anfra";function st(t,n=globalThis){let e=n[B],r=B in n;return n[B]=t,()=>{r?n[B]=e:delete n[B]}}o(st,"installSandbox");function at(t,n=[]){let e=t.document.getElementById(Se);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),i=o(m=>t.parent.postMessage(m,r.hostOrigin),"post"),s=new Map,l=new Map,a=Ae(i,{answer:o(async(m,y,f)=>{let b=s.get(m);if(!b)throw new C(`Nothing in this frame answers \'${m}\'.`);return b(y,f)},"answer"),event:o((m,y)=>{l.get(m)?.forEach(f=>{try{f(y)}catch{}})},"event")}),d=o(m=>m.source===t.parent||!!r.hostOrigin&&r.hostOrigin!=="null"&&m.origin===r.hostOrigin,"fromHost");t.addEventListener("message",m=>{d(m)&&a.receive(m.data)});let p={submitQuery:o((m,y)=>a.call("core.submitQuery",m,y).then(f=>(f.debug?.executedAt&&(f.debug.executedAt=new Date(f.debug.executedAt)),f)),"submitQuery"),fieldSuggestions:o((m,y)=>a.call("core.fieldSuggestions",m,y),"fieldSuggestions")},g=ot({datasets:r.datasets,user:r.user,backend:p,plugins:r.plugins??[]}),x=new Set,h=g.createApp.bind(g);g.createApp=m=>{let y=h(m);return x.forEach(f=>{try{f(y)}catch{}}),y};let E={window:t,sdk:g,endpoint:a,handlers:s,listeners:l,appListeners:x};for(let[m,y]of n)if(typeof y=="function")try{y(Be(m,E,{Query:T,Control:O}))}catch(f){t.console?.error(`anfra: plugin \'${m}\' failed to set up:`,f)}st(g,t),i({type:"anfra:ready"})}o(at,"bootstrap");return ht(rn);})();\n';
|
|
27
|
+
var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var z=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Pt=Object.prototype.hasOwnProperty;var Qt=(t,n,e)=>n in t?z(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var i=(t,n)=>z(t,"name",{value:n,configurable:!0});var Lt=(t,n)=>{for(var e in n)z(t,e,{get:n[e],enumerable:!0})},Bt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of It(n))!Pt.call(t,o)&&o!==e&&z(t,o,{get:()=>n[o],enumerable:!(r=Ft(n,o))||r.enumerable});return t};var zt=t=>Bt(z({},"__esModule",{value:!0}),t);var u=(t,n,e)=>Qt(t,typeof n!="symbol"?n+"":n,e);var Pn={};Lt(Pn,{bootstrap:()=>Nt});var Le="anfra-provision";var re=class re extends Error{constructor(e,r){super(e);u(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};i(re,"DataAppError");var O=re,oe=class oe extends O{};i(oe,"ValidationError");var g=oe,ie=class ie extends O{constructor(e,r,o){super(e,r);u(this,"cause");this.cause=o}};i(ie,"QueryError");var _=ie,se=class se extends O{};i(se,"PermissionError");var N=se,ae=class ae extends O{constructor(e,r,o){super(e,o);u(this,"status");this.status=r}};i(ae,"TransportError");var M=ae;function Be(){let t=new Error("Aborted");return t.name="AbortError",t}i(Be,"abortError");function Kt(t){return t?.name==="AbortError"}i(Kt,"isAbortError");var Vt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function jt(t){let n=t;return n instanceof Error&&Vt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}i(jt,"toBridgeError");function Ut(t){switch(t?.name){case"PermissionError":return new N(t.message);case"TransportError":return new M(t.message);case"ValidationError":return new g(t.message);default:return new _(t?.message||"The call failed.")}}i(Ut,"fromBridgeError");function ze(t,n){let e=new Map,r=new Map,o=1,s=i((a,l,d)=>{let f=new AbortController;r.set(a,f),Promise.resolve().then(()=>n.answer(l,d,f.signal)).then(w=>{f.signal.aborted||t({type:"anfra:result",id:a,ok:!0,result:w})}).catch(w=>{f.signal.aborted||Kt(w)||t({type:"anfra:result",id:a,ok:!1,error:jt(w)})}).finally(()=>{r.get(a)===f&&r.delete(a)})},"answer");return{call(a,l,d){return new Promise((f,w)=>{if(d?.aborted){w(Be());return}let S=o++;e.set(S,{resolve:f,reject:w}),d?.addEventListener("abort",()=>{e.delete(S)&&(t({type:"anfra:cancel",id:S}),w(Be()))},{once:!0}),t({type:"anfra:call",id:S,name:a,request:l})})},emit(a,l){t({type:"anfra:event",name:a,payload:l})},receive(a){switch(a?.type){case"anfra:call":return s(a.id,a.name,a.request),!0;case"anfra:result":{let l=e.get(a.id);return l&&(e.delete(a.id),a.ok?l.resolve(a.result):l.reject(Ut(a.error))),!0}case"anfra:cancel":return r.get(a.id)?.abort(),r.delete(a.id),!0;case"anfra:event":return n.event(a.name,a.payload),!0;default:return!1}},close(a){r.forEach(l=>l.abort()),r.clear(),e.forEach(({reject:l})=>l(a)),e.clear()}}}i(ze,"createEndpoint");var le=class le{constructor(n){u(this,"listeners",new Set);u(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};i(le,"Observable");var P=le;var Ke=["year","quarter","month","week","day","hour","minute"];function Jt(t,n){if(!Ke.includes(n))throw new g(`Invalid grain \'${n}\'. Expected one of: ${Ke.join(", ")}.`,t)}i(Jt,"assertGrain");function Ve(t,n){return n?(Jt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}i(Ve,"drillCondition");function Gt(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}i(Gt,"inferType");function qt(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}i(qt,"sameCondition");var de=class de extends P{constructor(e,r,o){super(r);u(this,"name");u(this,"app");u(this,"pending");u(this,"applied");u(this,"initial");this.name=e,this.app=r,this.initial=o,this.pending=o}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!qt(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};i(de,"Control");var F=de,ce=class ce extends F{constructor(e,r,o,s,a){super(e,r,o.default??{operator:"is",values:[]});u(this,"kind","filter");u(this,"declaration");u(this,"type");u(this,"resolved");u(this,"datasetName");u(this,"backend");u(this,"loadedOptions");if(this.declaration=o,this.backend=a,o.field){if(!s)throw new g(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=s.resolve(o.field,e),this.datasetName=s.descriptor.name,this.type=o.type??Gt(this.resolved.type)}else{if(!o.type)throw new g(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=o.type}this.assertValues(this.condition.values??[]),this.assertValues(o.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(o=>typeof o=="number");if(r!==void 0)throw new g(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let o=this.resolved?.modelName;if(!this.resolved||!o||!this.backend||!this.datasetName)return this.options;let s=await this.backend.fieldSuggestions({dataset:this.datasetName,model:o,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...s??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};i(ce,"Filter");var U=ce,ue=class ue extends F{constructor(e,r,o={}){super(e,r,Ve(e,o.default));u(this,"kind","dateDrill");u(this,"declaration");this.declaration=o}setGrain(e){this.setCondition(Ve(this.name,e))}toJSON(){return this.declaration}};i(ue,"DateDrillControl");var J=ue;var A={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},G=`[${A.container}],[${A.block}],[${A.query}],[${A.control}]`;function je(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}i(je,"parseRef");var Ue=i(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Je(t,n,e,r){let o=n==="query"?A.query:A.control;return[...t.querySelectorAll(`[${o}]`)].filter(s=>Ue(s.getAttribute(o)).some(a=>{let l=je(a);return l?.app===e&&l.name===r}))}i(Je,"markersFor");var Ht=i((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function Ge(t,n){var S;let e=[],r=new Map,o=new Map,s=new Map,a=new Map,l={container:new Set,block:new Set},d={},f=i((v,x,T)=>{let C=v?s.get(v).children:e,p=v?`${s.get(v).key}.`:"",m={...x,key:`${p}${C.length}`,children:[]};return C.push(m),r.set(m.key,T),o.set(T,[...o.get(T)??[],m.key]),m},"place");for(let v of t.querySelectorAll(G)){let x=v.parentElement?.closest(G)??null,T=v.getAttribute(A.container),C=v.getAttribute(A.block),p=v.getAttribute(A.label)??void 0,m=x&&(a.get(x)==="block"?x:x.closest(`[${A.block}]`)),c;if(T!==null||C!==null){let y=T!==null?"container":"block",b=(T??C??"").trim(),E=[];T!==null&&C!==null&&E.push("This element is marked as a container and as a block. It counts as a container."),b?l[y].has(b)?E.push(`Another ${y} already has the id "${b}".`):l[y].add(b):E.push(`This ${y} has no id.`),m&&E.push(`A block can\'t hold a ${y}. This one is inside the block "${m.getAttribute(A.block)}".`),c=f(x,{kind:y,id:b,...p!==void 0?{label:p}:{},problems:E},v),s.set(v,c),a.set(v,y)}let h=c?v:x;for(let y of["query","control"])for(let b of Ue(v.getAttribute(y==="query"?A.query:A.control))){let E=je(b),k=[];if(E?Ht(n,y,E)||k.push(n[E.app]?`No ${y} is called "${E.name}" in app ${E.app}.`:`The page has no app ${E.app}.`):k.push(`Can\'t read "${b}". Write the ${y}\'s name, or app/name when the page has several apps.`),f(h,{kind:y,name:E?.name??b,app:E?.app??0,problems:k},v),E&&!k.length){let R=`${E.app}/${E.name}`,D=d[S=`${y}:${R}`]??(d[S]={elements:new Set,blocks:new Set});D.elements.add(v);let $=c?.kind==="block"?c.id:m?.getAttribute(A.block);$&&D.blocks.add($)}}}let w=Object.fromEntries(Object.entries(d).map(([v,x])=>[v,{markers:x.elements.size,blocks:[...x.blocks]}]));return{nodes:e,usage:w,elements:r,keysOf:o}}i(Ge,"buildStructure");var Wt=i((t,n,e)=>`${t}:${n}/${e}`,"usageKey");function Yt(t){let n=t.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}i(Yt,"sizeOf");function qe(t,n,e){let r=Yt(n);if(t.kind==="container"||t.kind==="block")return{kind:t.kind,name:t.id??"",...t.label?{label:t.label}:{},size:r};let o=e.usage[Wt(t.kind,t.app??0,t.name??"")];return{kind:t.kind,name:t.name??"",...o&&o.markers>1?{note:`1 of ${o.markers}`}:{},size:r}}i(qe,"describeNode");var Ye=["color-bg","color-fg","color-muted","color-border","color-accent","color-danger","radius","font","font-mono"],He=\'system-ui, -apple-system, "Segoe UI", sans-serif\',We="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",pe={light:{"color-bg":"#ffffff","color-fg":"#18181b","color-muted":"#71717a","color-border":"#e4e4e7","color-accent":"#5b3df5","color-danger":"#c4261d",radius:"8px",font:He,"font-mono":We},dark:{"color-bg":"#1c1c20","color-fg":"#ececef","color-muted":"#9a9aa5","color-border":"#2f2f36","color-accent":"#a594ff","color-danger":"#f97066",radius:"8px",font:He,"font-mono":We}},Xt=/[;{}<>]|url\\(|expression\\(|@import|\\\\/i;function Xe(t){let n=typeof t=="object"&&t!==null?t:{},e=n.scheme==="dark"?"dark":"light",r={...pe[e]},o=typeof n.tokens=="object"&&n.tokens!==null?n.tokens:{};for(let s of Ye){let a=o[s];typeof a=="string"&&a.trim()!==""&&a.length<=200&&!Xt.test(a)&&(r[s]=a.trim())}return Object.freeze({scheme:e,tokens:Object.freeze(r)})}i(Xe,"resolveTheme");function fe(t,n){for(let e of Ye)t.setProperty(`--anfra-${e}`,n.tokens[e]);t.setProperty("color-scheme",n.scheme)}i(fe,"applyTheme");var me="data-anfra-layer",Ze=new WeakMap,Zt="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function en(t){let n=t.querySelector(`[${me}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");e.setAttribute(me,""),e.setAttribute("style",Zt);let r=Ze.get(t);return r&&fe(e.style,r),(t.body??t.documentElement).appendChild(e),e}i(en,"layerOf");function L(t,n){let e=en(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let o=t.createElement("div");return o.setAttribute("data-part",n),e.appendChild(o),o.attachShadow({mode:"open"})}i(L,"layerRoot");function et(t,n){Ze.set(t,n);let e=t.querySelector(`[${me}]`);e&&fe(e.style,n)}i(et,"themeLayer");var tt="anfra-overlay",tn=1500,nn="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",rn="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",on={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ge=class ge{constructor(n){u(this,"doc",n);u(this,"root");u(this,"shown",[]);u(this,"text",{kind:"",name:""});u(this,"timer");u(this,"reposition",i(()=>this.draw(),"reposition"));let e=L(n,"anfra"),r=e.getElementById(tt);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=tt,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||L(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=tn){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(l=>{let d=l.getBoundingClientRect(),f=this.doc.createElement("div");return f.setAttribute("style",`${nn}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),f}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let o=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),a=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${rn}left:${a}px;top:${Math.min(s,o-24)}px;`);for(let l of["kind","name","label","note","size"]){let d=this.text[l];if(!d)continue;let f=this.doc.createElement("span");f.setAttribute("style",on[l]),f.setAttribute("data-part",l),f.textContent=d,r.appendChild(f)}this.root.replaceChildren(...n,r)}};i(ge,"Overlay");var he=ge,nt=new WeakMap;function q(t){let n=nt.get(t);return n||(n=new he(t),nt.set(t,n)),n}i(q,"overlayFor");function H(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}i(H,"scrollTo");function rt(t,n){let e=null,r=i(d=>d.target instanceof Element?d.target.closest(G):null,"under"),o=i(d=>{let f=r(d);f!==e&&(e=f,n.onHover(f))},"onMove"),s=i(d=>{d.preventDefault(),d.stopPropagation();let f=r(d);f&&n.onPick(f)},"onClick"),a=i(d=>{d.key==="Escape"&&n.onCancel()},"onKey"),l={capture:!0};return t.addEventListener("mousemove",o,l),t.addEventListener("click",s,l),t.addEventListener("keydown",a,l),()=>{t.removeEventListener("mousemove",o,l),t.removeEventListener("click",s,l),t.removeEventListener("keydown",a,l)}}i(rt,"startPick");function ot(t,n){for(let e of t){if(e.key===n)return e;let r=ot(e.children,n);if(r)return r}}i(ot,"findNode");function it(t){let n=t.window,e=n.document,r=!1,o,s,a="",l,d;function f(){if(o=void 0,!!r)try{s=t.structure(),a=JSON.stringify(s.nodes),t.emit("snapshot",{apps:t.sdk.apps.map(p=>p.toInspectJSON()),structure:{nodes:s.nodes,usage:s.usage}})}catch{}}i(f,"postSnapshot");function w(){r&&o===void 0&&(o=setTimeout(f,50))}i(w,"scheduleSnapshot");function S(){let p=n.MutationObserver;if(l||typeof p!="function")return;let m=new p(()=>{if(!(!r||o!==void 0))try{JSON.stringify(t.structure().nodes)!==a&&w()}catch{}});l=m,m.observe(e.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:Object.values(A)})}i(S,"observeStructure");function v(p){let m=p!==null&&s?ot(s.nodes,p):void 0,c=p!==null?s?.elements.get(p):void 0;if(!m||!c||!s){t.overlay.hide();return}t.overlay.show([c],qe(m,c,s))}i(v,"highlight");function x(p){if(!p){d?.(),d=void 0;return}if(d)return;let m=i(c=>s?.keysOf.get(c)?.[0],"keyOf");d=rt(e,{onHover:i(c=>v(c?m(c)??null:null),"onHover"),onPick:i(c=>{let h=m(c);h!==void 0&&t.emit("picked",{node:h})},"onPick"),onCancel:i(()=>{x(!1),t.overlay.hide(),t.emit("picked",{node:null})},"onCancel")})}i(x,"setPicking");function T(p){r=p,p?(S(),f()):(l?.disconnect(),l=void 0,x(!1),t.overlay.hide(),s=void 0,a="")}i(T,"setInspecting");function C(p){if("node"in p){let m=s?.elements.get(p.node);m&&H(m),v(p.node)}else t.sdk.apps[p.app]?.locate(p.kind,p.name);w()}i(C,"locate"),t.on("watch",p=>T(p===!0)),t.on("highlight",p=>v(p)),t.on("locate",p=>C(p)),t.on("pick",p=>x(p===!0)),t.onApp(p=>{p.subscribe(w),w()})}i(it,"installInspection");var ye;function st(t,n){return ye?ye(t,n):!1}i(st,"openRowsMenu");var sn=`[${A.block}]`,an=\'[data-anfra-menu="off"]\',ln=i(t=>({...t,children:t.children.map(n=>({...n,children:[]}))}),"bare");function at(t,n,e=[]){for(let r of t){if(r.key===n)return[...e,r];let o=at(r.children,n,[...e,r]);if(o)return o}}i(at,"pathTo");var dn=i(t=>typeof t?.closest=="function","isElement");function lt(t){let n=t.window,e=n.document,r=[],o=new Set,s=!1,a,l=i(()=>t.body(),"ui"),d=i(()=>L(e,"anfra-ui"),"root"),f=i(c=>o.has(c)||r.some(h=>h.target===c),"offered"),w=i(()=>{let c=a;a=void 0,c?.()},"closeCurrent");function S(c){let h=dn(c)?c.closest(sn):null;return h&&!h.closest(an)?h:void 0}i(S,"blockOf");function v(c){let h=t.structure(),y=h.keysOf.get(c)?.[0],b=y!==void 0?at(h.nodes,y):void 0;if(!b)return;let{x:E,y:k,width:R,height:D}=c.getBoundingClientRect();return{kind:"node",node:ln(b[b.length-1]),ancestors:b.slice(0,-1).map($=>({...$,children:[]})),rect:{x:E,y:k,width:R,height:D}}}i(v,"nodeTarget");function x(c){let h=new Map,y=[];for(let b of r){if(b.target!==c.kind)continue;let E=!0;try{E=b.when?b.when(c)!==!1:!0}catch{E=!1}if(!E)continue;let k=`frame:${b.full}:${c.kind}`;y.push({id:k,label:b.label}),h.set(k,()=>b.run(c))}return{entries:y,run:h}}i(x,"frameEntries");async function T(c,h){let y=new Map(h.run),b=[...h.entries];if(o.has(c.kind))try{let E=await t.call("anfra.menu",c);for(let k of Array.isArray(E)?E:[]){if(typeof k?.id!="string"||typeof k.label!="string")continue;let R=`host:${k.id}:${c.kind}`;b.push({id:R,label:k.label,...typeof k.disabled=="string"?{disabled:k.disabled}:{}}),y.set(R,()=>t.call("anfra.run",{id:k.id,target:c}))}}catch{}return{entries:b,run:y}}i(T,"entriesFor");function C(c,h){let y=h.map(R=>({target:R,own:x(R)})).filter(({target:R,own:D})=>D.entries.length||o.has(R.kind));if(!y.length)return!1;c.preventDefault();let b=c,E=typeof b.clientX=="number"?b.clientX:0,k=typeof b.clientY=="number"?b.clientY:0;return(async()=>{let[R,...D]=await Promise.all([l(),...y.map(({target:Q,own:te})=>T(Q,te))]),$=D.map(Q=>Q.entries).filter(Q=>Q.length);if(!$.length)return;w();let j=R.menu(d(),{x:E,y:k,groups:$,onPick:i(Q=>{let te=D.map(ne=>ne.run.get(Q)).find(Boolean);Promise.resolve().then(te).catch(ne=>n.console?.error("anfra: a menu item failed:",ne))},"onPick"),onClose:i(()=>{a===j&&(a=void 0)},"onClose")});a=j})().catch(R=>n.console?.error("anfra: the menu failed to open:",R)),!0}i(C,"open");function p(){s||!(f("node")||f("rows"))||(s=!0,n.addEventListener("contextmenu",c=>{if(c.defaultPrevented||c.shiftKey)return;let h=S(c.target),y=h&&v(h);y&&C(c,[y])}))}i(p,"listen"),ye=i((c,h)=>{if(c.defaultPrevented||c.shiftKey)return!1;let y=S(c.target),b=y?v(y):void 0,E=b?{...h,node:b}:h;return C(c,b?[E,b]:[E])},"rowsOpener"),t.on("menu",c=>{let h=c?.kinds;o=new Set((Array.isArray(h)?h:[]).filter(y=>y==="node"||y==="rows")),p()});async function m(c,h){let y=await l();w();let b=i(()=>{},"close");return b=h(y,i(()=>{a===b&&(a=void 0);try{c.onClose?.()}catch{}},"onClose")),a=b,{close:b}}return i(m,"show"),{addItem(c,h){r.push({...h,full:`${c}.${h.id}`}),p()},modal:i(c=>m(c,(h,y)=>h.modal(d(),{title:c.title,size:c.size,mount:c.mount,onClose:y})),"modal"),popover:i(c=>m(c,(h,y)=>{let{anchor:b}=c,E;if("kind"in b){let k=t.structure().elements.get(b.node.key);E=i(()=>{if(!k?.isConnected)return;let{x:R,y:D,width:$,height:j}=k.getBoundingClientRect();return{x:R,y:D,width:$,height:j}},"rect")}else E=i(()=>({x:b.x,y:b.y,width:0,height:0}),"rect");return h.popover(d(),{anchor:E,side:c.side,mount:c.mount,dismiss:c.dismiss,closeButton:c.closeButton,onClose:y})}),"popover")}}i(lt,"installContentUi");var dt=["ctrl","alt","shift","meta"];function ct(t){if(typeof t!="string")return;let n=t.split("+").map(o=>o.trim().toLowerCase()).filter(Boolean),e=n.pop(),r=i(o=>dt.includes(o),"isModifier");if(!(!e||r(e)||!n.every(r)))return[...dt.filter(o=>n.includes(o)),e].join("+")}i(ct,"normalizeShortcut");function ut(t){let n=t;return!n||typeof n.tagName!="string"?!1:n.isContentEditable===!0||["INPUT","TEXTAREA","SELECT"].includes(n.tagName.toUpperCase())}i(ut,"isTyping");function pt(t){let n=typeof t.code=="string"?t.code:"",e=/^Key[A-Z]$/.test(n)?n.slice(3).toLowerCase():/^Digit[0-9]$/.test(n)?n.slice(5):(t.key??"").toLowerCase();return[t.ctrlKey&&"ctrl",t.altKey&&"alt",t.shiftKey&&"shift",t.metaKey&&"meta",e].filter(Boolean).join("+")}i(pt,"eventShortcut");function be(t,n,e,r,o){if(r in n||t.has(r))throw new g(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,o)}i(be,"addExtension");function W(t,n){return n?.forEach((e,r)=>{let o=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return o||(s=e(t),o=!0),s}})}),t}i(W,"applyExtensions");var cn="anfra.body",we="__anfraBodyExports",un={DataAppError:O,ValidationError:g,QueryError:_,PermissionError:N,TransportError:M};function pn(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(we)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let o=e[we];if(delete e[we],!o)throw new g("The host sent a plugin body that did not run.");return o.default??o}i(pn,"runBody");function ve(t,n,e){let{window:r,sdk:o,endpoint:s}=n,a;return{plugin:t,window:r,sdk:o,errors:un,get overlay(){return q(r.document)},structure:i(()=>Ge(r.document,o.apps),"structure"),call:i((l,d,f)=>s.call(l,d??null,f),"call"),emit:i((l,d)=>s.emit(`${t}.${l}`,d??null),"emit"),handle(l,d){n.handlers.set(`${t}.${l}`,d)},on(l,d){let f=`${t}.${l}`;n.listeners.has(f)||n.listeners.set(f,new Set),n.listeners.get(f).add(d)},onApp(l){n.appListeners.add(l),o.apps.forEach(d=>l(d))},provide(l){if(t in o)throw new g(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(o,t,{value:l,enumerable:!0})},provideOnQuery:i(l=>be(o.extensions.query,e.Query.prototype,"query",t,l),"provideOnQuery"),provideOnControl:i(l=>be(o.extensions.control,e.Control.prototype,"control",t,l),"provideOnControl"),layer:i(()=>L(r.document,t),"layer"),menuItem:i(l=>n.contentUi?.addItem(t,l),"menuItem"),modal:i(l=>n.contentUi.modal(l),"modal"),popover:i(l=>n.contentUi.popover(l),"popover"),body(){return a??(a=s.call(cn,{plugin:t}).then(l=>pn(r,l)).catch(l=>{throw a=void 0,l})),a}}}i(ve,"createKernel");var Ee=class Ee extends P{constructor(e,r,o){super(r);u(this,"kind","query");u(this,"name");u(this,"declaration");u(this,"dataset");u(this,"app");u(this,"_state","idle");u(this,"_result");u(this,"_error");u(this,"_page",1);u(this,"_sort",[]);u(this,"lastRunSignature");u(this,"lastPageRows",0);u(this,"controller");if(!o.aql?.trim())throw new g(`Query \'${e}\' declares no AQL.`,e);let{pageSize:s}=o;if(s!==void 0&&!(Number.isInteger(s)&&s>=1))throw new g(`Query \'${e}\' declares pageSize ${s}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=o,this.dataset=r.datasetIndex(o.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this._result.meta.hasMore??this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,o)=>r.field.localeCompare(o.field)||JSON.stringify(r).localeCompare(JSON.stringify(o)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new g(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}menu(e,r,o={}){return this.app.menu(this,e,Array.isArray(r)?r:[r],o.fields)}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let o=i(a=>JSON.stringify(e.fields.map(l=>a[l]??null)),"key"),s=new Set(e.rows.map(o));return r.filter(a=>s.has(o(a)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,o){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,o&&this._result){let s=[...this._result.rows,...e.rows];this._result={...e,rows:s,meta:{...e.meta,numRows:s.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};i(Ee,"Query");var I=Ee;var xe=class xe{constructor(n,e,r,o){u(this,"kind","control");u(this,"from");u(this,"to");u(this,"field");u(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=o}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};i(xe,"Mapping");var Y=xe,ke=class ke{constructor(n,e){u(this,"kind","crossFilter");u(this,"from");u(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};i(ke,"CrossFilter");var X=ke;var Se=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function fn(t,n){let e=t.length+1,r=n.length+1,o=Array.from({length:r},(s,a)=>a);for(let s=1;s<e;s++){let a=[s];for(let l=1;l<r;l++)a[l]=Math.min(o[l]+1,a[l-1]+1,o[l-1]+(t[s-1]===n[l-1]?0:1));o=a}return o[r-1]}i(fn,"editDistance");function mn(t,n){let e,r=1/0;n.forEach(s=>{let a=fn(t.toLowerCase(),s.toLowerCase());a<r&&(r=a,e=s)});let o=Math.max(2,Math.floor(t.length/3));return r<=o?e:void 0}i(mn,"suggest");function B(t,n,e){let r=mn(n,e);return r?`${t} Did you mean \'${r}\'?`:t}i(B,"withSuggestion");var Te=class Te{constructor(n){u(this,"descriptor");u(this,"fields",new Map);u(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let o=String(e.name);this.fields.set(`${o}.${r.name}`,{modelName:o,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new g(B(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};i(Te,"DatasetIndex");var Z=Te;function ft(t,n,e){let r=t[n];if(r)return r;throw new g(B(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}i(ft,"resolveDataset");function mt(t,n){if(!Se.includes(t))throw new g(B(`Invalid filter aggregation \'${t}\'.`,t,[...Se]),n)}i(mt,"assertValidFilterAggregation");function ht(t,n,e){if(!n)throw new g(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new g(`\'${n}\' is already declared in this app.`,n)}i(ht,"assertUniqueName");function hn(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}i(hn,"toFilter");function gn(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}i(gn,"toDateDrill");function yn(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let a={};return e.forEach((l,d)=>{a[l.name]=s[d]}),a}),{pageSize:o}=t;return{columns:e,rows:r,meta:{...o!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??o,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}i(yn,"toResult");function gt(t,n,e,r){let o=n.map(d=>hn(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>gn(d,d.from.appliedCondition)).filter(d=>d!==void 0),a=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),l=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...o,...a],conditions:l,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}i(gt,"buildQuery");function bn(t,n,e,r){return{...gt(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}i(bn,"buildRequest");function wn(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}i(wn,"defaultExportFilename");function yt(t,n,e,r,o){let s=o.format??"csv",a=s==="csv"?{bom:!0,...o.formatOptions}:o.formatOptions;return{...gt(t,n,e,r),format:s,...a?{formatOptions:a}:{},filename:o.filename?.trim()||wn(t,r.title)}}i(yt,"buildExportRequest");async function Ce(t,n,e,r,o){let s=bn(t,n,e,r),a=await r.backend.submitQuery(s,o);return yn(t,a)}i(Ce,"runQuery");function vn(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return kn(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}i(vn,"literal");function bt(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${vn(n,e)}`}i(bt,"equals");var En=new Set(["NaN","Infinity","-Infinity"]),xn=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function kn(t){let n=xn.exec(t);if(!n)throw En.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,o="",s]=n;if(s===void 0)return t;let a=r+o,l=r.length+Number(s),d;return l<=0?d=`0.${"0".repeat(-l)}${a}`:l>=a.length?d=a+"0".repeat(l-a.length):d=`${a.slice(0,l)}.${a.slice(l)}`,e+d.replace(/^0+(?=\\d)/,"")}i(kn,"numberLiteral");function wt(t,n,e){return`${t} matches @(${n} until ${e})`}i(wt,"dateRange");function vt(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}i(vt,"combine");var Et=i(t=>vt("and",t),"and"),xt=i(t=>vt("or",t),"or");var Sn=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,Tn={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function kt(t){if(typeof t!="string")return;let n=Sn.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}i(kt,"parseStamp");function K(t,n){let e=new Date(t),r=i(s=>String(s).padStart(2,"0"),"pad"),o=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${o} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:o}i(K,"format");function St(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}i(St,"toMs");function Ae(t){let n=kt(t);if(n)return K(St(n),n.hasTime)}i(Ae,"normalise");function Re(t,n){let e=kt(t);if(!e)return;let{year:r,month:o,day:s,hour:a,minute:l,second:d,hasTime:f}=e;return K(n==="year"?Date.UTC(r+1,o,s,a,l,d):n==="quarter"?Date.UTC(r,o+3,s,a,l,d):n==="month"?Date.UTC(r,o+1,s,a,l,d):St(e)+Tn[n],f)}i(Re,"addGrain");function Tt(t){if(t?.startsWith("datetrunc "))return t.slice(10)}i(Tt,"grainOf");function Cn(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}i(Cn,"distinct");function An(t,n){let e=t.map(Ae);if(e.some(o=>o===void 0))return!1;let r=e.slice().sort();for(let o=1;o<r.length;o+=1)if(Re(r[o-1],n)!==r[o])return!1;return!0}i(An,"isContiguous");function Rn(t,n,e){let r=n.map(Ae);if(r.some(d=>d===void 0))return;let o=r.slice().sort(),s=o[0],a=Re(o[o.length-1],e);if(!a)return;let l=An(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${a}`]},admits:l?n.length:Number.POSITIVE_INFINITY,lossy:!l}}i(Rn,"dateRange");function Dn(t,n,e){let r=e.filter(l=>l!=null),o=Cn(r);if(!o.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,a=Tt(n);if(a){let l=Rn(t,o,a);if(l)return{...l,lossy:l.lossy||s}}return{condition:{field:t,operator:"is",values:o},admits:o.length,lossy:s}}i(Dn,"deriveOne");function Ct(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}i(Ct,"fieldReferenceOf");function On(t,n,e,r){try{let o=e.map(s=>Et(n.map(a=>{let l=t.get(a),d=Ct(l),f=s[a]??null,w=Tt(r[d]);if(w&&typeof f=="string"){let S=Ae(f),v=Re(f,w);if(S&&v)return wt(d,S,v)}if(f!==null&&typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new TypeError("no AQL spelling");return bt(d,f,l.semantic_type)})));return xt(o)}catch{return}}i(On,"selectionExpression");function De(t,n,e,r={}){let o=t.result?.columns??[],s=new Map(o.map(p=>[p.name,p]));e?.forEach(p=>{let m=s.get(p);if(m){if(m.adhoc)throw new g(`Query \'${t.name}\' cannot cross-filter on \'${p}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(m.isMeasure)throw new g(`Query \'${t.name}\' cannot cross-filter on \'${p}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new g(B(`Query \'${t.name}\' has no column \'${p}\' in its last result.`,p,[...s.keys()]),t.name)});let a=o.filter(p=>!p.isMeasure),l=a.filter(p=>!p.adhoc).map(p=>p.name),d=e?[...e]:l;if(!n.length||!d.length)return;let f=[],w=1,S=!e&&l.length!==a.length,v=!1;d.forEach(p=>{let m=s.get(p),c=Ct(m),h=Dn(c,r[c],n.map(y=>y[p]));f.push(h.condition),w*=h.admits,v=v||h.lossy});let x=new Set(n.map(p=>JSON.stringify(d.map(m=>p[m]??null))));w>x.size&&(v=!0);let T=f.sort((p,m)=>p.field.localeCompare(m.field)),C={source:t.name,rows:[...n],fields:d};if(v){let p=On(s,d,n,r);if(p)return{...C,conditions:[],expression:p,lossy:S}}return{...C,conditions:T,lossy:S||v}}i(De,"deriveSelection");var Oe=Object.freeze([]);function Me(t){return t instanceof Error&&t.name==="AbortError"}i(Me,"isAbort");function At(t,n){return t.controller!==n}i(At,"superseded");function Mn(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}i(Mn,"inspectError");function $n(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Mn(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}i($n,"inspectQuery");function _n(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}i(_n,"inspectControl");function Rt(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}i(Rt,"inspectSelection");function Dt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}i(Dt,"selectionKey");function Ot(t,n){return t instanceof O?t:new _(t?.message??"The query failed.",n,t)}i(Ot,"toDataAppError");function Nn(t,n){if(t instanceof O&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof N?new N(e,n):t instanceof M?new M(e,t.status,n):t instanceof g?new g(e,n):new _(e,n,t)}i(Nn,"toExportError");var $e=class $e extends P{constructor(e,r,o,s,a){super();u(this,"extensions",a);u(this,"title");u(this,"_timezone");u(this,"datasets");u(this,"backend");u(this,"features");u(this,"_queries",new Map);u(this,"_controls",new Map);u(this,"_mappings",[]);u(this,"_crossFilters",[]);u(this,"_selection");u(this,"_appliedSelection");u(this,"selectionCommitted",!1);u(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=o,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let o=W(new I(e,this,r),this.extensions?.query);return this._queries.set(e,o),this.notify(),o}createFilter(e,r){this.assertNameFree(e,"filter");let o=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),s=W(new U(e,this,r,o,this.backend),this.extensions?.control);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new g(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let o=W(new J(e,this,r),this.extensions?.control);return this._controls.set(e,o),this.notify(),o}mapControl(e,r,o){if(!(e instanceof F))throw new g("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new g(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new g(`Query \'${r.name}\' belongs to a different app.`,r.name);o.aggregation&&mt(o.aggregation,e.name);let s=new Y(e,r,o.field,o.aggregation);if(this._mappings.some(a=>a.id===s.id))throw new g(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof I)||!(r instanceof I))throw new g("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new g(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new g(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new g(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new g(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let o=new X(e,r);if(this._crossFilters.some(s=>s.id===o.id))throw new g(`Cross-filter \'${o.id}\' is already declared.`,e.name);return this._crossFilters.push(o),this.notify(),o}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return ft(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===e?void 0:this._crossFilters.some(a=>a.from.name===o.source&&a.to.name===e)?o:void 0}selectionConditionsFor(e,r){let o=r==="pending"?this._selection:this._appliedSelection;return!o||o.source===e?Oe:this._crossFilters.some(a=>a.from.name===o.source&&a.to.name===e)?o.conditions:Oe}drillTransformations(e){let r={};return this._mappings.forEach(o=>{if(o.to!==e)return;let s=o.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[a]=s.values??[];typeof a=="string"&&(r[o.field]=a)}),r}menu(e,r,o,s){if(this._queries.get(e.name)!==e)throw new g(`Query \'${e.name}\' belongs to a different app.`,e.name);let a=De(e,o,s,this.drillTransformations(e));return st(r,{kind:"rows",app:this.index,query:e.name,rows:[...o],fields:a?.fields?[...a.fields]:[],conditions:a?.conditions?[...a.conditions]:[],...a?.expression?{expression:a.expression}:{}})}select(e,r,o){if(this._queries.get(e.name)!==e)throw new g(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=De(e,r,o,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?Dt(this._selection)!==Dt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(l=>l.shouldRun(e.force));this._controls.forEach(l=>l.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(l=>{l.controller?.abort(),l.resetPage()});let o={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],a=[];return await Promise.all(r.map(async l=>{let d=new AbortController;l.controller=d;let f=l.signature();l.markExecuting();try{let w=await Ce(l,this.mappingsTo(l.name),{conditions:this.selectionConditionsFor(l.name,"applied"),expression:this.selectionExpressionFor(l.name,"applied")},o,d.signal);if(At(l,d))return;l.markSuccess(w,f,!1),s.push(l.name)}catch(w){if(At(l,d)||Me(w))return;l.markError(Ot(w,l.name)),a.push(l.name)}finally{l.controller===d&&(l.controller=void 0)}})),{succeeded:s,failed:a}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let o=e.signature();e.markExecuting();try{let s=await Ce(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(s,o,!0)}catch(s){if(e.rewindPage(),Me(s))return;let a=Ot(s,e.name);throw e.markError(a),a}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,o){let s=yt(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await o(s,r.signal??new AbortController().signal)}catch(a){throw Me(a)?a:Nn(a,e.name)}}toJSON(){let e=i(r=>Object.fromEntries([...this._controls.entries()].filter(([,o])=>o.kind===r).map(([o,s])=>[o,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,o])=>[r,o.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,$n(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,_n(r)])),...this._selection?{selection:Rt(this._selection)}:{},...this._appliedSelection?{appliedSelection:Rt(this._appliedSelection)}:{}}}locate(e,r){let o=globalThis.document;if(!o)return!1;let s=Je(o,e,this.index,r);return s.length?(H(s[0]),q(o).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ht([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let o=Object.keys(this.datasets);if(o.length===1)return this.datasets[o[0]];throw new g(o.length?`Filter \'${e}\' names a field but the environment has ${o.length} datasets. Say which one: ${o.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],o=new Map;r.forEach(d=>{let f=d.from.name;o.set(f,[...o.get(f)??[],d.to.name])});let s=new Set,a=new Set,l=i(d=>{if(s.has(d))return!0;if(a.has(d))return!1;s.add(d);let f=(o.get(d)??[]).some(l);return s.delete(d),a.add(d),f},"walk");if([...o.keys()].some(l))throw new g(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};i($e,"App");var ee=$e;var Mt="0.14.0";var Ie=class Ie{constructor(){u(this,"current",{scheme:"light",tokens:pe.light});u(this,"listeners",new Set)}get scheme(){return this.current.scheme}get tokens(){return this.current.tokens}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}set(n){this.current=n,this.listeners.forEach(e=>{try{e(n)}catch{}})}};i(Ie,"HostTheme");var _e=Ie,Pe=class Pe{constructor(n){u(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};i(Pe,"InstalledPlugins");var Ne=Pe,In=Mt,Qe=class Qe{constructor(n){u(this,"version",In);u(this,"_apps",[]);u(this,"datasets");u(this,"user");u(this,"indices");u(this,"backend");u(this,"plugins");u(this,"theme",new _e);u(this,"gates");u(this,"deprecatedFeatures");u(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new g("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new g("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new g("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new Z(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new Ne(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new ee(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};i(Qe,"Sdk");var Fe=Qe;function $t(t){return new Fe(t)}i($t,"createSdk");var V="Anfra";function _t(t,n=globalThis){let e=n[V],r=V in n;return n[V]=t,()=>{r?n[V]=e:delete n[V]}}i(_t,"installSandbox");function Nt(t,n=[]){let e=t.document.getElementById(Le);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),o=i(m=>t.parent.postMessage(m,r.hostOrigin),"post"),s=new Map,a=new Map,l=ze(o,{answer:i(async(m,c,h)=>{let y=s.get(m);if(!y)throw new M(`Nothing in this frame answers \'${m}\'.`);return y(c,h)},"answer"),event:i((m,c)=>{a.get(m)?.forEach(h=>{try{h(c)}catch{}})},"event")}),d=i(m=>m.source===t.parent||!!r.hostOrigin&&r.hostOrigin!=="null"&&m.origin===r.hostOrigin,"fromHost");t.addEventListener("message",m=>{d(m)&&l.receive(m.data)});let f={submitQuery:i((m,c)=>l.call("core.submitQuery",m,c).then(h=>(h.debug?.executedAt&&(h.debug.executedAt=new Date(h.debug.executedAt)),h)),"submitQuery"),fieldSuggestions:i((m,c)=>l.call("core.fieldSuggestions",m,c),"fieldSuggestions")},w=$t({datasets:r.datasets,user:r.user,backend:f,plugins:r.plugins??[]}),S=new Set,v=w.createApp.bind(w);w.createApp=m=>{let c=v(m);return S.forEach(h=>{try{h(c)}catch{}}),c};let x={window:t,sdk:w,endpoint:l,handlers:s,listeners:a,appListeners:S},T=ve("anfra",x,{Query:I,Control:F});it(T),x.contentUi=lt(T),T.on("theme",m=>{let c=Xe(m);et(t.document,c),w.theme.set(c)});let C=new Set,p=!1;T.on("shortcuts",m=>{C=new Set((Array.isArray(m)?m:[]).map(ct).filter(c=>!!c)),!(p||!C.size)&&(p=!0,t.addEventListener("keydown",c=>{if(c.defaultPrevented||c.repeat||ut(c.target))return;let h=pt(c);C.has(h)&&(c.preventDefault(),T.emit("shortcut",h))}))});for(let[m,c]of n)if(typeof c=="function")try{c(ve(m,x,{Query:I,Control:F}))}catch(h){t.console?.error(`anfra: plugin \'${m}\' failed to set up:`,h)}_t(w,t),o({type:"anfra:ready"})}i(Nt,"bootstrap");return zt(Pn);})();\n';
|
|
28
|
+
|
|
29
|
+
// anfra-sdk:anfra-sdk:ui
|
|
30
|
+
var anfra_sdk_ui_default = '"use strict";var __anfraBody=(()=>{var k=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var a=(n,t)=>k(n,"name",{value:t,configurable:!0});var B=(n,t)=>{for(var e in t)k(n,e,{get:t[e],enumerable:!0})},D=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of I(t))!O.call(n,d)&&d!==e&&k(n,d,{get:()=>t[d],enumerable:!(r=C(t,d))||r.enumerable});return n};var T=n=>D(k({},"__esModule",{value:!0}),n);var Y={};B(Y,{default:()=>z});var W=`\n:host { all: initial; }\n* { box-sizing: border-box; }\n/* A part\'s container: over the whole viewport in the top layer, letting the pointer through to the page. */\n.part { position: fixed; inset: 0; width: auto; height: auto; margin: 0; padding: 0; border: 0; overflow: visible; background: none; pointer-events: none; }\n.surface, .backdrop { pointer-events: auto; }\n.surface { position: fixed; z-index: 1; color: var(--anfra-color-fg, #18181b); background: var(--anfra-color-bg, #fff);\n border: 1px solid var(--anfra-color-border, #e4e4e7); border-radius: var(--anfra-radius, 8px);\n box-shadow: 0 8px 24px rgb(0 0 0 / 18%), 0 1px 3px rgb(0 0 0 / 10%); font: 13px/1.45 var(--anfra-font, system-ui, sans-serif); }\n.menu { min-width: 180px; max-width: 320px; padding: 4px; outline: none; }\n.menu button { display: block; width: 100%; padding: 6px 10px; border: 0; border-radius: 4px; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }\n/* One highlight, as a native menu has: the focused entry, which the pointer and the arrows both move. */\n.menu button:focus { outline: none; background: color-mix(in srgb, var(--anfra-color-accent, #5b3df5) 14%, transparent); }\n.menu button[aria-disabled="true"] { color: var(--anfra-color-muted, #71717a); cursor: default; }\n.menu .reason { display: block; font-size: 11px; color: var(--anfra-color-muted, #71717a); }\n.menu hr { margin: 4px 0; border: 0; border-top: 1px solid var(--anfra-color-border, #e4e4e7); }\n.backdrop { position: fixed; inset: 0; background: rgb(0 0 0 / 40%); }\n.modal { display: flex; flex-direction: column; left: 50%; top: 50%; transform: translate(-50%, -50%); max-width: calc(100vw - 32px); max-height: calc(100vh - 32px); }\n.modal.sm { width: 360px; } .modal.md { width: 560px; } .modal.lg { width: 860px; }\n.modal.full { width: calc(100vw - 32px); height: calc(100vh - 32px); }\n.modal header { display: flex; align-items: center; gap: 8px; padding: 10px 12px 10px 16px; border-bottom: 1px solid var(--anfra-color-border, #e4e4e7); }\n.modal h2 { flex: 1; margin: 0; font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.close { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 4px; background: none; color: var(--anfra-color-muted, #71717a); cursor: pointer; font: 18px/1 var(--anfra-font, system-ui, sans-serif); }\n.close:hover { color: var(--anfra-color-fg, #18181b); background: color-mix(in srgb, var(--anfra-color-fg, #18181b) 7%, transparent); }\n.content { flex: 1; min-height: 0; overflow: auto; }\n.popover { max-width: min(360px, calc(100vw - 16px)); outline: none; }\n.popover > .close { position: absolute; top: 4px; right: 4px; width: 22px; height: 22px; font-size: 16px; }\n.popover.closable > .content { padding-right: 26px; }\n`;function N(n){return{width:n.innerWidth,height:n.innerHeight}}a(N,"viewport");function H(n,t,e,r,d){let{width:y,height:o}=N(n),s=e,g=r;return s+t.width>y-8&&(s=d?d.left-t.width:y-8-t.width),g+t.height>o-8&&(g=d?d.top-t.height:o-8-t.height),{left:Math.max(8,s),top:Math.max(8,g)}}a(H,"place");var P={right:"left",left:"right",bottom:"top",top:"bottom"};function K(n,t,e,r){let{width:d,height:y}=N(n),o=a(c=>c==="right"?{left:e.x+e.width+6,top:e.y}:c==="left"?{left:e.x-t.width-6,top:e.y}:c==="bottom"?{left:e.x,top:e.y+e.height+6}:{left:e.x,top:e.y-t.height-6},"at"),s=a(c=>{let{left:w,top:v}=o(c);return c==="right"||c==="left"?w>=8&&w+t.width<=d-8:v>=8&&v+t.height<=y-8},"fits"),g=[r,P[r],...["right","bottom","left","top"].filter(c=>c!==r&&c!==P[r])],{left:x,top:b}=o(g.find(s)??r),f=a((c,w,v)=>Math.max(8,Math.min(c,v-8-w)),"clamp");return{left:f(x,t.width,d),top:f(b,t.height,y)}}a(K,"beside");function L(n){let t=n.ownerDocument,e=t.createElement("div");e.className="part",e.setAttribute("popover","manual");let r=t.createElement("style");return r.textContent=W,e.append(r),n.append(e),e.showPopover?.(),{container:e,remove:a(()=>e.remove(),"remove")}}a(L,"part");function S(n,t){let e=n.createElement("div");return e.className=t,{element:e,root:e.attachShadow({mode:"open"})}}a(S,"contentRoot");function G(n,t,e){try{let r=t(e);return typeof r=="function"?r:()=>{}}catch(r){return n.console?.error("anfra: a plugin failed to draw:",r),()=>{}}}a(G,"mountContent");function $(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("div");o.className="surface menu",o.setAttribute("role","menu");let s=[];t.groups.filter(i=>i.length).forEach((i,m)=>{m>0&&o.append(e.createElement("hr"));for(let u of i){let p=e.createElement("button");if(p.type="button",p.setAttribute("role","menuitem"),p.dataset.item=u.id,p.textContent=u.label,u.disabled){p.setAttribute("aria-disabled","true"),p.title=u.disabled;let M=e.createElement("span");M.className="reason",M.textContent=u.disabled,p.append(M)}p.addEventListener("click",()=>{u.disabled||(h(),t.onPick(u.id))}),s.push(p),o.append(p)}}),d.append(o);let g=o.getBoundingClientRect(),{left:x,top:b}=H(r,g,t.x,t.y,{left:t.x,top:t.y});o.style.left=`${x}px`,o.style.top=`${b}px`,o.tabIndex=-1,o.focus();let f=s.filter(i=>!i.hasAttribute("aria-disabled"));o.addEventListener("pointermove",i=>{let m=i.composedPath().find(u=>s.includes(u));m&&f.includes(m)?n.activeElement!==m&&m.focus():n.activeElement!==o&&o.focus()}),o.addEventListener("pointerleave",()=>o.focus());let c=a(i=>{if(i.key==="Escape"){i.preventDefault(),h();return}if(i.key!=="ArrowDown"&&i.key!=="ArrowUp"||(i.preventDefault(),!f.length))return;let m=f.indexOf(n.activeElement),u=i.key==="ArrowDown"?1:-1,p=m===-1?u===1?0:f.length-1:(m+u+f.length)%f.length;f[p].focus()},"onKey"),w=a(i=>{i.composedPath().includes(o)||h()},"onOutside"),v=a(()=>h(),"onAway"),E=[[e,"keydown",c,!0],[e,"pointerdown",w,!0],[r,"scroll",v,!0],[r,"resize",v,!1],[r,"blur",v,!1]];E.forEach(([i,m,u,p])=>i.addEventListener(m,u,p));let l=!1;function h(){l||(l=!0,E.forEach(([i,m,u,p])=>i.removeEventListener(m,u,p)),y(),t.onClose())}return a(h,"close"),h}a($,"menu");function V(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("div");o.className="backdrop";let s=e.createElement("section");s.className=`surface modal ${t.size??"md"}`,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true");let g=e.createElement("header"),x=e.createElement("h2");x.id="anfra-modal-title",x.textContent=t.title,s.setAttribute("aria-labelledby",x.id);let b=e.createElement("button");b.type="button",b.className="close",b.setAttribute("aria-label","Close"),b.textContent="\\xD7",b.addEventListener("click",()=>M()),g.append(x,b);let f=S(e,"content");s.append(g,f.element),d.append(o,s);let c=n.host.parentElement,w=r,v=[],E=a(A=>{for(let R of A)!(R instanceof w.Element)||R===c||R.hasAttribute("inert")||(R.setAttribute("inert",""),v.push(R))},"inert");E(e.body.children);let l=new w.MutationObserver(A=>A.forEach(R=>E(R.addedNodes)));l.observe(e.body,{childList:!0});let h=e.documentElement,i={overflow:h.style.overflow,gutter:h.style.getPropertyValue("scrollbar-gutter")};r.innerWidth>h.clientWidth&&h.style.setProperty("scrollbar-gutter","stable"),h.style.overflow="hidden";let m=G(r,t.mount,f.root);b.focus();let u=a(A=>{A.key==="Escape"&&(A.preventDefault(),M())},"onKey");e.addEventListener("keydown",u,!0);let p=!1;function M(){if(!p){p=!0,e.removeEventListener("keydown",u,!0);try{m()}catch{}l.disconnect(),v.forEach(A=>A.removeAttribute("inert")),h.style.overflow=i.overflow,i.gutter?h.style.setProperty("scrollbar-gutter",i.gutter):h.style.removeProperty("scrollbar-gutter"),y(),t.onClose()}}return a(M,"close"),M}a(V,"modal");function U(n,t){let e=n.ownerDocument,r=e.defaultView,{container:d,remove:y}=L(n),o=e.createElement("section");o.className="surface popover",o.setAttribute("role","dialog"),o.tabIndex=-1;let s=S(e,"content");if(o.append(s.element),t.closeButton!==!1){o.classList.add("closable");let l=e.createElement("button");l.type="button",l.className="close",l.setAttribute("aria-label","Close"),l.textContent="\\xD7",l.addEventListener("click",()=>E()),o.append(l)}d.append(o);let g=G(r,t.mount,s.root);s.root.activeElement||o.focus();let x=!1,b=a(()=>{x=!1;let l=t.anchor();if(!l){E();return}let h=o.getBoundingClientRect(),{left:i,top:m}=K(r,h,l,t.side??"right");o.style.left=`${i}px`,o.style.top=`${m}px`},"position"),f=a(()=>{x||(x=!0,r.requestAnimationFrame(b))},"schedule");b();let c=a(l=>{l.key==="Escape"&&(l.preventDefault(),E())},"onKey"),w=a(l=>{l.composedPath().includes(o)||E()},"onOutside");e.addEventListener("keydown",c,!0),r.addEventListener("scroll",f,!0),r.addEventListener("resize",f),t.dismiss==="outside"&&e.addEventListener("pointerdown",w,!0);let v=!1;function E(){if(!v){v=!0,e.removeEventListener("keydown",c,!0),r.removeEventListener("scroll",f,!0),r.removeEventListener("resize",f),e.removeEventListener("pointerdown",w,!0);try{g()}catch{}y(),t.onClose()}}return a(E,"close"),E}a(U,"popover");var q={menu:$,modal:V,popover:U},z=q;return T(Y);})();\n';
|
|
20
31
|
|
|
21
32
|
// src/host/frameScript.ts
|
|
22
33
|
function builtFrameScript() {
|
|
23
34
|
return anfra_sdk_frame_script_default || void 0;
|
|
24
35
|
}
|
|
36
|
+
function builtUiBody() {
|
|
37
|
+
return anfra_sdk_ui_default || void 0;
|
|
38
|
+
}
|
|
25
39
|
|
|
26
40
|
// src/host/provision.ts
|
|
27
41
|
function scriptJSON(value) {
|
|
@@ -53,8 +67,10 @@ function composeFrameScript(frameScript, setups = []) {
|
|
|
53
67
|
}
|
|
54
68
|
var charsetRe = /<meta[^>]*charset[^>]*>/i;
|
|
55
69
|
var headRe = /<head(?:\s[^>]*)?>/i;
|
|
56
|
-
var gap = "(?:\\s|<!--[\\s\\S]
|
|
57
|
-
var
|
|
70
|
+
var gap = "(?:\\s|<!--(?!-?>)[\\s\\S]*?--!?>)*";
|
|
71
|
+
var attribute = `[^\\s/>][^\\s/>=]*(?![^\\s/>=])(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>"'][^\\s>]*(?![^\\s>]))|(?!\\s*=))`;
|
|
72
|
+
var attributes = `(?:\\s(?:[\\s/]|${attribute})*)?`;
|
|
73
|
+
var preambleRe = new RegExp(`^${gap}(?:<!doctype[^>]*>${gap})?(?:<html${attributes}>${gap})?(?:<head${attributes}>)?`, "i");
|
|
58
74
|
function provisionDocument(definition, options) {
|
|
59
75
|
const policy = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(options.contentPolicy)}">`;
|
|
60
76
|
const injected = [
|
|
@@ -112,6 +128,198 @@ function contentPolicy(allowOrigins = []) {
|
|
|
112
128
|
].join("; ");
|
|
113
129
|
}
|
|
114
130
|
|
|
131
|
+
// src/host/panel.ts
|
|
132
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
133
|
+
var isNodeTree = (value) => isObject(value) && typeof value.key === "string" && typeof value.kind === "string" && Array.isArray(value.problems) && Array.isArray(value.children) && value.children.every(isNodeTree);
|
|
134
|
+
function checkSnapshot(payload) {
|
|
135
|
+
if (!isObject(payload) || !Array.isArray(payload.apps) || !payload.apps.every(isObject)) return void 0;
|
|
136
|
+
const structure = payload.structure ?? { nodes: [], usage: {} };
|
|
137
|
+
if (!isObject(structure) || !Array.isArray(structure.nodes) || !structure.nodes.every(isNodeTree) || !isObject(structure.usage ?? {})) return void 0;
|
|
138
|
+
return {
|
|
139
|
+
apps: payload.apps,
|
|
140
|
+
structure: { nodes: structure.nodes, usage: structure.usage ?? {} }
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function checkPicked(payload) {
|
|
144
|
+
if (!isObject(payload) || !(typeof payload.node === "string" || payload.node === null)) return void 0;
|
|
145
|
+
return { node: payload.node };
|
|
146
|
+
}
|
|
147
|
+
function createPanel(mount, options) {
|
|
148
|
+
let open = false;
|
|
149
|
+
let tab;
|
|
150
|
+
let selection = null;
|
|
151
|
+
let snapshot;
|
|
152
|
+
let picking = false;
|
|
153
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
154
|
+
const changed = () => listeners.forEach((listener) => {
|
|
155
|
+
try {
|
|
156
|
+
listener();
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
const setPicking = (on) => {
|
|
161
|
+
if (picking === on) return;
|
|
162
|
+
picking = on;
|
|
163
|
+
mount.emit("anfra.pick", on);
|
|
164
|
+
};
|
|
165
|
+
const setOpen = (value) => {
|
|
166
|
+
if (open === value) return;
|
|
167
|
+
open = value;
|
|
168
|
+
mount.emit("anfra.watch", value);
|
|
169
|
+
if (!value) {
|
|
170
|
+
setPicking(false);
|
|
171
|
+
selection = null;
|
|
172
|
+
snapshot = void 0;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const known = (id) => {
|
|
176
|
+
const tabs = options.tabs();
|
|
177
|
+
return id !== void 0 && tabs.includes(id) ? id : tab !== void 0 && tabs.includes(tab) ? tab : tabs[0];
|
|
178
|
+
};
|
|
179
|
+
const panel = {
|
|
180
|
+
get open() {
|
|
181
|
+
return open;
|
|
182
|
+
},
|
|
183
|
+
get tab() {
|
|
184
|
+
return tab;
|
|
185
|
+
},
|
|
186
|
+
get selection() {
|
|
187
|
+
return selection;
|
|
188
|
+
},
|
|
189
|
+
get snapshot() {
|
|
190
|
+
return snapshot;
|
|
191
|
+
},
|
|
192
|
+
get picking() {
|
|
193
|
+
return picking;
|
|
194
|
+
},
|
|
195
|
+
show(next, target) {
|
|
196
|
+
setOpen(true);
|
|
197
|
+
tab = known(next);
|
|
198
|
+
if (target !== void 0) {
|
|
199
|
+
selection = target;
|
|
200
|
+
if (target !== null) mount.emit("anfra.locate", { node: target });
|
|
201
|
+
}
|
|
202
|
+
changed();
|
|
203
|
+
},
|
|
204
|
+
hide() {
|
|
205
|
+
if (!open) return;
|
|
206
|
+
setOpen(false);
|
|
207
|
+
mount.emit("anfra.highlight", null);
|
|
208
|
+
changed();
|
|
209
|
+
},
|
|
210
|
+
toggle(next) {
|
|
211
|
+
if (open && (next === void 0 || next === tab)) panel.hide();
|
|
212
|
+
else panel.show(next);
|
|
213
|
+
},
|
|
214
|
+
select(node) {
|
|
215
|
+
selection = node;
|
|
216
|
+
setPicking(false);
|
|
217
|
+
changed();
|
|
218
|
+
},
|
|
219
|
+
highlight(node) {
|
|
220
|
+
mount.emit("anfra.highlight", node);
|
|
221
|
+
},
|
|
222
|
+
locate(target) {
|
|
223
|
+
mount.emit("anfra.locate", target);
|
|
224
|
+
},
|
|
225
|
+
pick(on) {
|
|
226
|
+
if (on && !open) {
|
|
227
|
+
setOpen(true);
|
|
228
|
+
tab = known(tab);
|
|
229
|
+
}
|
|
230
|
+
setPicking(on === true);
|
|
231
|
+
changed();
|
|
232
|
+
},
|
|
233
|
+
subscribe(listener) {
|
|
234
|
+
listeners.add(listener);
|
|
235
|
+
return () => {
|
|
236
|
+
listeners.delete(listener);
|
|
237
|
+
};
|
|
238
|
+
},
|
|
239
|
+
mountTab: (id, element) => options.mountTab(panel, id, element)
|
|
240
|
+
};
|
|
241
|
+
return {
|
|
242
|
+
panel,
|
|
243
|
+
snapshot(payload) {
|
|
244
|
+
if (!open) return;
|
|
245
|
+
const checked = checkSnapshot(payload);
|
|
246
|
+
if (!checked) return;
|
|
247
|
+
snapshot = checked;
|
|
248
|
+
changed();
|
|
249
|
+
},
|
|
250
|
+
picked(payload) {
|
|
251
|
+
if (!open) return;
|
|
252
|
+
const checked = checkPicked(payload);
|
|
253
|
+
if (!checked) return;
|
|
254
|
+
setPicking(false);
|
|
255
|
+
if (checked.node !== null) selection = checked.node;
|
|
256
|
+
mount.emit("anfra.highlight", null);
|
|
257
|
+
changed();
|
|
258
|
+
},
|
|
259
|
+
ready() {
|
|
260
|
+
if (open) mount.emit("anfra.watch", true);
|
|
261
|
+
if (picking) mount.emit("anfra.pick", true);
|
|
262
|
+
},
|
|
263
|
+
dispose() {
|
|
264
|
+
listeners.clear();
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// src/host/contributions.ts
|
|
270
|
+
function installContributions(plugins, own, keep) {
|
|
271
|
+
const commands = [];
|
|
272
|
+
const tabs = [];
|
|
273
|
+
const ids = /* @__PURE__ */ new Set();
|
|
274
|
+
const unique = (kind, id) => {
|
|
275
|
+
if (typeof id !== "string" || id === "") throw new Error(`A ${kind} needs an id.`);
|
|
276
|
+
if (ids.has(id)) throw new Error(`Two contributions are named '${id}'.`);
|
|
277
|
+
ids.add(id);
|
|
278
|
+
};
|
|
279
|
+
for (const plugin of plugins) {
|
|
280
|
+
for (const command of plugin.host?.commands ?? []) {
|
|
281
|
+
const id = `${plugin.name}.${command.id}`;
|
|
282
|
+
unique("command", id);
|
|
283
|
+
commands.push({ ...command, id, plugin: plugin.name });
|
|
284
|
+
}
|
|
285
|
+
for (const tab of plugin.host?.tabs ?? []) {
|
|
286
|
+
const id = `${plugin.name}.${tab.id}`;
|
|
287
|
+
unique("tab", id);
|
|
288
|
+
tabs.push({ ...tab, id, plugin: plugin.name });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
for (const command of own.commands ?? []) {
|
|
292
|
+
unique("command", command.id);
|
|
293
|
+
commands.push({ ...command });
|
|
294
|
+
}
|
|
295
|
+
for (const tab of own.tabs ?? []) {
|
|
296
|
+
unique("tab", tab.id);
|
|
297
|
+
tabs.push({ ...tab });
|
|
298
|
+
}
|
|
299
|
+
const order = new Map(tabs.map((tab, index) => [tab, index]));
|
|
300
|
+
tabs.sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || order.get(a) - order.get(b));
|
|
301
|
+
return {
|
|
302
|
+
commands: keep ? commands.filter((command) => keep({ kind: "command", command })) : commands,
|
|
303
|
+
tabs: keep ? tabs.filter((tab) => keep({ kind: "tab", tab })) : tabs
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function commandState(command, context, target) {
|
|
307
|
+
if (command.state) {
|
|
308
|
+
try {
|
|
309
|
+
return command.state(context, target) ?? {};
|
|
310
|
+
} catch {
|
|
311
|
+
return { disabled: "This command failed to report its state." };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if ("tab" in command.run) {
|
|
315
|
+
const { panel } = context;
|
|
316
|
+
const shown = panel.tab;
|
|
317
|
+
const pressed = panel.open && shown !== void 0 && (command.plugin ? shown.startsWith(`${command.plugin}.`) : shown === command.run.tab);
|
|
318
|
+
return { pressed };
|
|
319
|
+
}
|
|
320
|
+
return {};
|
|
321
|
+
}
|
|
322
|
+
|
|
115
323
|
// src/host/runtime.ts
|
|
116
324
|
var BODY_CALL = "anfra.body";
|
|
117
325
|
function matches(pattern, name) {
|
|
@@ -155,6 +363,8 @@ function createHost(options) {
|
|
|
155
363
|
...plugins.flatMap((plugin) => plugin.host?.middleware ?? [])
|
|
156
364
|
].sort((a, b) => (a.stage ?? 0) - (b.stage ?? 0) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
157
365
|
const bodies = new Map(plugins.flatMap((plugin) => plugin.frame?.body ? [[plugin.name, plugin.frame.body]] : []));
|
|
366
|
+
const ui = options.uiBody ?? builtUiBody();
|
|
367
|
+
if (ui) bodies.set("anfra", ui);
|
|
158
368
|
answers.set(BODY_CALL, {
|
|
159
369
|
plugin: "anfra",
|
|
160
370
|
definition: {
|
|
@@ -167,8 +377,49 @@ function createHost(options) {
|
|
|
167
377
|
}
|
|
168
378
|
}
|
|
169
379
|
});
|
|
380
|
+
const menus = /* @__PURE__ */ new WeakMap();
|
|
381
|
+
const menuOf = (mount) => {
|
|
382
|
+
const menu = mount && menus.get(mount);
|
|
383
|
+
if (!menu) throw new ValidationError("The menu is for a mounted Data App.");
|
|
384
|
+
return menu;
|
|
385
|
+
};
|
|
386
|
+
const targetOf = (request) => {
|
|
387
|
+
const target = checkTarget(request);
|
|
388
|
+
if (!target) throw new ValidationError("Not a menu target.");
|
|
389
|
+
return target;
|
|
390
|
+
};
|
|
391
|
+
answers.set("anfra.menu", {
|
|
392
|
+
plugin: "anfra",
|
|
393
|
+
definition: { frame: true, handler: (request, { mount }) => menuOf(mount).entries(targetOf(request)) }
|
|
394
|
+
});
|
|
395
|
+
answers.set("anfra.run", {
|
|
396
|
+
plugin: "anfra",
|
|
397
|
+
definition: {
|
|
398
|
+
frame: true,
|
|
399
|
+
handler: (request, { mount }) => {
|
|
400
|
+
const id = request?.id;
|
|
401
|
+
if (typeof id !== "string") throw new ValidationError("Name the command to run.");
|
|
402
|
+
return menuOf(mount).run(id, targetOf(request.target));
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
});
|
|
170
406
|
const events = new Map(plugins.flatMap((plugin) => Object.entries(plugin.host?.events ?? {}).map(([name, check]) => [`${plugin.name}.${name}`, check])));
|
|
171
407
|
const infos = plugins.map(({ name, version }) => ({ name, version }));
|
|
408
|
+
const { commands, tabs } = installContributions(plugins, options, options.contributions);
|
|
409
|
+
let theme = resolveTheme(options.theme);
|
|
410
|
+
const themeListeners = /* @__PURE__ */ new Set();
|
|
411
|
+
const tabIds = tabs.map((tab) => tab.id);
|
|
412
|
+
const menuKinds = [...new Set(commands.flatMap((command) => command.target ? [command.target] : []))];
|
|
413
|
+
const byShortcut = /* @__PURE__ */ new Map();
|
|
414
|
+
for (const command of commands) {
|
|
415
|
+
if (command.shortcut === void 0) continue;
|
|
416
|
+
const shortcut = normalizeShortcut(command.shortcut);
|
|
417
|
+
if (!shortcut) throw new Error(`Command '${command.id}' has a shortcut that isn't one: '${command.shortcut}'.`);
|
|
418
|
+
if (command.target) throw new Error(`Command '${command.id}' is for the menu on the page, which has no shortcuts.`);
|
|
419
|
+
const other = byShortcut.get(shortcut);
|
|
420
|
+
if (other) throw new Error(`Commands '${other}' and '${command.id}' have the same shortcut, '${command.shortcut}'.`);
|
|
421
|
+
byShortcut.set(shortcut, command.id);
|
|
422
|
+
}
|
|
172
423
|
let nextMount = 1;
|
|
173
424
|
function dispatch(name, request, callers, mount, signal, asOrigin = false) {
|
|
174
425
|
const answer = answers.get(name);
|
|
@@ -214,8 +465,23 @@ function createHost(options) {
|
|
|
214
465
|
if (!answers.has(name) && mount) return mount.call(name, request, { signal });
|
|
215
466
|
return dispatch(name, request, callers, mount, signal, callOptions.asOrigin === true);
|
|
216
467
|
}
|
|
468
|
+
const callersOf = (plugin) => plugin ? [{ kind: "host" }, { kind: "plugin", plugin }] : [{ kind: "host" }];
|
|
217
469
|
return {
|
|
218
470
|
plugins: infos,
|
|
471
|
+
commands,
|
|
472
|
+
tabs,
|
|
473
|
+
get theme() {
|
|
474
|
+
return theme;
|
|
475
|
+
},
|
|
476
|
+
setTheme(input) {
|
|
477
|
+
theme = resolveTheme(input);
|
|
478
|
+
themeListeners.forEach((listener) => {
|
|
479
|
+
try {
|
|
480
|
+
listener(theme);
|
|
481
|
+
} catch {
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
},
|
|
219
485
|
call: (name, request, callOptions) => call(name, request, [{ kind: "host" }], void 0, callOptions),
|
|
220
486
|
mount(mountOptions) {
|
|
221
487
|
const frameScript = options.frameScript ?? builtFrameScript();
|
|
@@ -228,6 +494,13 @@ function createHost(options) {
|
|
|
228
494
|
mountOptions.container.appendChild(frame);
|
|
229
495
|
const listeners = /* @__PURE__ */ new Map();
|
|
230
496
|
const readyListeners = /* @__PURE__ */ new Set();
|
|
497
|
+
const commandListeners = /* @__PURE__ */ new Set();
|
|
498
|
+
const commandsChanged = () => commandListeners.forEach((listener) => {
|
|
499
|
+
try {
|
|
500
|
+
listener();
|
|
501
|
+
} catch {
|
|
502
|
+
}
|
|
503
|
+
});
|
|
231
504
|
const listen = (set, listener) => {
|
|
232
505
|
set.add(listener);
|
|
233
506
|
return () => {
|
|
@@ -240,17 +513,32 @@ function createHost(options) {
|
|
|
240
513
|
id: nextMount++,
|
|
241
514
|
frame,
|
|
242
515
|
document: doc,
|
|
516
|
+
user: mountOptions.user,
|
|
517
|
+
datasets: mountOptions.datasets,
|
|
243
518
|
call: (name, request, callOptions) => endpoint.call(name, request, callOptions?.signal),
|
|
244
519
|
emit: (name, payload) => endpoint.emit(name, payload),
|
|
245
520
|
on(name, listener) {
|
|
246
521
|
if (!listeners.has(name)) listeners.set(name, /* @__PURE__ */ new Set());
|
|
247
522
|
return listen(listeners.get(name), listener);
|
|
248
523
|
},
|
|
249
|
-
onReady: (listener) => listen(readyListeners, listener)
|
|
524
|
+
onReady: (listener) => listen(readyListeners, listener),
|
|
525
|
+
commandsChanged
|
|
250
526
|
};
|
|
251
527
|
endpoint = createEndpoint(post, {
|
|
252
528
|
answer: (name, request, signal) => dispatch(name, request, [{ kind: "frame" }], context, signal),
|
|
253
529
|
event: (name, payload) => {
|
|
530
|
+
if (name === "anfra.snapshot") {
|
|
531
|
+
panelState.snapshot(payload);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if (name === "anfra.picked") {
|
|
535
|
+
panelState.picked(payload);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (name === "anfra.shortcut") {
|
|
539
|
+
runShortcut(payload, "key");
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
254
542
|
const check = events.get(name);
|
|
255
543
|
if (!check || !listeners.has(name)) return;
|
|
256
544
|
let checked;
|
|
@@ -268,10 +556,77 @@ function createHost(options) {
|
|
|
268
556
|
});
|
|
269
557
|
}
|
|
270
558
|
});
|
|
559
|
+
const panelState = createPanel(context, {
|
|
560
|
+
tabs: () => tabIds,
|
|
561
|
+
mountTab(panel, id, element) {
|
|
562
|
+
const tab = tabs.find((candidate) => candidate.id === id);
|
|
563
|
+
if (!tab) throw new Error(`No tab '${id}' is installed.`);
|
|
564
|
+
const root = element.shadowRoot ?? element.attachShadow({ mode: "open" });
|
|
565
|
+
applyTheme(element.style, theme);
|
|
566
|
+
const themed = (next) => applyTheme(element.style, next);
|
|
567
|
+
themeListeners.add(themed);
|
|
568
|
+
let disposed = false;
|
|
569
|
+
let cleanup;
|
|
570
|
+
const done = (result) => {
|
|
571
|
+
if (disposed) {
|
|
572
|
+
if (typeof result === "function") result();
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
cleanup = result;
|
|
576
|
+
};
|
|
577
|
+
try {
|
|
578
|
+
const result = tab.mount(root, {
|
|
579
|
+
tab: id,
|
|
580
|
+
panel,
|
|
581
|
+
mount: context,
|
|
582
|
+
plugins: infos,
|
|
583
|
+
document: doc,
|
|
584
|
+
get theme() {
|
|
585
|
+
return theme;
|
|
586
|
+
},
|
|
587
|
+
call: (name, request, callOptions) => call(name, request, callersOf(tab.plugin), context, callOptions)
|
|
588
|
+
});
|
|
589
|
+
if (result instanceof Promise) result.then(done, (err) => win.console?.error(`anfra: tab '${id}' failed to draw:`, err));
|
|
590
|
+
else done(result);
|
|
591
|
+
} catch (err) {
|
|
592
|
+
win.console?.error(`anfra: tab '${id}' failed to draw:`, err);
|
|
593
|
+
}
|
|
594
|
+
return () => {
|
|
595
|
+
if (disposed) return;
|
|
596
|
+
disposed = true;
|
|
597
|
+
themeListeners.delete(themed);
|
|
598
|
+
try {
|
|
599
|
+
if (typeof cleanup === "function") cleanup();
|
|
600
|
+
} catch {
|
|
601
|
+
}
|
|
602
|
+
root.replaceChildren();
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
panelState.panel.subscribe(commandsChanged);
|
|
607
|
+
const sendTheme = (next) => context.emit("anfra.theme", next);
|
|
608
|
+
themeListeners.add(sendTheme);
|
|
609
|
+
const stateContext = { mount: context, panel: panelState.panel };
|
|
610
|
+
const runShortcut = (shortcut, from = "host") => {
|
|
611
|
+
const id = typeof shortcut === "string" ? byShortcut.get(shortcut) : void 0;
|
|
612
|
+
if (!id) return false;
|
|
613
|
+
runCommand(id, void 0, from).catch(() => {
|
|
614
|
+
});
|
|
615
|
+
return true;
|
|
616
|
+
};
|
|
617
|
+
const commandOf = (id) => {
|
|
618
|
+
const command = commands.find((candidate) => candidate.id === id);
|
|
619
|
+
if (!command) throw new Error(`No command '${id}' is installed.`);
|
|
620
|
+
return command;
|
|
621
|
+
};
|
|
271
622
|
const onMessage = (event) => {
|
|
272
623
|
if (event.source !== frame.contentWindow) return;
|
|
273
624
|
const message = event.data;
|
|
274
625
|
if (message?.type === "anfra:ready") {
|
|
626
|
+
context.emit("anfra.theme", theme);
|
|
627
|
+
if (menuKinds.length) context.emit("anfra.menu", { kinds: menuKinds });
|
|
628
|
+
if (byShortcut.size) context.emit("anfra.shortcuts", [...byShortcut.keys()]);
|
|
629
|
+
panelState.ready();
|
|
275
630
|
readyListeners.forEach((listener) => listener());
|
|
276
631
|
return;
|
|
277
632
|
}
|
|
@@ -294,12 +649,60 @@ function createHost(options) {
|
|
|
294
649
|
frameScript,
|
|
295
650
|
setups: plugins.flatMap((plugin) => plugin.frame ? [{ name: plugin.name, setup: plugin.frame.setup }] : [])
|
|
296
651
|
});
|
|
652
|
+
const runCommand = async (id, target, from = "host") => {
|
|
653
|
+
const command = commandOf(id);
|
|
654
|
+
if (command.target && target?.kind !== command.target) throw new ValidationError(`'${id}' runs from the menu on the page, with a ${command.target} target.`);
|
|
655
|
+
const { disabled, pressed } = commandState(command, stateContext, target);
|
|
656
|
+
if (disabled) throw new PermissionError(disabled);
|
|
657
|
+
if ("tab" in command.run) {
|
|
658
|
+
const node = target ? (target.kind === "node" ? target : target.node)?.node.key : void 0;
|
|
659
|
+
const selected = node ?? command.run.target;
|
|
660
|
+
if (selected !== void 0) panelState.panel.show(command.run.tab, selected);
|
|
661
|
+
else if (pressed) panelState.panel.hide();
|
|
662
|
+
else panelState.panel.show(command.run.tab);
|
|
663
|
+
return null;
|
|
664
|
+
}
|
|
665
|
+
const request = target ? { ...command.run.request ?? {}, target } : command.run.request ?? null;
|
|
666
|
+
const callers = from === "host" ? callersOf(command.plugin) : [{ kind: "frame" }, ...callersOf(command.plugin)];
|
|
667
|
+
return call(command.run.call, request, callers, context, { asOrigin: from === "key" });
|
|
668
|
+
};
|
|
669
|
+
menus.set(context, {
|
|
670
|
+
entries: (target) => menuFor(target),
|
|
671
|
+
// Picked in the frame: the command's call keeps the frame as its origin.
|
|
672
|
+
run: (id, target) => {
|
|
673
|
+
if (!commandOf(id).target) return Promise.reject(new PermissionError(`'${id}' isn't a menu command.`));
|
|
674
|
+
return runCommand(id, target, "menu");
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
const menuFor = (target) => commands.flatMap((command) => {
|
|
678
|
+
if (command.target !== target.kind) return [];
|
|
679
|
+
try {
|
|
680
|
+
if (command.when && !command.when(target, stateContext)) return [];
|
|
681
|
+
} catch {
|
|
682
|
+
return [];
|
|
683
|
+
}
|
|
684
|
+
const { disabled } = commandState(command, stateContext, target);
|
|
685
|
+
return [{ id: command.id, label: command.title, ...disabled ? { disabled } : {} }];
|
|
686
|
+
});
|
|
297
687
|
return {
|
|
298
688
|
frame,
|
|
299
689
|
call: (name, request, callOptions) => call(name, request, [{ kind: "host" }], context, callOptions),
|
|
300
690
|
emit: context.emit,
|
|
301
691
|
on: context.on,
|
|
692
|
+
panel: panelState.panel,
|
|
693
|
+
commandState: (id) => commandState(commandOf(id), stateContext),
|
|
694
|
+
run: (id) => runCommand(id),
|
|
695
|
+
onCommandsChange: (listener) => listen(commandListeners, listener),
|
|
696
|
+
handleKeydown(event) {
|
|
697
|
+
if (event.defaultPrevented || event.repeat || isTyping(event.target)) return false;
|
|
698
|
+
if (!runShortcut(eventShortcut(event))) return false;
|
|
699
|
+
event.preventDefault();
|
|
700
|
+
return true;
|
|
701
|
+
},
|
|
302
702
|
unmount() {
|
|
703
|
+
themeListeners.delete(sendTheme);
|
|
704
|
+
commandListeners.clear();
|
|
705
|
+
panelState.dispose();
|
|
303
706
|
win.removeEventListener("message", onMessage);
|
|
304
707
|
endpoint.close(new ValidationError("The Data App was unmounted before the call finished."));
|
|
305
708
|
disposers.forEach((dispose) => dispose());
|