@holistics/anfra-sdk 0.10.1 → 0.11.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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * What a plugin is, the host's side: a name, a version, the plugins it needs, a host half that
3
+ * answers its calls, and the frame half's code. See docs/designs/sdk-plugins.md.
4
+ */
5
+ /** Who made a call. Middleware and handlers can tell the definition's calls from a plugin's. */
6
+ type Caller =
7
+ /** The Data App's frame: its definition, or a plugin's frame half there. */
8
+ {
9
+ kind: 'frame';
10
+ }
11
+ /** The host page's own code, through `Host.call` or `MountedDataApp.call`. */
12
+ | {
13
+ kind: 'host';
14
+ }
15
+ /** Another plugin's host half, by its name. */
16
+ | {
17
+ kind: 'plugin';
18
+ plugin: string;
19
+ };
20
+ interface CallOptions {
21
+ signal?: AbortSignal;
22
+ }
23
+ /** One call, as its handler and each middleware see it. */
24
+ interface CallContext {
25
+ /** The call's full name, `<plugin>.<name>`. */
26
+ readonly name: string;
27
+ readonly caller: Caller;
28
+ /**
29
+ * Who led to this call, outermost first, ending with `caller`: a query an agent plugin runs for
30
+ * the frame's prompt is `[frame, plugin agent]`. Decide by it, or by `origin`, what a call started
31
+ * by the frame may do, since a plugin's call made for the frame has the plugin as its `caller`.
32
+ */
33
+ readonly chain: readonly Caller[];
34
+ /** Who started the chain: the frame, or the host (`chain[0]`). */
35
+ readonly origin: Caller;
36
+ /** Aborts when the caller cancels. */
37
+ readonly signal: AbortSignal;
38
+ /** The frame the call is about: the one that made it, or the one the host named. */
39
+ readonly mount?: MountContext;
40
+ /** The middleware the call has passed through so far, by name, outermost first. */
41
+ readonly trace: readonly string[];
42
+ }
43
+ interface HandlerCallOptions extends CallOptions {
44
+ /**
45
+ * Hold the call to what this chain's origin may call: started by the frame, it is refused unless
46
+ * the frame could make it itself. For a handler that forwards a call, or a request, the frame
47
+ * chose, so the plugin can't be made to make a host-only call for it.
48
+ */
49
+ asOrigin?: boolean;
50
+ }
51
+ /** What a plugin's handler gets: the call, and a way to make calls of its own as that plugin. */
52
+ interface HandlerContext extends CallContext {
53
+ /**
54
+ * Make another plugin's call, through the same pipeline, as this plugin, about the same frame. It
55
+ * carries this call's chain, with this plugin added.
56
+ */
57
+ call: <T = unknown>(name: string, request?: unknown, options?: HandlerCallOptions) => Promise<T>;
58
+ }
59
+ type CallHandler = (request: any, context: HandlerContext) => unknown;
60
+ interface CallDefinition {
61
+ handler: CallHandler;
62
+ /** Whether a frame may make this call. Off unless true: a call is the host's until its plugin says. */
63
+ frame?: boolean;
64
+ }
65
+ /**
66
+ * Code around calls, chosen by name: `*`, `<plugin>.*`, or one call's full name. It may change the
67
+ * request, answer in place of the plugin (not calling `next`), refuse the call (throwing), or change
68
+ * the answer. Every call passes through it, whoever made it. A plugin's middleware is as powerful as
69
+ * the host's: it sees and may change every call on the page, not only its plugin's.
70
+ */
71
+ interface Middleware {
72
+ /** Names the middleware in a call's trace, and orders it among middleware of the same stage. */
73
+ name: string;
74
+ match: string | readonly string[];
75
+ /** Lower runs first (outermost). 0 unless given. Ties are ordered by name, never by registration. */
76
+ stage?: number;
77
+ handle: (request: unknown, context: CallContext, next: (request?: unknown) => Promise<unknown>) => unknown;
78
+ }
79
+ /** One mounted frame, as a plugin's host half sees it. */
80
+ interface MountContext {
81
+ readonly id: number;
82
+ readonly frame: HTMLIFrameElement;
83
+ /** The host page's document, where the frame is. */
84
+ readonly document: Document;
85
+ /** Make a call a frame half answers, in this frame. */
86
+ call: <T = unknown>(name: string, request?: unknown, options?: CallOptions) => Promise<T>;
87
+ /** Send this frame an event. */
88
+ emit: (name: string, payload?: unknown) => void;
89
+ /** Listen to this frame's events, by full name. Returns the function that stops listening. */
90
+ on: (name: string, listener: (payload: any) => void) => () => void;
91
+ /** Each time the frame's document (re)loads and its kernel runs. */
92
+ onReady: (listener: () => void) => () => void;
93
+ }
94
+ /**
95
+ * Checks one of a frame's events before the host hears it: what it returns is what listeners get,
96
+ * and `undefined` drops the event. A frame's events are as untrusted as its calls.
97
+ */
98
+ type EventCheck = (payload: unknown, mount: MountContext) => unknown;
99
+ interface HostHalf {
100
+ /** The calls this plugin answers, by their name under the plugin (`submitQuery`, not `core.submitQuery`). */
101
+ calls?: Record<string, CallHandler | CallDefinition>;
102
+ /**
103
+ * The events a frame may send under this plugin's name (`snapshot`, not `inspect.snapshot`), each
104
+ * with its check. An event no installed plugin declares never reaches the host.
105
+ */
106
+ events?: Record<string, EventCheck>;
107
+ /** Middleware this plugin puts around calls, its own or others'. */
108
+ middleware?: readonly Middleware[];
109
+ /** Each time a frame is mounted. What it returns runs when the frame is unmounted. */
110
+ mount?: (mount: MountContext) => void | (() => void);
111
+ }
112
+ /** A frame half: code the host provisions into the frame, as script source (docs/designs/sdk-plugins.md). */
113
+ interface FrameHalf {
114
+ /** Runs before the definition, once per document: registers the plugin's API. */
115
+ setup: string;
116
+ /** Loaded on first use, through the kernel. */
117
+ body?: string;
118
+ }
119
+ interface Plugin {
120
+ /** Lowercase letters, digits and dashes, starting with a letter. Names its calls, events and API. */
121
+ name: string;
122
+ version: string;
123
+ /** Plugins this one needs; installing it without them fails. */
124
+ requires?: readonly string[];
125
+ host?: HostHalf;
126
+ frame?: FrameHalf;
127
+ }
128
+ /** A plugin, checked (`checkPlugin`). A host checks every plugin it installs anyway. */
129
+ declare function definePlugin<P extends Plugin>(plugin: P): P;
130
+
131
+ export { type CallOptions as C, type EventCheck as E, type FrameHalf as F, type HandlerCallOptions as H, type Middleware as M, type Plugin as P, type CallContext as a, type CallDefinition as b, type CallHandler as c, type Caller as d, type HandlerContext as e, type HostHalf as f, type MountContext as g, definePlugin as h };
@@ -0,0 +1,52 @@
1
+ import { B as Backend } from './types-BTyDyld7.js';
2
+ import { P as Plugin } from './plugin-C5cihcQD.js';
3
+
4
+ /**
5
+ * `core`: running a Data App's queries and suggesting a filter's values. Every host installs it:
6
+ * the app model makes its calls, through the pipeline like any caller, so a host swaps or wraps it
7
+ * as it would any plugin's. No frame half: the kernel is its frame side.
8
+ */
9
+
10
+ /** What `core` answers with: a Backend's two required methods, `coreApiBackend` on any host. */
11
+ type CoreBackend = Pick<Backend, 'submitQuery' | 'fieldSuggestions'>;
12
+ declare function corePlugin(backend: CoreBackend): Plugin;
13
+
14
+ /**
15
+ * `export`: a query's whole result as a file (`query.export()`), made by the host's Backend and
16
+ * saved for the reader from the host's page, since the frame has no `allow-downloads`.
17
+ */
18
+
19
+ /** `backend` must have `exportQuery` (`coreApiBackend` does). */
20
+ declare function exportPlugin(backend: Pick<Backend, 'exportQuery'>): Plugin;
21
+
22
+ /** `lineage`: tracing fields through the repo's catalog (`Anfra.lineage()`). */
23
+
24
+ /** `backend` must have `lineage` (`coreApiBackend` does). */
25
+ declare function lineagePlugin(backend: Pick<Backend, 'lineage'>): Plugin;
26
+
27
+ /**
28
+ * The name a picture is saved under: the frame's, without what a file system or a reader would
29
+ * misread (control characters, path separators), ending in the extension its bytes call for. A
30
+ * name that pretends otherwise (`report.pdf.exe`) keeps its words and gets the real extension.
31
+ */
32
+ declare function pictureFilename(filename: unknown, ext: string): string;
33
+ interface RenderPluginOptions {
34
+ /** The renderer's script; the one built into this package unless given (tests). */
35
+ renderer?: string;
36
+ }
37
+ /**
38
+ * Installing it is the host's opt-in to rendering: it has the host save a file the frame made
39
+ * (docs/designs/data-apps.md, Renderings).
40
+ */
41
+ declare function renderPlugin(options?: RenderPluginOptions): Plugin;
42
+
43
+ /**
44
+ * `inspect`: what the host's inspect panel needs of a frame. While the host watches, the frame posts
45
+ * a snapshot of its apps and its structure (`inspect.snapshot`) on each change; the host can
46
+ * highlight a node, locate a node or an entity, and turn pick mode on, where a click reports a node
47
+ * (`inspect.picked`). Calls the host page makes, never the frame.
48
+ */
49
+
50
+ declare function inspectPlugin(): Plugin;
51
+
52
+ export { type CoreBackend, type RenderPluginOptions, corePlugin, exportPlugin, inspectPlugin, lineagePlugin, pictureFilename, renderPlugin };
@@ -0,0 +1,233 @@
1
+ import {
2
+ definePlugin
3
+ } from "./chunk-TQ7S5DRE.js";
4
+ import {
5
+ version
6
+ } from "./chunk-ENWRS6AT.js";
7
+ import {
8
+ ValidationError
9
+ } from "./chunk-KCTLO3CO.js";
10
+ import "./chunk-PKBMQBKP.js";
11
+
12
+ // src/plugins/version.ts
13
+ var PLUGIN_VERSION = version;
14
+
15
+ // src/plugins/core/index.ts
16
+ function corePlugin(backend) {
17
+ return definePlugin({
18
+ name: "core",
19
+ version: PLUGIN_VERSION,
20
+ host: {
21
+ calls: {
22
+ submitQuery: { frame: true, handler: (request, { signal }) => backend.submitQuery(request, signal) },
23
+ fieldSuggestions: { frame: true, handler: (request, { signal }) => backend.fieldSuggestions(request, signal) }
24
+ }
25
+ }
26
+ });
27
+ }
28
+
29
+ // anfra-sdk:anfra-sdk:setup/export
30
+ var export_default = '"use strict";var __anfraPlugin=(()=>{var n=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var a=(r,e)=>n(r,"name",{value:e,configurable:!0});var y=(r,e)=>{for(var p in e)n(r,p,{get:e[p],enumerable:!0})},d=(r,e,p,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of x(e))!f.call(r,t)&&t!==p&&n(r,t,{get:()=>e[t],enumerable:!(o=u(e,t))||o.enumerable});return r};var l=r=>d(n({},"__esModule",{value:!0}),r);var E={};y(E,{default:()=>m});function m(r){r.provideOnQuery(e=>(p={})=>{let o=r.sdk.apps.find(t=>t.queries[e.name]===e);return o?o.exportQuery(e,p,(t,s)=>r.call("export.query",t,s).then(i=>(i.expiresAt=new Date(i.expiresAt),i))):Promise.reject(new r.errors.ValidationError(`Query \'${e.name}\' belongs to no app.`,e.name))})}a(m,"setup");return l(E);})();\n';
31
+
32
+ // src/plugins/export/index.ts
33
+ function saveLink(doc, link) {
34
+ const a = doc.createElement("a");
35
+ a.href = link.url;
36
+ a.download = link.filename;
37
+ a.rel = "noopener";
38
+ a.style.display = "none";
39
+ doc.body.appendChild(a);
40
+ a.click();
41
+ a.remove();
42
+ }
43
+ function exportPlugin(backend) {
44
+ const { exportQuery } = backend;
45
+ if (typeof exportQuery !== "function") throw new Error("exportPlugin: the Backend has no exportQuery.");
46
+ return definePlugin({
47
+ name: "export",
48
+ version: PLUGIN_VERSION,
49
+ requires: ["core"],
50
+ host: {
51
+ calls: {
52
+ /** Make the export, start saving it, then answer its link. */
53
+ query: {
54
+ frame: true,
55
+ async handler(request, { signal, mount }) {
56
+ const link = await exportQuery.call(backend, request, signal);
57
+ saveLink(mount?.document ?? document, link);
58
+ return link;
59
+ }
60
+ }
61
+ }
62
+ },
63
+ frame: { setup: export_default }
64
+ });
65
+ }
66
+
67
+ // anfra-sdk:anfra-sdk:setup/lineage
68
+ var lineage_default = `"use strict";var __anfraPlugin=(()=>{var o=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var s=(e,n)=>o(e,"name",{value:n,configurable:!0});var L=(e,n)=>{for(var t in n)o(e,t,{get:n[t],enumerable:!0})},h=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of d(n))!y.call(e,a)&&a!==t&&o(e,a,{get:()=>n[a],enumerable:!(i=f(n,a))||i.enumerable});return e};var T=e=>h(o({},"__esModule",{value:!0}),e);var v={};L(v,{default:()=>p});function p(e){function n(t,i={}){let a=Array.isArray(t)?[...t]:[t],g=s(r=>typeof r=="string"&&r.trim()!=="","named");if(a.length===0||a.some(r=>typeof r!="object"||r===null||!g(r.parent)||!g(r.child)))return Promise.reject(new e.errors.ValidationError("Anfra.lineage() takes a target or an array of targets, each by its parent and its name in it, such as { parent: 'ecommerce', child: 'revenue' }."));let{limit:l,offset:m,signal:c}=i;return e.call("lineage.trace",{targets:a.map(({parent:r,child:u})=>({parent:r,child:u})),...l!==void 0?{limit:l}:{},...m!==void 0?{offset:m}:{}},c)}s(n,"lineage"),e.provide(n)}s(p,"setup");return T(v);})();
69
+ `;
70
+
71
+ // src/plugins/lineage/index.ts
72
+ function lineagePlugin(backend) {
73
+ const { lineage } = backend;
74
+ if (typeof lineage !== "function") throw new Error("lineagePlugin: the Backend has no lineage.");
75
+ return definePlugin({
76
+ name: "lineage",
77
+ version: PLUGIN_VERSION,
78
+ host: {
79
+ calls: {
80
+ trace: { frame: true, handler: (request, { signal }) => lineage.call(backend, request, signal) }
81
+ }
82
+ },
83
+ frame: { setup: lineage_default }
84
+ });
85
+ }
86
+
87
+ // anfra-sdk:anfra-sdk:setup/render
88
+ var render_default = '"use strict";var __anfraPlugin=(()=>{var p=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var i=(e,t)=>p(e,"name",{value:t,configurable:!0});var $=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},E=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of R(t))!w.call(e,a)&&a!==n&&p(e,a,{get:()=>t[a],enumerable:!(o=k(t,a))||o.enumerable});return e};var A=e=>E(p({},"__esModule",{value:!0}),e);var O={};$(O,{SETTLE_MS:()=>b,SKIP_ATTRIBUTE:()=>f,createRender:()=>g,default:()=>h,settle:()=>y});var S="data-anfra-layer";function m(e){return e.hasAttribute(S)}i(m,"isLayer");var c={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},F=`[${c.container}],[${c.block}],[${c.query}],[${c.control}]`;var f="data-anfra-render",x={png:"png",pdf:"pdf"},b=1e4;function T(e,t,n,o){let a=x[e.format],r=e.filename?.trim();if(!r){let s=n.find(d=>d.title)?.title||t.title.trim()||"Data App",l=o&&(o.getAttribute(c.label)||e.block||e.container);r=l?`${s} - ${l}`:s}return r=r.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim()||"Data App",r.toLowerCase().endsWith(`.${a}`)?r:`${r}.${a}`}i(T,"filenameFor");function v(e,t,{ValidationError:n}){if(e.block!==void 0&&e.container!==void 0)throw new n("Render a block or a container, not both.",e.block);if(e.format!=="png"&&e.format!=="pdf")throw new n(`Can\'t render as \'${String(e.format)}\': the formats are \'png\' and \'pdf\'.`);let{pixelRatio:o}=e;if(o!==void 0&&!(Number.isFinite(o)&&o>0))throw new n(`pixelRatio ${String(o)} is not a positive number.`);let a=e.block!==void 0?"block":e.container!==void 0?"container":void 0;if(!a)return{element:null};let r=e.block??e.container,s=[...t.querySelectorAll(`[${c[a]}]`)].find(l=>l.getAttribute(c[a])===r);if(!s)throw new n(`No element is marked ${c[a]}="${r}" on the page.`,r);return{element:s,entity:r}}i(v,"targetOf");function L(e){return m(e)||e.getAttribute(f)==="skip"}i(L,"skip");function g(e,t){let{ValidationError:n}=t.errors;return async o=>{let a=e.document,{element:r,entity:s}=v(o??{},a,t.errors),l=T(o,a,t.apps(),r);try{let u=await(await t.renderer()).draw(r,{format:o.format,pixelRatio:o.pixelRatio,skip:L});return await t.saveFile({blob:u.blob,filename:l}),{filename:l,format:o.format,...u}}catch(d){throw d instanceof n&&d.entity?d:new n(d?.message||"The rendering failed.",s)}}}i(g,"createRender");async function y(e,t,n=b){let o=i(()=>t().some(r=>Object.values(r.queries).some(s=>s.state==="executing")),"busy"),a=Date.now()+n;for(;o()&&Date.now()<a;)await new Promise(r=>{e.setTimeout(r,100)});await new Promise(r=>{e.requestAnimationFrame(()=>r(void 0))})}i(y,"settle");function h(e){let t=g(e.window,{renderer:i(()=>e.body(),"renderer"),saveFile:i(n=>e.call("render.save",n),"saveFile"),apps:i(()=>e.sdk.apps,"apps"),errors:e.errors});e.provide(n=>t(n)),e.handle("draw",n=>y(e.window,()=>e.sdk.apps).then(()=>t(n)))}i(h,"setup");return A(O);})();\n';
89
+
90
+ // anfra-sdk:anfra-sdk:body/render
91
+ var render_default2 = '"use strict";var __anfraBody=(()=>{var $=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var i=(e,t)=>$(e,"name",{value:t,configurable:!0});var me=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},he=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ue(t))!fe.call(e,o)&&o!==n&&$(e,o,{get:()=>t[o],enumerable:!(r=le(t,o))||r.enumerable});return e};var ge=e=>he($({},"__esModule",{value:!0}),e);var it={};me(it,{default:()=>ce});function H(e,t){if(e.match(/^[a-z]+:\\/\\//i))return e;if(e.match(/^\\/\\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;let n=document.implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}i(H,"resolveUrl");var V=(()=>{let e=0,t=i(()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4),"random");return()=>(e+=1,`u${t()}${e}`)})();function p(e){let t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}i(p,"toArray");var b=null;function L(e={}){return b||(e.includeStyleProperties?(b=e.includeStyleProperties,b):(b=p(window.getComputedStyle(document.documentElement)),b))}i(L,"getStyleProperties");function D(e,t){let r=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}i(D,"px");function de(e){let t=D(e,"border-left-width"),n=D(e,"border-right-width");return e.clientWidth+t+n}i(de,"getNodeWidth");function pe(e){let t=D(e,"border-top-width"),n=D(e,"border-bottom-width");return e.clientHeight+t+n}i(pe,"getNodeHeight");function I(e,t={}){let n=t.width||de(e),r=t.height||pe(e);return{width:n,height:r}}i(I,"getImageSize");function W(){let e,t;try{t=process}catch{}let n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}i(W,"getPixelRatio");var g=16384;function _(e){(e.width>g||e.height>g)&&(e.width>g&&e.height>g?e.width>e.height?(e.height*=g/e.width,e.width=g):(e.width*=g/e.height,e.height=g):e.width>g?(e.height*=g/e.width,e.width=g):(e.width*=g/e.height,e.height=g))}i(_,"checkCanvasDimensions");function x(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}i(x,"createImage");async function ye(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}i(ye,"svgToDataURL");async function j(e,t,n){let r="http://www.w3.org/2000/svg",o=document.createElementNS(r,"svg"),a=document.createElementNS(r,"foreignObject");return o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.setAttribute("viewBox",`0 0 ${t} ${n}`),a.setAttribute("width","100%"),a.setAttribute("height","100%"),a.setAttribute("x","0"),a.setAttribute("y","0"),a.setAttribute("externalResourcesRequired","true"),o.appendChild(a),a.appendChild(e),ye(o)}i(j,"nodeToDataURL");var m=i((e,t)=>{if(e instanceof t)return!0;let n=Object.getPrototypeOf(e);return n===null?!1:n.constructor.name===t.name||m(n,t)},"isInstanceOfElement");function we(e){let t=e.getPropertyValue("content");return`${e.cssText} content: \'${t.replace(/\'|"/g,"")}\';`}i(we,"formatCSSText");function be(e,t){return L(t).map(n=>{let r=e.getPropertyValue(n),o=e.getPropertyPriority(n);return`${n}: ${r}${o?" !important":""};`}).join(" ")}i(be,"formatCSSProperties");function xe(e,t,n,r){let o=`.${e}:${t}`,a=n.cssText?we(n):be(n,r);return document.createTextNode(`${o}{${a}}`)}i(xe,"getPseudoElementStyle");function q(e,t,n,r){let o=window.getComputedStyle(e,n),a=o.getPropertyValue("content");if(a===""||a==="none")return;let s=V();try{t.className=`${t.className} ${s}`}catch{return}let c=document.createElement("style");c.appendChild(xe(s,n,o,r)),t.appendChild(c)}i(q,"clonePseudoElement");function z(e,t,n){q(e,t,":before",n),q(e,t,":after",n)}i(z,"clonePseudoElements");var G="application/font-woff",X="image/jpeg",Se={woff:G,woff2:G,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:X,jpeg:X,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Ee(e){let t=/\\.([^./]*?)$/g.exec(e);return t?t[1]:""}i(Ee,"getExtension");function S(e){let t=Ee(e).toLowerCase();return Se[t]||""}i(S,"getMimeType");function Re(e){return e.split(/,/)[1]}i(Re,"getContentFromDataUrl");function C(e){return e.search(/^(data:)/)!==-1}i(C,"isDataUrl");function v(e,t){return`data:${t};base64,${e}`}i(v,"makeDataUrl");async function k(e,t,n){let r=await fetch(e,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);let o=await r.blob();return new Promise((a,s)=>{let c=new FileReader;c.onerror=s,c.onloadend=()=>{try{a(n({res:r,result:c.result}))}catch(l){s(l)}},c.readAsDataURL(o)})}i(k,"fetchAsDataURL");var U={};function Ae(e,t,n){let r=e.replace(/\\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\\//,"")),t?`[${t}]${r}`:r}i(Ae,"getCacheKey");async function E(e,t,n){let r=Ae(e,t,n.includeQueryParams);if(U[r]!=null)return U[r];n.cacheBust&&(e+=(/\\?/.test(e)?"&":"?")+new Date().getTime());let o;try{let a=await k(e,n.fetchRequestInit,({res:s,result:c})=>(t||(t=s.headers.get("Content-Type")||""),Re(c)));o=v(a,t)}catch(a){o=n.imagePlaceholder||"";let s=`Failed to fetch resource: ${e}`;a&&(s=typeof a=="string"?a:a.message),s&&console.warn(s)}return U[r]=o,o}i(E,"resourceToDataURL");async function Ce(e){let t=e.toDataURL();return t==="data:,"?e.cloneNode(!1):x(t)}i(Ce,"cloneCanvasElement");async function Pe(e,t){if(e.currentSrc){let a=document.createElement("canvas"),s=a.getContext("2d");a.width=e.clientWidth,a.height=e.clientHeight,s?.drawImage(e,0,0,a.width,a.height);let c=a.toDataURL();return x(c)}let n=e.poster,r=S(n),o=await E(n,r,t);return x(o)}i(Pe,"cloneVideoElement");async function Te(e,t){var n;try{if(!((n=e?.contentDocument)===null||n===void 0)&&n.body)return await P(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}i(Te,"cloneIFrameElement");async function $e(e,t){return m(e,HTMLCanvasElement)?Ce(e):m(e,HTMLVideoElement)?Pe(e,t):m(e,HTMLIFrameElement)?Te(e,t):e.cloneNode(J(e))}i($e,"cloneSingleNode");var De=i(e=>e.tagName!=null&&e.tagName.toUpperCase()==="SLOT","isSlotElement"),J=i(e=>e.tagName!=null&&e.tagName.toUpperCase()==="SVG","isSVGElement");async function Le(e,t,n){var r,o;if(J(t))return t;let a=[];return De(e)&&e.assignedNodes?a=p(e.assignedNodes()):m(e,HTMLIFrameElement)&&(!((r=e.contentDocument)===null||r===void 0)&&r.body)?a=p(e.contentDocument.body.childNodes):a=p(((o=e.shadowRoot)!==null&&o!==void 0?o:e).childNodes),a.length===0||m(e,HTMLVideoElement)||await a.reduce((s,c)=>s.then(()=>P(c,n)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}i(Le,"cloneChildren");function Fe(e,t,n){let r=t.style;if(!r)return;let o=window.getComputedStyle(e);o.cssText?(r.cssText=o.cssText,r.transformOrigin=o.transformOrigin):L(n).forEach(a=>{let s=o.getPropertyValue(a);a==="font-size"&&s.endsWith("px")&&(s=`${Math.floor(parseFloat(s.substring(0,s.length-2)))-.1}px`),m(e,HTMLIFrameElement)&&a==="display"&&s==="inline"&&(s="block"),a==="d"&&t.getAttribute("d")&&(s=`path(${t.getAttribute("d")})`),r.setProperty(a,s,o.getPropertyPriority(a))})}i(Fe,"cloneCSSStyle");function Ie(e,t){m(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),m(e,HTMLInputElement)&&t.setAttribute("value",e.value)}i(Ie,"cloneInputValue");function Ue(e,t){if(m(e,HTMLSelectElement)){let r=Array.from(t.children).find(o=>e.value===o.getAttribute("value"));r&&r.setAttribute("selected","")}}i(Ue,"cloneSelectValue");function ve(e,t,n){return m(t,Element)&&(Fe(e,t,n),z(e,t,n),Ie(e,t),Ue(e,t)),t}i(ve,"decorate");async function ke(e,t){let n=e.querySelectorAll?e.querySelectorAll("use"):[];if(n.length===0)return e;let r={};for(let a=0;a<n.length;a++){let c=n[a].getAttribute("xlink:href");if(c){let l=e.querySelector(c),f=document.querySelector(c);!l&&f&&!r[c]&&(r[c]=await P(f,t,!0))}}let o=Object.values(r);if(o.length){let a="http://www.w3.org/1999/xhtml",s=document.createElementNS(a,"svg");s.setAttribute("xmlns",a),s.style.position="absolute",s.style.width="0",s.style.height="0",s.style.overflow="hidden",s.style.display="none";let c=document.createElementNS(a,"defs");s.appendChild(c);for(let l=0;l<o.length;l++)c.appendChild(o[l]);e.appendChild(s)}return e}i(ke,"ensureSVGSymbols");async function P(e,t,n){return!n&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(r=>$e(r,t)).then(r=>Le(e,r,t)).then(r=>ve(e,r,t)).then(r=>ke(r,t))}i(P,"cloneNode");var K=/url\\(([\'"]?)([^\'"]+?)\\1\\)/g,Oe=/url\\([^)]+\\)\\s*format\\((["\']?)([^"\']+)\\1\\)/g,Be=/src:\\s*(?:url\\([^)]+\\)\\s*format\\([^)]+\\)[,;]\\s*)+/g;function Me(e){let t=e.replace(/([.*+?^${}()|\\[\\]\\/\\\\])/g,"\\\\$1");return new RegExp(`(url\\\\([\'"]?)(${t})([\'"]?\\\\))`,"g")}i(Me,"toRegex");function He(e){let t=[];return e.replace(K,(n,r,o)=>(t.push(o),n)),t.filter(n=>!C(n))}i(He,"parseURLs");async function Ve(e,t,n,r,o){try{let a=n?H(t,n):t,s=S(t),c;if(o){let l=await o(a);c=v(l,s)}else c=await E(a,s,r);return e.replace(Me(t),`$1${c}$3`)}catch{}return e}i(Ve,"embed");function We(e,{preferredFontFormat:t}){return t?e.replace(Be,n=>{for(;;){let[r,,o]=Oe.exec(n)||[];if(!o)return"";if(o===t)return`src: ${r};`}}):e}i(We,"filterPreferredFontFormat");function O(e){return e.search(K)!==-1}i(O,"shouldEmbed");async function F(e,t,n){if(!O(e))return e;let r=We(e,n);return He(r).reduce((a,s)=>a.then(c=>Ve(c,s,t,n)),Promise.resolve(r))}i(F,"embedResources");async function R(e,t,n){var r;let o=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(e);if(o){let a=await F(o,null,n);return t.style.setProperty(e,a,t.style.getPropertyPriority(e)),!0}return!1}i(R,"embedProp");async function _e(e,t){await R("background",e,t)||await R("background-image",e,t),await R("mask",e,t)||await R("-webkit-mask",e,t)||await R("mask-image",e,t)||await R("-webkit-mask-image",e,t)}i(_e,"embedBackground");async function je(e,t){let n=m(e,HTMLImageElement);if(!(n&&!C(e.src))&&!(m(e,SVGImageElement)&&!C(e.href.baseVal)))return;let r=n?e.src:e.href.baseVal,o=await E(r,S(r),t);await new Promise((a,s)=>{e.onload=a,e.onerror=t.onImageErrorHandler?(...l)=>{try{a(t.onImageErrorHandler(...l))}catch(f){s(f)}}:s;let c=e;c.decode&&(c.decode=a),c.loading==="lazy"&&(c.loading="eager"),n?(e.srcset="",e.src=o):e.href.baseVal=o})}i(je,"embedImageNode");async function qe(e,t){let r=p(e.childNodes).map(o=>B(o,t));await Promise.all(r).then(()=>e)}i(qe,"embedChildren");async function B(e,t){m(e,Element)&&(await _e(e,t),await je(e,t),await qe(e,t))}i(B,"embedImages");function Q(e,t){let{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);let r=t.style;return r!=null&&Object.keys(r).forEach(o=>{n[o]=r[o]}),e}i(Q,"applyStyle");var Y={};async function Z(e){let t=Y[e];if(t!=null)return t;let r=await(await fetch(e)).text();return t={url:e,cssText:r},Y[e]=t,t}i(Z,"fetchCSS");async function N(e,t){let n=e.cssText,r=/url\\(["\']?([^"\')]+)["\']?\\)/g,a=(n.match(/url\\([^)]+\\)/g)||[]).map(async s=>{let c=s.replace(r,"$1");return c.startsWith("https://")||(c=new URL(c,e.url).href),k(c,t.fetchRequestInit,({result:l})=>(n=n.replace(s,`url(${l})`),[s,l]))});return Promise.all(a).then(()=>n)}i(N,"embedFonts");function ee(e){if(e==null)return[];let t=[],n=/(\\/\\*[\\s\\S]*?\\*\\/)/gi,r=e.replace(n,""),o=new RegExp("((@.*?keyframes [\\\\s\\\\S]*?){([\\\\s\\\\S]*?}\\\\s*?)})","gi");for(;;){let l=o.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(o,"");let a=/@import[\\s\\S]*?url\\([^)]*\\)[\\s\\S]*?;/gi,s="((\\\\s*?(?:\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\/)?\\\\s*?@media[\\\\s\\\\S]*?){([\\\\s\\\\S]*?)}\\\\s*?})|(([\\\\s\\\\S]*?){([\\\\s\\\\S]*?)})",c=new RegExp(s,"gi");for(;;){let l=a.exec(r);if(l===null){if(l=c.exec(r),l===null)break;a.lastIndex=c.lastIndex}else c.lastIndex=a.lastIndex;t.push(l[0])}return t}i(ee,"parseCSS");async function ze(e,t){let n=[],r=[];return e.forEach(o=>{if("cssRules"in o)try{p(o.cssRules||[]).forEach((a,s)=>{if(a.type===CSSRule.IMPORT_RULE){let c=s+1,l=a.href,f=Z(l).then(u=>N(u,t)).then(u=>ee(u).forEach(h=>{try{o.insertRule(h,h.startsWith("@import")?c+=1:o.cssRules.length)}catch(A){console.error("Error inserting rule from remote css",{rule:h,error:A})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(f)}})}catch(a){let s=e.find(c=>c.href==null)||document.styleSheets[0];o.href!=null&&r.push(Z(o.href).then(c=>N(c,t)).then(c=>ee(c).forEach(l=>{s.insertRule(l,s.cssRules.length)})).catch(c=>{console.error("Error loading remote stylesheet",c)})),console.error("Error inlining remote css file",a)}}),Promise.all(r).then(()=>(e.forEach(o=>{if("cssRules"in o)try{p(o.cssRules||[]).forEach(a=>{n.push(a)})}catch(a){console.error(`Error while reading CSS rules from ${o.href}`,a)}}),n))}i(ze,"getCSSRules");function Ge(e){return e.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>O(t.style.getPropertyValue("src")))}i(Ge,"getWebFontRules");async function Xe(e,t){if(e.ownerDocument==null)throw new Error("Provided element is not within a Document");let n=p(e.ownerDocument.styleSheets),r=await ze(n,t);return Ge(r)}i(Xe,"parseWebFontRules");function te(e){return e.trim().replace(/["\']/g,"")}i(te,"normalizeFontFamily");function Je(e){let t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(a=>{t.add(te(a))}),Array.from(r.children).forEach(a=>{a instanceof HTMLElement&&n(a)})}return i(n,"traverse"),n(e),t}i(Je,"getUsedFonts");async function re(e,t){let n=await Xe(e,t),r=Je(e);return(await Promise.all(n.filter(a=>r.has(te(a.style.fontFamily))).map(a=>{let s=a.parentStyleSheet?a.parentStyleSheet.href:null;return F(a.cssText,s,t)}))).join(`\n`)}i(re,"getWebFontCSS");async function ne(e,t){let n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await re(e,t);if(n){let r=document.createElement("style"),o=document.createTextNode(n);r.appendChild(o),e.firstChild?e.insertBefore(r,e.firstChild):e.appendChild(r)}}i(ne,"embedWebFonts");async function Ke(e,t={}){let{width:n,height:r}=I(e,t),o=await P(e,t,!0);return await ne(o,t),await B(o,t),Q(o,t),await j(o,n,r)}i(Ke,"toSvg");async function oe(e,t={}){let{width:n,height:r}=I(e,t),o=await Ke(e,t),a=await x(o),s=document.createElement("canvas"),c=s.getContext("2d"),l=t.pixelRatio||W(),f=t.canvasWidth||n,u=t.canvasHeight||r;return s.width=f*l,s.height=u*l,t.skipAutoScale||_(s),s.style.width=`${f}`,s.style.height=`${u}`,t.backgroundColor&&(c.fillStyle=t.backgroundColor,c.fillRect(0,0,s.width,s.height)),c.drawImage(a,0,0,s.width,s.height),s}i(oe,"toCanvas");function ae(e,t,n){let r=(n.width*.75).toFixed(2),o=(n.height*.75).toFixed(2),a=`q ${r} 0 0 ${o} 0 0 cm /Im0 Do Q`,s=new TextEncoder,c=[],l=[],f=0,u=i(d=>{let w=typeof d=="string"?s.encode(d):d;c.push(w),f+=w.length},"push"),h=i((d,w)=>{l[d]=f,u(`${d} 0 obj\n`),(Array.isArray(w)?w:[w]).forEach(u),u(`\nendobj\n`)},"object");u(`%PDF-1.4\n`),u(new Uint8Array([37,226,227,207,211,10])),h(1,"<< /Type /Catalog /Pages 2 0 R >>"),h(2,"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),h(3,`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${r} ${o}] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>`),h(4,[`<< /Type /XObject /Subtype /Image /Width ${t.width} /Height ${t.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${e.length} >>\nstream\n`,e,`\nendstream`]),h(5,`<< /Length ${a.length} >>\nstream\n${a}\nendstream`);let A=f;return u(`xref\n0 6\n0000000000 65535 f \n${l.slice(1).map(d=>`${String(d).padStart(10,"0")} 00000 n \n`).join("")}`),u(`trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${A}\n%%EOF\n`),new Blob(c,{type:"application/pdf"})}i(ae,"pdfOfJpeg");var M=class M extends Error{constructor(t){super(t),this.name="RenderFailure"}};i(M,"RenderFailure");var y=M;var T=16384,ie=12e7;function Qe(e,t,n){let r=i(c=>e*c<=T&&t*c<=T&&e*t*c*c<=ie,"fits"),o=i(c=>new y(`${e}\\xD7${t} px at pixelRatio ${c} is over a canvas\'s limit (${T} px a side): render a smaller node, or a lower pixelRatio.`),"tooBig");if(n!==void 0){if(!r(n))throw o(n);return n}let a=Math.max(globalThis.devicePixelRatio||1,2);if(r(a))return a;let s=Math.floor(Math.min(T/e,T/t,Math.sqrt(ie/(e*t)))*100)/100;if(s<1)throw o(1);return s}i(Qe,"ratioFor");function Ye(e){return!!e&&e!=="transparent"&&!/rgba\\(.*,\\s*0\\)$/.test(e)}i(Ye,"opaque");function Ze(e,t){let n=[];if(e){for(let r=e;r;r=r.parentElement)n.push(r);n.push(t.body)}else n.push(t.documentElement,t.body);return n.map(r=>getComputedStyle(r).backgroundColor).find(Ye)??"#ffffff"}i(Ze,"backgroundOf");function Ne(e,t){let n=[],r=i(o=>{if(!t(o)){n.push(o);for(let a of o.children)r(a)}},"walk");return r(e),n}i(Ne,"drawnElements");async function et(e){let t=new Set;for(let r of e)if(r instanceof HTMLImageElement){let o=r.currentSrc||r.src;o&&!/^(data|blob):/.test(o)&&t.add(o)}let n=await Promise.all([...t].map(async r=>{try{return(await fetch(r,{mode:"cors",cache:"force-cache"})).ok}catch{return!1}}));return[...t].filter((r,o)=>!n[o])}i(et,"unreadableImages");var tt="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";function rt(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}i(rt,"dataUrlOf");function nt(e){let t=new Set;for(let n of e)for(let r of getComputedStyle(n).fontFamily.split(","))t.add(r.trim().replace(/^["\']|["\']$/g,"").toLowerCase());return t}i(nt,"familiesOf");async function ot(e,t){let n=nt(t),r=[];return await Promise.all([...e.styleSheets].map(async a=>{let s=a.href??e.baseURI;try{for(let c of a.cssRules)c instanceof CSSFontFaceRule&&r.push({css:c.cssText,base:s})}catch{if(!a.href)return;try{let c=await(await fetch(a.href,{mode:"cors",cache:"force-cache"})).text();for(let l of c.match(/@font-face\\s*{[^}]*}/g)??[])r.push({css:l,base:s})}catch{}}})),(await Promise.all(r.map(async({css:a,base:s})=>{let c=/font-family:\\s*["\']?([^;"\']+)/.exec(a)?.[1]?.trim().toLowerCase();if(!c||!n.has(c))return"";let l=a;for(let[f,,u]of a.matchAll(/url\\((["\']?)([^"\')]+)\\1\\)/g))if(!u.startsWith("data:"))try{let h=await fetch(new URL(u,s).href,{mode:"cors",cache:"force-cache"});l=l.replace(f,`url(${await rt(await h.blob())})`)}catch{return""}return l}))).filter(Boolean).join(`\n`)}i(ot,"embedFonts");function se(e,t,n){return new Promise((r,o)=>{try{e.toBlob(a=>a?r(a):o(new y("The browser made no image of the canvas.")),t,n)}catch{o(new y(\'The page holds something read from another server without CORS (a canvas or a font), so the browser refuses to make an image of it. Load it with CORS, or mark it data-anfra-render="skip".\'))}})}i(se,"toBlob");async function at(e,t){let n=document,r=e??n.body,o=r.getBoundingClientRect(),a=Math.ceil(e?o.width:n.documentElement.scrollWidth),s=Math.ceil(e?o.height:n.documentElement.scrollHeight);if(!a||!s)throw new y("There is nothing to draw: it has no size (hidden, or empty).");let c=Qe(a,s,t.pixelRatio),l=Ne(r,t.skip),f=await et(l),u=await ot(n,l),h=await oe(r,{width:a,height:s,pixelRatio:c,skipAutoScale:!0,backgroundColor:Ze(e,n),fontEmbedCSS:u,imagePlaceholder:tt,filter:i(d=>!(d instanceof Element&&t.skip(d)),"filter"),style:e?{boxSizing:"border-box",margin:"0"}:{boxSizing:"border-box",width:`${o.width}px`,height:"auto"}});if(t.format==="png")return{blob:await se(h,"image/png"),width:a,height:s,omitted:f};let A=new Uint8Array(await(await se(h,"image/jpeg",.92)).arrayBuffer());return{blob:ae(A,h,{width:a,height:s}),width:a,height:s,omitted:f}}i(at,"draw");var ce={draw:at};return ge(it);})();\n';
92
+
93
+ // src/plugins/render/index.ts
94
+ var PICTURES = [
95
+ { ext: "png", type: "image/png", signature: [137, 80, 78, 71, 13, 10, 26, 10] },
96
+ { ext: "pdf", type: "application/pdf", signature: [37, 80, 68, 70, 45] }
97
+ ];
98
+ var SAVES_PER_WINDOW = 5;
99
+ var SAVE_WINDOW_MS = 1e4;
100
+ function pictureFilename(filename, ext) {
101
+ const name = (typeof filename === "string" ? filename : "").replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/[\\/:*?"<>|]/g, "-").trim().replace(/^[.\s]+|[.\s]+$/g, "").slice(0, 200) || "Rendering";
102
+ return name.toLowerCase().endsWith(`.${ext}`) ? name : `${name}.${ext}`;
103
+ }
104
+ async function saveBlob(doc, request) {
105
+ const blob = request?.blob;
106
+ if (!(blob instanceof Blob)) throw new ValidationError("A rendering must be saved as a file.");
107
+ const head = new Uint8Array(await blob.slice(0, 8).arrayBuffer());
108
+ const picture = PICTURES.find(({ signature }) => signature.every((byte, i) => head[i] === byte));
109
+ if (!picture) throw new ValidationError("Only a PNG or a PDF rendering can be saved.");
110
+ const url = URL.createObjectURL(new Blob([blob], { type: picture.type }));
111
+ const a = doc.createElement("a");
112
+ a.href = url;
113
+ a.download = pictureFilename(request.filename, picture.ext);
114
+ a.rel = "noopener";
115
+ a.style.display = "none";
116
+ doc.body.appendChild(a);
117
+ a.click();
118
+ a.remove();
119
+ setTimeout(() => URL.revokeObjectURL(url), 6e4);
120
+ }
121
+ function renderPlugin(options = {}) {
122
+ const renderer = options.renderer ?? (render_default2 || void 0);
123
+ const states = /* @__PURE__ */ new WeakMap();
124
+ return definePlugin({
125
+ name: "render",
126
+ version: PLUGIN_VERSION,
127
+ host: {
128
+ mount(mount) {
129
+ states.set(mount, { saving: false, saves: [] });
130
+ },
131
+ calls: {
132
+ /** Save a rendering the frame made: one at a time, and only so many in a window. */
133
+ save: {
134
+ frame: true,
135
+ async handler(request, { mount }) {
136
+ const state = mount && states.get(mount);
137
+ if (!mount || !state) throw new ValidationError("A rendering is saved for a frame.");
138
+ const now = Date.now();
139
+ while (state.saves.length && now - state.saves[0] >= SAVE_WINDOW_MS) state.saves.shift();
140
+ if (state.saving || state.saves.length >= SAVES_PER_WINDOW) {
141
+ throw new ValidationError("Too many files saved at once: try again in a few seconds.");
142
+ }
143
+ state.saving = true;
144
+ state.saves.push(now);
145
+ try {
146
+ await saveBlob(mount.document, request);
147
+ } finally {
148
+ state.saving = false;
149
+ }
150
+ return null;
151
+ }
152
+ }
153
+ }
154
+ },
155
+ frame: { setup: render_default, ...renderer ? { body: renderer } : {} }
156
+ });
157
+ }
158
+
159
+ // anfra-sdk:anfra-sdk:setup/inspect
160
+ var inspect_default = '"use strict";var __anfraPlugin=(()=>{var b=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var o=(e,n)=>b(e,"name",{value:n,configurable:!0});var N=(e,n)=>{for(var i in n)b(e,i,{get:n[i],enumerable:!0})},C=(e,n,i,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of M(n))!R.call(e,r)&&r!==i&&b(e,r,{get:()=>n[r],enumerable:!(s=O(n,r))||s.enumerable});return e};var H=e=>C(b({},"__esModule",{value:!0}),e);var B={};N(B,{default:()=>S});var m={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},E=`[${m.container}],[${m.block}],[${m.query}],[${m.control}]`;var I=o((e,n,i)=>`${e}:${n}/${i}`,"usageKey");function q(e){let n=e.getBoundingClientRect();return`${Math.round(n.width)} \\xD7 ${Math.round(n.height)}`}o(q,"sizeOf");function k(e,n,i){let s=q(n);if(e.kind==="container"||e.kind==="block")return{kind:e.kind,name:e.id??"",...e.label?{label:e.label}:{},size:s};let r=i.usage[I(e.kind,e.app??0,e.name??"")];return{kind:e.kind,name:e.name??"",...r&&r.markers>1?{note:`1 of ${r.markers}`}:{},size:s}}o(k,"describeNode");function x(e){typeof e.scrollIntoView=="function"&&e.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(x,"scrollTo");function w(e,n){let i=null,s=o(l=>l.target instanceof Element?l.target.closest(E):null,"under"),r=o(l=>{let p=s(l);p!==i&&(i=p,n.onHover(p))},"onMove"),a=o(l=>{l.preventDefault(),l.stopPropagation();let p=s(l);p&&n.onPick(p)},"onClick"),f=o(l=>{l.key==="Escape"&&n.onCancel()},"onKey"),c={capture:!0};return e.addEventListener("mousemove",r,c),e.addEventListener("click",a,c),e.addEventListener("keydown",f,c),()=>{e.removeEventListener("mousemove",r,c),e.removeEventListener("click",a,c),e.removeEventListener("keydown",f,c)}}o(w,"startPick");function L(e,n){for(let i of e){if(i.key===n)return i;let s=L(i.children,n);if(s)return s}}o(L,"findNode");function S(e){let n=e.window,i=n.document,s=!1,r,a,f="",c,l;function p(){if(r=void 0,!!s)try{a=e.structure(),f=JSON.stringify(a.nodes),e.emit("snapshot",{apps:e.sdk.apps.map(t=>t.toInspectJSON()),structure:{nodes:a.nodes,usage:a.usage}})}catch{}}o(p,"postSnapshot");function h(){s&&r===void 0&&(r=setTimeout(p,50))}o(h,"scheduleSnapshot");function T(){let t=n.MutationObserver;if(c||typeof t!="function")return;let u=new t(()=>{if(!(!s||r!==void 0))try{JSON.stringify(e.structure().nodes)!==f&&h()}catch{}});c=u,u.observe(i.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:Object.values(m)})}o(T,"observeStructure");function y(t){let u=t!==null&&a?L(a.nodes,t):void 0,d=t!==null?a?.elements.get(t):void 0;if(!u||!d||!a){e.overlay.hide();return}e.overlay.show([d],k(u,d,a))}o(y,"highlight");function g(t){if(!t){l?.(),l=void 0;return}if(l)return;let u=o(d=>a?.keysOf.get(d)?.[0],"keyOf");l=w(i,{onHover:o(d=>y(d?u(d)??null:null),"onHover"),onPick:o(d=>{let v=u(d);v!==void 0&&e.emit("picked",{node:v})},"onPick"),onCancel:o(()=>{g(!1),e.overlay.hide(),e.emit("picked",{node:null})},"onCancel")})}o(g,"setPicking");function $(t){s=t,t?(T(),p()):(c?.disconnect(),c=void 0,g(!1),e.overlay.hide(),a=void 0,f="")}o($,"setInspecting");function A(t){if("node"in t){let u=a?.elements.get(t.node);u&&x(u),y(t.node)}else e.sdk.apps[t.app]?.locate(t.kind,t.name);h()}o(A,"locate"),e.on("watch",t=>$(t===!0)),e.on("highlight",t=>y(t)),e.on("locate",t=>A(t)),e.on("pick",t=>g(t===!0)),e.onApp(t=>{t.subscribe(h),h()})}o(S,"setup");return H(B);})();\n';
161
+
162
+ // src/plugins/inspect/index.ts
163
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
164
+ function checkSnapshot(payload) {
165
+ if (!isObject(payload) || !Array.isArray(payload.apps) || !payload.apps.every(isObject)) return void 0;
166
+ const structure = payload.structure ?? { nodes: [], usage: {} };
167
+ if (!isObject(structure) || !Array.isArray(structure.nodes) || !isObject(structure.usage ?? {})) return void 0;
168
+ return {
169
+ apps: payload.apps,
170
+ structure: { nodes: structure.nodes, usage: structure.usage ?? {} }
171
+ };
172
+ }
173
+ function checkPicked(payload) {
174
+ if (!isObject(payload) || !(typeof payload.node === "string" || payload.node === null)) return void 0;
175
+ return { node: payload.node };
176
+ }
177
+ function inspectPlugin() {
178
+ const watching = /* @__PURE__ */ new WeakMap();
179
+ const frameOf = (mount) => {
180
+ if (!mount) throw new Error("inspect: call it on a mounted Data App.");
181
+ return mount;
182
+ };
183
+ return definePlugin({
184
+ name: "inspect",
185
+ version: PLUGIN_VERSION,
186
+ host: {
187
+ mount(mount) {
188
+ return mount.onReady(() => {
189
+ if (watching.get(mount)) mount.emit("inspect.watch", true);
190
+ });
191
+ },
192
+ events: {
193
+ /** The frame's apps and structure, while watched. Only while watched, and only of its shape. */
194
+ snapshot: (payload, mount) => watching.get(mount) ? checkSnapshot(payload) : void 0,
195
+ /** The node the reader picked, or null on leaving pick mode. */
196
+ picked: (payload, mount) => watching.get(mount) ? checkPicked(payload) : void 0
197
+ },
198
+ calls: {
199
+ /** Start or stop the snapshots; survives the frame reloading. */
200
+ watch(open, { mount }) {
201
+ const frame = frameOf(mount);
202
+ watching.set(frame, open === true);
203
+ frame.emit("inspect.watch", open === true);
204
+ return null;
205
+ },
206
+ /** Show a node of the last snapshot's structure on the page, or nothing (null). */
207
+ highlight(node, { mount }) {
208
+ frameOf(mount).emit("inspect.highlight", node);
209
+ return null;
210
+ },
211
+ /** Scroll a node, or an entity wherever it is drawn, into view, and hold the highlight on it. */
212
+ locate(target, { mount }) {
213
+ frameOf(mount).emit("inspect.locate", target);
214
+ return null;
215
+ },
216
+ /** Start or stop pick mode: pointing outlines marked elements, a click reports one. */
217
+ pick(on, { mount }) {
218
+ frameOf(mount).emit("inspect.pick", on === true);
219
+ return null;
220
+ }
221
+ }
222
+ },
223
+ frame: { setup: inspect_default }
224
+ });
225
+ }
226
+ export {
227
+ corePlugin,
228
+ exportPlugin,
229
+ inspectPlugin,
230
+ lineagePlugin,
231
+ pictureFilename,
232
+ renderPlugin
233
+ };
@@ -0,0 +1,47 @@
1
+ import { b as PluginInfo } from './bridge-Byq62yS8.js';
2
+ import { ai as User, D as DatasetDescriptor } from './types-BTyDyld7.js';
3
+ import { S as Sdk, P as PluginSetup } from './bootstrap-B7r0ggJN.js';
4
+ import './errors-CKvqVaqU.js';
5
+
6
+ /** The reader a test frame is provisioned with unless given. */
7
+ declare const TEST_READER: User;
8
+ interface TestFrameOptions {
9
+ /** The plugins' setups, by name, in install order: `[['notes', setup]]`, `setup` the frame half's default export. */
10
+ setups?: readonly PluginSetup[];
11
+ /** What the frame is provisioned with; none unless given. */
12
+ datasets?: Record<string, DatasetDescriptor>;
13
+ /** The reader; `TEST_READER` unless given. */
14
+ user?: User;
15
+ /** The host's answer to each frame call, by full name. A call without one fails as nothing answers it. */
16
+ answers?: Record<string, (request: any, signal: AbortSignal) => unknown>;
17
+ /** What a plugin's frame body exports, by plugin: jsdom runs no injected script, so the test gives it. */
18
+ bodies?: Record<string, unknown>;
19
+ /** `Anfra.plugins`; the setups' names unless given. */
20
+ plugins?: PluginInfo[];
21
+ }
22
+ interface TestFrame {
23
+ win: Window;
24
+ /** `Anfra`, with whatever the plugins added. */
25
+ anfra: Sdk & Record<string, any>;
26
+ /** The frame's calls, in order. */
27
+ calls: {
28
+ name: string;
29
+ request: unknown;
30
+ }[];
31
+ /** The frame's events, in order. */
32
+ events: {
33
+ name: string;
34
+ payload: unknown;
35
+ }[];
36
+ /** How often the frame said it was ready. */
37
+ ready: () => number;
38
+ /** The host making a call into the frame. */
39
+ call: <T = unknown>(name: string, request?: unknown) => Promise<T>;
40
+ /** The host sending the frame an event. */
41
+ emit: (name: string, payload?: unknown) => void;
42
+ }
43
+ /** Until queued messages and the work they start have run. */
44
+ declare const flush: () => Promise<unknown>;
45
+ declare function testFrame(options?: TestFrameOptions): TestFrame;
46
+
47
+ export { TEST_READER, type TestFrame, type TestFrameOptions, flush, testFrame };
@@ -0,0 +1,104 @@
1
+ import {
2
+ bootstrap
3
+ } from "./chunk-BL7SPVAS.js";
4
+ import "./chunk-XIUFHRZE.js";
5
+ import {
6
+ createEndpoint
7
+ } from "./chunk-ADWBOQW2.js";
8
+ import {
9
+ PROVISION_ELEMENT_ID
10
+ } from "./chunk-33B2D4U5.js";
11
+ import "./chunk-ENWRS6AT.js";
12
+ import "./chunk-KCTLO3CO.js";
13
+ import "./chunk-PKBMQBKP.js";
14
+
15
+ // src/testing/frame.ts
16
+ var TEST_READER = {
17
+ id: 1,
18
+ name: "Test Reader",
19
+ email: "reader@example.com",
20
+ role: "analyst",
21
+ timezone: "UTC",
22
+ permissions: { canViewGeneratedSql: true, canExportData: true }
23
+ };
24
+ var flush = () => new Promise((resolve) => {
25
+ setTimeout(resolve, 0);
26
+ });
27
+ function testFrame(options = {}) {
28
+ const setups = options.setups ?? [];
29
+ const provision = {
30
+ datasets: options.datasets ?? {},
31
+ user: options.user ?? TEST_READER,
32
+ plugins: options.plugins ?? setups.map(([name]) => ({ name, version: "test" })),
33
+ hostOrigin: "http://host.test"
34
+ };
35
+ document.getElementById(PROVISION_ELEMENT_ID)?.remove();
36
+ const element = document.createElement("script");
37
+ element.type = "application/json";
38
+ element.id = PROVISION_ELEMENT_ID;
39
+ element.textContent = JSON.stringify(provision);
40
+ document.head.appendChild(element);
41
+ const frameListeners = [];
42
+ const calls = [];
43
+ const events = [];
44
+ let readyCount = 0;
45
+ const win = Object.create(window);
46
+ const toFrame = (message) => {
47
+ queueMicrotask(() => frameListeners.forEach((listener) => listener({ source: parent, data: message })));
48
+ };
49
+ const host = createEndpoint(toFrame, {
50
+ answer: async (name, request, signal) => {
51
+ calls.push({ name, request });
52
+ if (name === "anfra.body") {
53
+ const plugin = request.plugin;
54
+ if (!options.bodies || !(plugin in options.bodies)) throw new Error(`No body for '${plugin}'.`);
55
+ win.__anfraBodyExports = { default: options.bodies[plugin] };
56
+ return "";
57
+ }
58
+ const answer = options.answers?.[name];
59
+ if (!answer) throw new Error(`Nothing answers '${name}'.`);
60
+ return answer(request, signal);
61
+ },
62
+ event: (name, payload) => {
63
+ events.push({ name, payload });
64
+ }
65
+ });
66
+ const parent = {
67
+ postMessage(message) {
68
+ if (message.type === "anfra:ready") {
69
+ readyCount += 1;
70
+ return;
71
+ }
72
+ queueMicrotask(() => host.receive(message));
73
+ }
74
+ };
75
+ Object.defineProperties(win, {
76
+ parent: { value: parent },
77
+ document: { value: document },
78
+ // Called on the stand-in, which jsdom's own would refuse as not a window.
79
+ setTimeout: { value: window.setTimeout.bind(window) },
80
+ clearTimeout: { value: window.clearTimeout.bind(window) },
81
+ requestAnimationFrame: { value: (callback) => window.setTimeout(() => callback(0), 0) },
82
+ addEventListener: {
83
+ value: (type, listener) => {
84
+ if (type === "message") frameListeners.push(listener);
85
+ else window.addEventListener(type, listener);
86
+ }
87
+ }
88
+ });
89
+ bootstrap(win, setups);
90
+ return {
91
+ win,
92
+ anfra: win.Anfra,
93
+ calls,
94
+ events,
95
+ ready: () => readyCount,
96
+ call: (name, request) => host.call(name, request ?? null),
97
+ emit: (name, payload) => host.emit(name, payload ?? null)
98
+ };
99
+ }
100
+ export {
101
+ TEST_READER,
102
+ flush,
103
+ testFrame
104
+ };