@maxhealth.tech/prefab 0.3.10 → 0.3.11
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/CHANGELOG.md +723 -698
- package/README.md +1 -1
- package/dist/a2ui/catalog.d.ts +22 -1
- package/dist/a2ui/catalog.d.ts.map +1 -1
- package/dist/a2ui/catalog.js +88 -32
- package/dist/a2ui/catalog.js.map +1 -1
- package/dist/a2ui/control.d.ts +20 -0
- package/dist/a2ui/control.d.ts.map +1 -0
- package/dist/a2ui/control.js +107 -0
- package/dist/a2ui/control.js.map +1 -0
- package/dist/a2ui/emit.d.ts.map +1 -1
- package/dist/a2ui/emit.js +113 -9
- package/dist/a2ui/emit.js.map +1 -1
- package/dist/a2ui/expr.d.ts +52 -19
- package/dist/a2ui/expr.d.ts.map +1 -1
- package/dist/a2ui/expr.js +153 -33
- package/dist/a2ui/expr.js.map +1 -1
- package/dist/a2ui/index.d.ts +2 -0
- package/dist/a2ui/index.d.ts.map +1 -1
- package/dist/a2ui/index.js +1 -0
- package/dist/a2ui/index.js.map +1 -1
- package/dist/a2ui/pipes.d.ts +49 -0
- package/dist/a2ui/pipes.d.ts.map +1 -0
- package/dist/a2ui/pipes.js +106 -0
- package/dist/a2ui/pipes.js.map +1 -0
- package/dist/a2ui.min.js +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/renderer.auto.min.js +1 -1
- package/dist/renderer.min.js +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prefab pipe → A2UI catalog function.
|
|
3
|
+
*
|
|
4
|
+
* `{{ price | currency:'USD' }}` was previously reported as unbindable on the
|
|
5
|
+
* grounds that A2UI has no expression language. That is true of the language and
|
|
6
|
+
* false of the catalog: A2UI ships `formatCurrency`, `formatNumber`, `formatDate`
|
|
7
|
+
* and `pluralize` as functions, which is exactly what these pipes are.
|
|
8
|
+
*
|
|
9
|
+
* Seven of prefab's twenty-two built-ins map. The rest — `truncate`, `join`,
|
|
10
|
+
* `selectattr`, `percent`, `compact` and friends — transform data rather than
|
|
11
|
+
* format it and have no equivalent, so they stay unbindable.
|
|
12
|
+
*
|
|
13
|
+
* The date pipes are the one inexact mapping. prefab renders through
|
|
14
|
+
* `toLocaleDateString()`, so the output follows the reader's locale; A2UI's
|
|
15
|
+
* `formatDate` requires an explicit Unicode TR35 pattern. Choosing a pattern
|
|
16
|
+
* changes what the reader sees, so it is done with a diagnostic rather than
|
|
17
|
+
* silently — losing the value entirely would be the worse trade.
|
|
18
|
+
*/
|
|
19
|
+
import type { A2uiDynamicValue, A2uiFunctionCall } from './types.js';
|
|
20
|
+
/** A pipe applied to a base expression: `path | name:arg`. */
|
|
21
|
+
export interface ParsedPipe {
|
|
22
|
+
base: string;
|
|
23
|
+
name: string;
|
|
24
|
+
arg?: string | number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Split a pipe expression into its parts.
|
|
28
|
+
*
|
|
29
|
+
* Only a single pipe with at most one argument, which is the shape prefab's own
|
|
30
|
+
* evaluator handles. A chained expression returns `undefined` and is reported
|
|
31
|
+
* rather than half-translated.
|
|
32
|
+
*/
|
|
33
|
+
export declare function parsePipe(expr: string): ParsedPipe | undefined;
|
|
34
|
+
/** What a mapped pipe produces, plus anything the mapping cost. */
|
|
35
|
+
export interface PipeMapping {
|
|
36
|
+
call: A2uiFunctionCall;
|
|
37
|
+
/** Set when the translation is inexact, for the caller to report. */
|
|
38
|
+
note?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Every prefab pipe with an A2UI equivalent, for docs and tests. */
|
|
41
|
+
export declare function mappedPipes(): string[];
|
|
42
|
+
/**
|
|
43
|
+
* Map a parsed pipe onto a catalog function.
|
|
44
|
+
*
|
|
45
|
+
* @param value the already-resolved base, as a binding or a literal.
|
|
46
|
+
* @returns `undefined` when the pipe transforms rather than formats.
|
|
47
|
+
*/
|
|
48
|
+
export declare function pipeCall(pipe: ParsedPipe, value: A2uiDynamicValue): PipeMapping | undefined;
|
|
49
|
+
//# sourceMappingURL=pipes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipes.d.ts","sourceRoot":"","sources":["../../src/a2ui/pipes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAEpE,8DAA8D;AAC9D,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CACtB;AAKD;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CA2B9D;AAED,mEAAmE;AACnE,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,gBAAgB,CAAA;IACtB,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AA2CD,qEAAqE;AACrE,wBAAgB,WAAW,IAAI,MAAM,EAAE,CAEtC;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,gBAAgB,GAAG,WAAW,GAAG,SAAS,CAE3F"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prefab pipe → A2UI catalog function.
|
|
3
|
+
*
|
|
4
|
+
* `{{ price | currency:'USD' }}` was previously reported as unbindable on the
|
|
5
|
+
* grounds that A2UI has no expression language. That is true of the language and
|
|
6
|
+
* false of the catalog: A2UI ships `formatCurrency`, `formatNumber`, `formatDate`
|
|
7
|
+
* and `pluralize` as functions, which is exactly what these pipes are.
|
|
8
|
+
*
|
|
9
|
+
* Seven of prefab's twenty-two built-ins map. The rest — `truncate`, `join`,
|
|
10
|
+
* `selectattr`, `percent`, `compact` and friends — transform data rather than
|
|
11
|
+
* format it and have no equivalent, so they stay unbindable.
|
|
12
|
+
*
|
|
13
|
+
* The date pipes are the one inexact mapping. prefab renders through
|
|
14
|
+
* `toLocaleDateString()`, so the output follows the reader's locale; A2UI's
|
|
15
|
+
* `formatDate` requires an explicit Unicode TR35 pattern. Choosing a pattern
|
|
16
|
+
* changes what the reader sees, so it is done with a diagnostic rather than
|
|
17
|
+
* silently — losing the value entirely would be the worse trade.
|
|
18
|
+
*/
|
|
19
|
+
/** Matches `<base> | <name>` with an optional single `:arg`. */
|
|
20
|
+
const PIPE = /^(.+?)\s*\|\s*([A-Za-z_][\w]*)\s*(?::\s*(.+))?$/;
|
|
21
|
+
/**
|
|
22
|
+
* Split a pipe expression into its parts.
|
|
23
|
+
*
|
|
24
|
+
* Only a single pipe with at most one argument, which is the shape prefab's own
|
|
25
|
+
* evaluator handles. A chained expression returns `undefined` and is reported
|
|
26
|
+
* rather than half-translated.
|
|
27
|
+
*/
|
|
28
|
+
export function parsePipe(expr) {
|
|
29
|
+
const m = PIPE.exec(expr);
|
|
30
|
+
if (m == null)
|
|
31
|
+
return undefined;
|
|
32
|
+
const base = m[1].trim();
|
|
33
|
+
// A second `|` means a chain, which has no single-function equivalent.
|
|
34
|
+
if (base.includes('|'))
|
|
35
|
+
return undefined;
|
|
36
|
+
// `at` rather than indexing: an optional capture group is typed `string` but
|
|
37
|
+
// is genuinely absent when the pipe took no argument.
|
|
38
|
+
const raw = m.at(3)?.trim();
|
|
39
|
+
if (raw === undefined)
|
|
40
|
+
return { base, name: m[2] };
|
|
41
|
+
const quoted = /^'([^']*)'$|^"([^"]*)"$/.exec(raw);
|
|
42
|
+
if (quoted != null) {
|
|
43
|
+
// One alternative matched, so exactly one group is present. An empty capture
|
|
44
|
+
// is a real empty-string argument, which `??` keeps and `||` would discard.
|
|
45
|
+
const literal = quoted.at(1) ?? quoted.at(2);
|
|
46
|
+
return { base, name: m[2], arg: literal ?? '' };
|
|
47
|
+
}
|
|
48
|
+
const num = Number(raw);
|
|
49
|
+
if (!Number.isNaN(num))
|
|
50
|
+
return { base, name: m[2], arg: num };
|
|
51
|
+
// An unquoted, non-numeric argument is a reference prefab would resolve at
|
|
52
|
+
// render time. A2UI function args take a value, not an expression to evaluate.
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
/** Build a `formatDate` call, noting that an explicit pattern replaces the locale. */
|
|
56
|
+
function dateFormat(pattern, pipe) {
|
|
57
|
+
return (value) => ({
|
|
58
|
+
call: { call: 'formatDate', args: { value, format: pattern } },
|
|
59
|
+
note: `the "${pipe}" pipe renders in the reader's locale; A2UI needs an explicit pattern, so "${pattern}" was used`,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
const BUILDERS = {
|
|
63
|
+
currency: (value, arg) => ({
|
|
64
|
+
call: {
|
|
65
|
+
call: 'formatCurrency',
|
|
66
|
+
// prefab defaults to USD when the pipe is given no code.
|
|
67
|
+
args: { value, currency: typeof arg === 'string' ? arg : 'USD' },
|
|
68
|
+
},
|
|
69
|
+
}),
|
|
70
|
+
number: (value, arg) => ({
|
|
71
|
+
call: {
|
|
72
|
+
call: 'formatNumber',
|
|
73
|
+
args: { value, ...(typeof arg === 'number' && { decimals: arg }) },
|
|
74
|
+
},
|
|
75
|
+
}),
|
|
76
|
+
round: (value, arg) => ({
|
|
77
|
+
call: {
|
|
78
|
+
call: 'formatNumber',
|
|
79
|
+
// prefab's `round` with no argument means whole numbers.
|
|
80
|
+
args: { value, decimals: typeof arg === 'number' ? arg : 0 },
|
|
81
|
+
},
|
|
82
|
+
}),
|
|
83
|
+
pluralize: (value, arg) => {
|
|
84
|
+
if (typeof arg !== 'string')
|
|
85
|
+
return undefined;
|
|
86
|
+
// prefab pluralizes by appending an s, which is the rule it can express.
|
|
87
|
+
return { call: { call: 'pluralize', args: { value, one: arg, other: `${arg}s` } } };
|
|
88
|
+
},
|
|
89
|
+
date: dateFormat('y-MM-dd', 'date'),
|
|
90
|
+
time: dateFormat('HH:mm', 'time'),
|
|
91
|
+
datetime: dateFormat('y-MM-dd HH:mm', 'datetime'),
|
|
92
|
+
};
|
|
93
|
+
/** Every prefab pipe with an A2UI equivalent, for docs and tests. */
|
|
94
|
+
export function mappedPipes() {
|
|
95
|
+
return Object.keys(BUILDERS).sort();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Map a parsed pipe onto a catalog function.
|
|
99
|
+
*
|
|
100
|
+
* @param value the already-resolved base, as a binding or a literal.
|
|
101
|
+
* @returns `undefined` when the pipe transforms rather than formats.
|
|
102
|
+
*/
|
|
103
|
+
export function pipeCall(pipe, value) {
|
|
104
|
+
return BUILDERS[pipe.name]?.(value, pipe.arg);
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=pipes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipes.js","sourceRoot":"","sources":["../../src/a2ui/pipes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAWH,gEAAgE;AAChE,MAAM,IAAI,GAAG,iDAAiD,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzB,IAAI,CAAC,IAAI,IAAI;QAAE,OAAO,SAAS,CAAA;IAE/B,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IACxB,uEAAuE;IACvE,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAA;IAExC,6EAA6E;IAC7E,sDAAsD;IACtD,MAAM,GAAG,GAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAA;IAC/C,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAElD,MAAM,MAAM,GAAG,yBAAyB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAClD,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QACnB,6EAA6E;QAC7E,4EAA4E;QAC5E,MAAM,OAAO,GAAuB,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QAChE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,IAAI,EAAE,EAAE,CAAA;IACjD,CAAC;IAED,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAA;IACvB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAA;IAE7D,2EAA2E;IAC3E,+EAA+E;IAC/E,OAAO,SAAS,CAAA;AAClB,CAAC;AAWD,sFAAsF;AACtF,SAAS,UAAU,CAAC,OAAe,EAAE,IAAY;IAC/C,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACjB,IAAI,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;QAC9D,IAAI,EAAE,QAAQ,IAAI,8EAA8E,OAAO,YAAY;KACpH,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,QAAQ,GAA4C;IACxD,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;QACzB,IAAI,EAAE;YACJ,IAAI,EAAE,gBAAgB;YACtB,yDAAyD;YACzD,IAAI,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;SACjE;KACF,CAAC;IACF,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;QACvB,IAAI,EAAE;YACJ,IAAI,EAAE,cAAc;YACpB,IAAI,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,GAAG,KAAK,QAAQ,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,EAAE;SACnE;KACF,CAAC;IACF,KAAK,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;QACtB,IAAI,EAAE;YACJ,IAAI,EAAE,cAAc;YACpB,yDAAyD;YACzD,IAAI,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE;SAC7D;KACF,CAAC;IACF,SAAS,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACxB,IAAI,OAAO,GAAG,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAA;QAC7C,yEAAyE;QACzE,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,GAAG,GAAG,EAAE,EAAE,EAAE,CAAA;IACrF,CAAC;IACD,IAAI,EAAE,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC;IACnC,IAAI,EAAE,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IACjC,QAAQ,EAAE,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC;CAClD,CAAA;AAED,qEAAqE;AACrE,MAAM,UAAU,WAAW;IACzB,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAA;AACrC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAgB,EAAE,KAAuB;IAChE,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC"}
|
package/dist/a2ui.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var{defineProperty:A,getOwnPropertyNames:z,getOwnPropertyDescriptor:Y}=Object,X=Object.prototype.hasOwnProperty;function Z(e){return this[e]}var Q=(e)=>{var n=(D??=new WeakMap).get(e),t;if(n)return n;if(n=A({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var r of z(e))if(!X.call(n,r))A(n,r,{get:Z.bind(e,r),enumerable:!(t=Y(e,r))||t.enumerable})}return D.set(e,n),n},D;var ee=(e)=>e;function ne(e,n){this[e]=ee.bind(null,n)}var te=(e,n)=>{for(var t in n)A(e,t,{get:n[t],enumerable:!0,configurable:!0,set:ne.bind(n,t)})};var De={};te(De,{default:()=>Ie,emit:()=>G,envelope:()=>K});var I={silent:0,error:1,warn:2,info:3,debug:4},re="warn";function y(e){let n=e?`[prefab:${e}]`:"[prefab]",t=(r,i,o)=>{if(I[r]>I[re])return;console[r](`${n} ${i}`,...o)};return{error:(r,...i)=>t("error",r,i),warn:(r,...i)=>t("warn",r,i),info:(r,...i)=>t("info",r,i),debug:(r,...i)=>t("debug",r,i)}}var Me=y();var ie=/^\s*\{\{\s*(.+?)\s*\}\}\s*$/s,oe=/^[A-Za-z_$][\w$]*(?:\.(?:[A-Za-z_$][\w$]*|\d+))*$/;function b(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ae(e){return"/"+e.map(b).join("/")}function se(e){return e.startsWith("state.")?e.slice(6):e}function d(e){let n=ie.exec(e);if(n==null){if(e.includes("{{"))return{kind:"unbindable",expression:e};return{kind:"literal",value:e}}let t=se(n[1].trim());if(!oe.test(t))return{kind:"unbindable",expression:n[1].trim()};return{kind:"binding",value:{path:ae(t.split("."))}}}function c(e){if(e==null)return;let n=d(e);if(n.kind==="literal")return n.value;if(n.kind==="binding")return n.value;return}var ue=["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"],le=new Map(ue.map((e)=>[O(e),e])),ce={alertcircle:"error",alerttriangle:"warning",alertoctagon:"error",xcircle:"error",circlex:"error",circlealert:"error",checkcircle:"check",circlecheck:"check",checkcircle2:"check",infocircle:"info",circleinfo:"info",helpcircle:"help",circlehelp:"help",bell:"notifications",belloff:"notificationsOff",arrowleft:"arrowBack",arrowright:"arrowForward",chevronleft:"arrowBack",chevronright:"arrowForward",x:"close",plus:"add",trash:"delete",trash2:"delete",ellipsisvertical:"moreVert",ellipsis:"moreHoriz",morehorizontal:"moreHoriz",morevertical:"moreVert",pencil:"edit",pen:"edit",squarepen:"edit",user:"person",usercircle:"accountCircle",circleuser:"accountCircle",eye:"visibility",eyeoff:"visibilityOff",mappin:"locationOn",map:"locationOn",image:"photo",images:"photo",file:"folder",files:"folder",calendar:"calendarToday",calendardays:"calendarToday",clock:"event",creditcard:"payment",cart:"shoppingCart",shoppingbag:"shoppingCart",phonecall:"call",mailopen:"mail",inbox:"mail",cog:"settings",gear:"settings",sliders:"settings",rotatecw:"refresh",rotateccw:"refresh",refreshcw:"refresh",heart:"favorite",heartoff:"favoriteOff",volume:"volumeUp",volume1:"volumeDown",volume2:"volumeUp",volumex:"volumeOff",skipforward:"skipNext",skipback:"skipPrevious",paperclip:"attachFile",link:"share",share2:"share",magnifyingglass:"search",searchicon:"search"};function O(e){return e.replace(/[\s._-]/g,"").toLowerCase()}function M(e){let n=O(e);return le.get(n)??ce[n]}var R=["TableHead","TableBody","TableFooter","TableRow","TableCell","TableHeader","ExpandableRow"];function de(e){if(!Array.isArray(e.columns))return[];let n=[];for(let t of e.columns){if(t==null||typeof t!=="object")continue;let r=t,i=typeof r.accessor==="string"?r.accessor:typeof r.key==="string"?r.key:void 0;if(i==null)continue;n.push({key:i,header:typeof r.header==="string"?r.header:i})}return n}function pe(e,n){let t=e.rows;if(typeof t==="string"){let r=d(t);if(r.kind==="binding")return r.value.path;n.note("expression","DataTable",`rows expression "${t}" is not a plain path; the table has no data source`);return}if(Array.isArray(t))return n.bindData("rows",t);n.note("unsupported","DataTable","no rows to render");return}function E(e,n){let t=de(e);if(t.length===0){n.note("unsupported","DataTable","no usable column definitions");return}let r=pe(e,n);if(r==null)return;let i=n.push({component:"Row",children:t.map((l)=>n.push({component:"Text",text:l.header,variant:"caption"})),align:"center"}),o=n.push({component:"Row",children:t.map((l)=>n.push({component:"Text",text:{path:l.key.split(".").join("/")}})),align:"center"}),u=n.push({component:"Column",children:{path:r,componentId:o}});if(e.search===!0||e.paginated===!0)n.note("degraded","DataTable","search and pagination dropped; A2UI Basic has no table controls");return{component:"Column",children:[i,u]}}function fe(e){let n=[],t=(r)=>{if(r.type==="TableRow"||r.type==="ExpandableRow"){n.push(r);return}if(Array.isArray(r.children))for(let i of r.children)t(i)};if(Array.isArray(e.children))for(let r of e.children)t(r);return n}function ge(e,n){let t=e.type==="TableHeader";if(Array.isArray(e.children)&&e.children.length>0)return n.single(e.children);let r=e.content??e.text??e.label;if(typeof r!=="string"&&typeof r!=="number"&&typeof r!=="boolean")return;let i=String(r),o=c(i);if(o==null){n.note("expression",e.type,`cell expression "${i}" has no A2UI equivalent`);return}return n.push({component:"Text",text:o,...t&&{variant:"caption"}})}function P(e,n){let t=fe(e),r=[];for(let i of t){let u=(Array.isArray(i.children)?i.children:[]).map((l)=>ge(l,n)).filter((l)=>l!=null);if(u.length===0)continue;r.push(n.push({component:"Row",children:u,align:"center"}))}if(r.length===0){n.note("unsupported","Table","no rows with renderable cells");return}return n.note("degraded","Table","rendered as a Column of Rows; column widths do not align"),{component:"Column",children:r}}function a(e,...n){for(let t of n){let r=e[t];if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")return String(r)}return}function s(e,n,t){let r=a(e,...t?.keys??["content","text","label","title"]);if(r==null){n.note("unsupported",e.type,"no text content to render");return}let i=d(r);if(i.kind==="unbindable")n.note("expression",e.type,`"${i.expression}" is richer than a JSON Pointer; the text was left as written`);let o=t?.prefix??"",u=t?.suffix??"";if(i.kind==="binding"){if(o!==""||u!=="")n.note("degraded",e.type,"Markdown emphasis dropped: the text is a data binding");return{component:"Text",text:i.value,...t?.variant!=null&&{variant:t.variant}}}let l=i.kind==="literal"?i.value:r;return{component:"Text",text:`${o}${l}${u}`,...t?.variant!=null&&{variant:t.variant}}}var me={start:"start",end:"end",center:"center",between:"spaceBetween",around:"spaceAround",evenly:"spaceEvenly",spaceBetween:"spaceBetween",spaceAround:"spaceAround",spaceEvenly:"spaceEvenly"},he={start:"start",end:"end",center:"center",stretch:"stretch",baseline:"baseline"};function g(e){return(n,t)=>{let r=t.children(n.children);if(r.length===0){t.note("unsupported",n.type,`${e} requires at least one child and none survived`);return}let i=typeof n.justify==="string"?me[n.justify]:void 0,o=typeof n.align==="string"?he[n.align]:void 0;return{component:e,children:r,...i!=null&&{justify:i},...o!=null&&{align:o}}}}var Ae=["Div","Container","Stack","Grid","GridItem","Page","Pages","Dashboard","DashboardItem","MasterDetail","Detail","Form","Fieldset","CardContent","CardHeader","CardFooter","Accordion","Carousel","SelectGroup","ComboboxGroup","Section","Article","Aside","Header","Footer","Nav","Span"],ye=["ButtonGroup","Toolbar","Inline"],be={H1:"# ",H2:"## ",H3:"### ",H4:"#### ",H5:"##### ",H6:"###### "},B={Heading:(e,n)=>{let t=typeof e.level==="number"?Math.min(6,Math.max(1,e.level)):1;return s(e,n,{prefix:`${"#".repeat(t)} `})},Text:(e,n)=>s(e,n),P:(e,n)=>s(e,n),Lead:(e,n)=>s(e,n),Large:(e,n)=>s(e,n),Small:(e,n)=>s(e,n,{variant:"caption"}),Muted:(e,n)=>s(e,n,{variant:"caption"}),Label:(e,n)=>s(e,n,{variant:"caption"}),TableCaption:(e,n)=>s(e,n,{variant:"caption"}),BlockQuote:(e,n)=>s(e,n,{prefix:"> "}),Code:(e,n)=>s(e,n,{prefix:"`",suffix:"`"}),Kbd:(e,n)=>s(e,n,{prefix:"`",suffix:"`"}),Markdown:(e,n)=>s(e,n),Badge:(e,n)=>s(e,n,{keys:["label","content"],variant:"caption"}),AlertTitle:(e,n)=>s(e,n,{prefix:"**",suffix:"**"}),AlertDescription:(e,n)=>s(e,n)};for(let[e,n]of Object.entries(be))B[e]=(t,r)=>s(t,r,{prefix:n});function v(e){return(n,t)=>{let r=c(a(n,"src","url"));if(r==null){t.note("unsupported",n.type,"no resolvable source URL");return}let i=e==="Video"?void 0:c(a(n,"alt","description")),o=e==="Video"?c(a(n,"poster","posterUrl")):void 0;return{component:e,url:r,...i!=null&&{description:i},...o!=null&&{posterUrl:o}}}}var ve={text:"shortText",email:"shortText",url:"shortText",tel:"shortText",search:"shortText",password:"obscured",number:"number"};function f(e){let n=typeof e.name==="string"?e.name:void 0;if(n==null)return;let t=d(`{{ ${n} }}`);return t.kind==="binding"?t.value:void 0}function Ce(e,n){let t=Array.isArray(e.children)?e.children:[],r=[];for(let i of t){let o=a(i,"value");if(o==null){n.note("degraded",e.type,`dropped a ${i.type} child that carries no option value`);continue}r.push({label:a(i,"label")??o,value:o})}return r}function C(e,n,t){if(a(e,"label","name")==null)n.note("degraded",e.type,"no label available for the DateTimeInput");return{component:"DateTimeInput",value:f(e)??"",...t}}function x(e){return(n,t)=>{let r=c(a(n,"label","name"));if(r==null){t.note("unsupported",n.type,"ChoicePicker requires a label and none could be derived");return}let i=Ce(n,t);if(i.length===0){t.note("unsupported",n.type,"no options to choose from");return}let o=f(n);return{component:"ChoicePicker",label:r,variant:e,options:i,...o!=null&&{value:o}}}}function N(e,n,t){let r=c(a(e,"label","name"));if(r==null){n.note("unsupported",e.type,"TextField requires a label and none could be derived");return}let i=f(e),o=c(a(e,"placeholder"));return{component:"TextField",label:r,variant:t,...i!=null&&{value:i},...o!=null&&{placeholder:o}}}var w={Input:(e,n)=>{let t=typeof e.inputType==="string"?e.inputType:"text",r=ve[t];if(r==null)n.note("degraded",e.type,`inputType "${t}" has no A2UI variant; used shortText`);return N(e,n,r??"shortText")},Textarea:(e,n)=>N(e,n,"longText"),Checkbox:(e,n)=>{let t=c(a(e,"label","name"));if(t==null){n.note("unsupported",e.type,"CheckBox requires a label and none could be derived");return}return{component:"CheckBox",label:t,value:f(e)??!1}},Slider:(e,n)=>{let t=typeof e.max==="number"?e.max:void 0;if(t==null){n.note("unsupported",e.type,"Slider requires a max and prefab left it open");return}let r=c(a(e,"label","name")),i=typeof e.min==="number"?e.min:void 0,o=typeof e.step==="number"?e.step:void 0,u=o!=null&&o>0?Math.max(1,Math.round((t-(i??0))/o)):void 0;return{component:"Slider",max:t,value:f(e)??i??0,...r!=null&&{label:r},...i!=null&&{min:i},...u!=null&&{steps:u}}},Button:(e,n)=>{let t=a(e,"label","content")??"Button",r=n.action(e.onClick,"Button")??(e.submit===!0?{event:{name:"submit"}}:void 0);if(r==null){n.note("unsupported",e.type,"Button requires an action and none could be derived");return}let i=n.push({component:"Text",text:c(t)??t}),o=e.variant==="link"||e.variant==="ghost"?"borderless":e.variant==="default"?"primary":"default";return{component:"Button",child:i,action:r,variant:o}},Link:(e,n)=>{let t=a(e,"href","url");if(t==null){n.note("unsupported",e.type,"no href to open");return}let r=a(e,"content","label")??t;return{component:"Button",child:n.push({component:"Text",text:c(r)??r}),variant:"borderless",action:{functionCall:{call:"openUrl",args:{url:t}}}}},DatePicker:(e,n)=>C(e,n,{enableDate:!0}),TimePicker:(e,n)=>C(e,n,{enableTime:!0}),DateTimePicker:(e,n)=>C(e,n,{enableDate:!0,enableTime:!0}),Select:x("mutuallyExclusive"),RadioGroup:x("mutuallyExclusive"),Combobox:x("mutuallyExclusive")};w.Switch=w.Checkbox;var xe={Card:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Card","Card requires a child and it had none");return}return{component:"Card",child:t}},Alert:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Alert","no alert body to render");return}let r=typeof e.variant==="string"?e.variant:"default";return n.note("degraded","Alert",`variant "${r}" rendered as a plain Card`),{component:"Card",child:t}},Separator:()=>({component:"Divider"}),Divider:()=>({component:"Divider"}),Icon:(e,n)=>{let t=a(e,"name","icon");if(t==null){n.note("unsupported","Icon","no icon name");return}let r=M(t);if(r==null){n.note("unsupported","Icon",`"${t}" has no equivalent in the A2UI icon set`);return}if(r!==t)n.note("degraded","Icon",`"${t}" mapped to the A2UI icon "${r}"`);return{component:"Icon",name:r}},Metric:(e,n)=>{let t=[],r=a(e,"label","title");if(r!=null)t.push(n.push({component:"Text",text:c(r)??r,variant:"caption"}));let i=a(e,"value");if(i!=null)t.push(n.push({component:"Text",text:c(i)??i}));if(t.length===0){n.note("unsupported","Metric","neither a label nor a value to render");return}return n.note("degraded","Metric","rendered as a Column of Text; trend and delta styling dropped"),{component:"Column",children:t}},Tabs:(e,n)=>{let t=Array.isArray(e.children)?e.children:[],r=[];for(let i of t){let o=n.single(i.children);if(o==null)continue;r.push({title:a(i,"title")??"Tab",child:o})}if(r.length===0){n.note("unsupported","Tabs","no tab had renderable content");return}return{component:"Tabs",tabs:r}},Dialog:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Dialog","no dialog body to render");return}let r=e.trigger,i=r!=null?n.child(r):n.push({component:"Text",text:a(e,"title")??"Open"});if(i==null){n.note("unsupported","Dialog","Modal requires a trigger and none could be emitted");return}return{component:"Modal",trigger:i,content:t}},AccordionItem:(e,n)=>{let t=[],r=a(e,"title");if(r!=null)t.push(n.push({component:"Text",text:r,variant:"caption"}));if(t.push(...n.children(e.children)),t.length===0){n.note("unsupported","AccordionItem","nothing to render");return}return n.note("degraded","AccordionItem","rendered expanded; A2UI Basic has no disclosure component"),{component:"Column",children:t}}},m={Column:g("Column"),Row:g("Row"),...B,...w,...xe,Image:v("Image"),Video:v("Video"),Audio:v("AudioPlayer"),Table:P,DataTable:E};for(let e of Ae)m[e]??=g("Column");for(let e of ye)m[e]??=g("Row");var we=new Set(["Tab","SelectOption","ComboboxOption","Radio","Option",...R]),ke={LineChart:"charts",BarChart:"charts",AreaChart:"charts",PieChart:"charts",ScatterChart:"charts",RadarChart:"charts",RadialChart:"charts",Histogram:"charts",Sparkline:"charts",Svg:"inline vector graphics",Mermaid:"diagrams",Embed:"embedded frames",DropZone:"file uploads",Ring:"progress rings",Loader:"loading indicators",Progress:"progress bars"};function L(e){return m[e]}function U(e){return we.has(e)}function _(){return Object.keys(m).sort()}function F(e,n){let t=ke[e.type];if(t!=null){n.note("unsupported",e.type,`${t} are outside the A2UI Basic catalog`);return}if(Array.isArray(e.children)&&e.children.length>0){let r=n.children(e.children);if(r.length>0)return n.note("degraded",e.type,"no Basic-catalog equivalent; flattened to a Column"),{component:"Column",children:r}}if(a(e,"content","text","label","title")!=null)return n.note("degraded",e.type,"no Basic-catalog equivalent; rendered as Text"),s(e,n);n.note("unsupported",e.type,"no Basic-catalog equivalent and nothing to render");return}var p="v1.0",h="https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",J="application/a2ui+json",j="a2ui://",k="root";var Te=y("a2ui");function Se(e){let n=e.children;if(e.type==="Div"&&typeof e.cssClass==="string"&&e.cssClass.startsWith("pf-app-root")&&Array.isArray(n)&&n.length===1)return n[0];return e}class H{warn;components=new Map;dataModel={};used=new Set([k]);diagnostics=[];counter=0;constructor(e){this.warn=e}note(e,n,t){if(this.diagnostics.push({kind:e,subject:n,detail:t}),this.warn)Te.warn(`${e}: ${n} — ${t}`)}allocate(e){let n=typeof e?.id==="string"&&e.id.length>0?e.id:void 0;if(n!=null&&!this.used.has(n))return this.used.add(n),n;let t;do this.counter+=1,t=`c${this.counter}`;while(this.used.has(t));return this.used.add(t),t}push(e){let n=this.allocate();return this.components.set(n,{id:n,...e}),n}bindData(e,n){let t=e,r=0;while(t in this.dataModel)r+=1,t=`${e}${r}`;return this.dataModel[t]=n,`/${b(t)}`}child(e){return this.emit(e,!1)}children(e){if(!Array.isArray(e))return[];let n=[];for(let t of e){if(t==null||typeof t!=="object")continue;let r=this.emit(t,!1);if(r!=null)n.push(r)}return n}single(e){let n=this.children(e);if(n.length===0)return;if(n.length===1)return n[0];return this.push({component:"Column",children:n})}action(e,n){if(e==null)return;if(Array.isArray(e)){if(e.length===0)return;if(e.length>1)this.note("action",n,`${e.length} actions were bound; A2UI carries one, so the rest were dropped`);return this.action(e[0],n)}if(typeof e!=="object")return;let t=e,r=typeof t.action==="string"?t.action:void 0;if(r==null)return;switch(r){case"toolCall":{let i=typeof t.tool==="string"?t.tool:void 0;if(i==null)return;let o=this.eventContext(t.arguments,n);return{event:{name:i,...o!=null&&{context:o}}}}case"sendMessage":return{event:{name:"sendMessage",context:{message:typeof t.message==="string"?t.message:""}}};case"openLink":{let i=typeof t.url==="string"?t.url:typeof t.href==="string"?t.href:void 0;if(i==null)return;return{functionCall:{call:"openUrl",args:{url:i}}}}default:{this.note("action",n,`"${r}" has no renderer-side equivalent; emitted as an agent event`);let{action:i,...o}=t,u=this.eventContext(o,n);return{event:{name:r,...u!=null&&{context:u}}}}}}eventContext(e,n){if(e==null||typeof e!=="object"||Array.isArray(e))return;let t={};for(let[r,i]of Object.entries(e)){if(typeof i==="number"||typeof i==="boolean"||i===null){t[r]=i;continue}if(typeof i!=="string"){this.note("action",n,`argument "${r}" is not a scalar and was dropped from the event context`);continue}let o=d(i);if(o.kind==="unbindable"){this.note("action",n,`argument "${r}" uses "${o.expression}", which A2UI cannot bind; it was dropped`);continue}t[r]=o.kind==="binding"?o.value:o.value}return Object.keys(t).length>0?t:void 0}emit(e,n){if(typeof e.type!=="string")return;if(U(e.type)){this.note("unsupported",e.type,"only meaningful inside its parent; emitted standalone it has no meaning");return}let t=n?k:this.allocate(e);this.components.set(t,void 0);let i=(L(e.type)??F)(e,this);if(i==null){if(this.components.delete(t),!n)this.used.delete(t);return}return this.components.set(t,{id:t,...i}),t}finish(e,n){let t=n.surfaceId??"prefab";if(this.emit(Se(e.view),!0)==null)this.note("unsupported","view","nothing in the view could be expressed in A2UI; the surface is empty");let i=[];for(let S of this.components.values())if(S!=null)i.push(S);let o={...this.dataModel,...e.state??{}},u=Object.keys(o).length>0,l=[],T=n.catalogId??h;if(n.stream===!0){if(l.push({version:p,createSurface:{surfaceId:t,catalogId:T,...n.sendDataModel===!0&&{sendDataModel:!0}}}),i.length>0)l.push({version:p,updateComponents:{surfaceId:t,components:i}});if(u)l.push({version:p,updateDataModel:{surfaceId:t,value:o}})}else l.push({version:p,createSurface:{surfaceId:t,catalogId:T,...n.sendDataModel===!0&&{sendDataModel:!0},...i.length>0&&{components:i},...u&&{dataModel:o}}});return{messages:l,diagnostics:this.diagnostics}}}function V(e,n){let t=n??{};return new H(t.warn===!0).finish(e,t)}var q="0.3.10";function G(e,n){if(e==null||typeof e!=="object"||!("view"in e))throw TypeError('PrefabA2UI.emit: expected a $prefab payload with a "view"');return V(e,n)}function K(e){return{messages:e}}var W={emit:G,envelope:K,mappedTypes:_,VERSION:q,A2UI_VERSION:p,A2UI_BASIC_CATALOG:h,A2UI_MIME:J,A2UI_SCHEME:j},Ie=W;if(typeof window<"u")window.PrefabA2UI=W;})();
|
|
1
|
+
(()=>{var{defineProperty:v,getOwnPropertyNames:se,getOwnPropertyDescriptor:ae}=Object,ue=Object.prototype.hasOwnProperty;function le(e){return this[e]}var de=(e)=>{var n=(R??=new WeakMap).get(e),t;if(n)return n;if(n=v({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var i of se(e))if(!ue.call(n,i))v(n,i,{get:le.bind(e,i),enumerable:!(t=ae(e,i))||t.enumerable})}return R.set(e,n),n},R;var ce=(e)=>e;function pe(e,n){this[e]=ce.bind(null,n)}var fe=(e,n)=>{for(var t in n)v(e,t,{get:n[t],enumerable:!0,configurable:!0,set:pe.bind(n,t)})};var He={};fe(He,{default:()=>qe,emit:()=>te,envelope:()=>ie});var E={silent:0,error:1,warn:2,info:3,debug:4},me="warn";function x(e){let n=e?`[prefab:${e}]`:"[prefab]",t=(i,r,o)=>{if(E[i]>E[me])return;console[i](`${n} ${r}`,...o)};return{error:(i,...r)=>t("error",i,r),warn:(i,...r)=>t("warn",i,r),info:(i,...r)=>t("info",i,r),debug:(i,...r)=>t("debug",i,r)}}var Ge=x();var ge=/^(.+?)\s*\|\s*([A-Za-z_][\w]*)\s*(?::\s*(.+))?$/;function N(e){let n=ge.exec(e);if(n==null)return;let t=n[1].trim();if(t.includes("|"))return;let i=n.at(3)?.trim();if(i===void 0)return{base:t,name:n[2]};let r=/^'([^']*)'$|^"([^"]*)"$/.exec(i);if(r!=null){let s=r.at(1)??r.at(2);return{base:t,name:n[2],arg:s??""}}let o=Number(i);if(!Number.isNaN(o))return{base:t,name:n[2],arg:o};return}function S(e,n){return(t)=>({call:{call:"formatDate",args:{value:t,format:e}},note:`the "${n}" pipe renders in the reader's locale; A2UI needs an explicit pattern, so "${e}" was used`})}var he={currency:(e,n)=>({call:{call:"formatCurrency",args:{value:e,currency:typeof n==="string"?n:"USD"}}}),number:(e,n)=>({call:{call:"formatNumber",args:{value:e,...typeof n==="number"&&{decimals:n}}}}),round:(e,n)=>({call:{call:"formatNumber",args:{value:e,decimals:typeof n==="number"?n:0}}}),pluralize:(e,n)=>{if(typeof n!=="string")return;return{call:{call:"pluralize",args:{value:e,one:n,other:`${n}s`}}}},date:S("y-MM-dd","date"),time:S("HH:mm","time"),datetime:S("y-MM-dd HH:mm","datetime")};function B(e,n){return he[e.name]?.(n,e.arg)}var ye=/^\s*\{\{\s*(.+?)\s*\}\}\s*$/s,Ae=/\{\{\s*(.+?)\s*\}\}/g,be=/^\$?[A-Za-z_][\w$]*(?:\.(?:[A-Za-z_$][\w$]*|\d+))*$/,U="$index";function c(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Ce(e){return"/"+e.map(c).join("/")}function ve(e){return e.startsWith("state.")?e.slice(6):e}function w(e,n){if(!be.test(e))return;let t=ve(e).split("."),i=t[0],r=Object.hasOwn(n,i)?n[i]:void 0;if(r===void 0){if(i.startsWith("$"))return;return Ce(t)}let o=t.slice(1);if(r==="")return o.length===0?void 0:o.map(c).join("/");return o.length===0?r:`${r}/${o.map(c).join("/")}`}function L(e){return e.replace(/\$\{/g,"\\${")}function xe(e,n){let t,i="",r=0;for(let o of e.matchAll(Ae)){let s=o[1].trim(),a=w(s,n);if(a==null){t=s;break}i+=L(e.slice(r,o.index)),i+=`\${${a}}`,r=o.index+o[0].length}if(t!=null)return;return i+=L(e.slice(r)),{call:"formatString",args:{value:i}}}function Se(e,n){let t=N(e);if(t==null)return;let i=w(t.base,n),r=i!=null?{path:i}:/^-?\d+(\.\d+)?$/.test(t.base)?Number(t.base):void 0;if(r===void 0)return;let o=B(t,r);if(o==null)return;return{kind:"format",value:o.call,...o.note!=null&&{note:o.note}}}function f(e,n={}){let t=ye.exec(e);if(t!=null&&!t[1].includes("{{")&&!t[1].includes("}}")){let o=t[1].trim();if(o===U&&U in n)return{kind:"index",value:{call:"@index"}};let s=w(o,n);if(s!=null)return{kind:"binding",value:{path:s}};let a=Se(o,n);if(a!=null)return a;return{kind:"unbindable",expression:o}}if(!e.includes("{{"))return{kind:"literal",value:e};let r=xe(e,n);if(r!=null)return{kind:"format",value:r};return{kind:"unbindable",expression:e}}function h(e,n={}){if(e==null)return;let t=f(e,n);switch(t.kind){case"literal":return t.value;case"binding":return t.value;case"format":return t.value;case"index":return t.value;default:return}}var we=["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"],ke=new Map(we.map((e)=>[F(e),e])),Te={alertcircle:"error",alerttriangle:"warning",alertoctagon:"error",xcircle:"error",circlex:"error",circlealert:"error",checkcircle:"check",circlecheck:"check",checkcircle2:"check",infocircle:"info",circleinfo:"info",helpcircle:"help",circlehelp:"help",bell:"notifications",belloff:"notificationsOff",arrowleft:"arrowBack",arrowright:"arrowForward",chevronleft:"arrowBack",chevronright:"arrowForward",x:"close",plus:"add",trash:"delete",trash2:"delete",ellipsisvertical:"moreVert",ellipsis:"moreHoriz",morehorizontal:"moreHoriz",morevertical:"moreVert",pencil:"edit",pen:"edit",squarepen:"edit",user:"person",usercircle:"accountCircle",circleuser:"accountCircle",eye:"visibility",eyeoff:"visibilityOff",mappin:"locationOn",map:"locationOn",image:"photo",images:"photo",file:"folder",files:"folder",calendar:"calendarToday",calendardays:"calendarToday",clock:"event",creditcard:"payment",cart:"shoppingCart",shoppingbag:"shoppingCart",phonecall:"call",mailopen:"mail",inbox:"mail",cog:"settings",gear:"settings",sliders:"settings",rotatecw:"refresh",rotateccw:"refresh",refreshcw:"refresh",heart:"favorite",heartoff:"favoriteOff",volume:"volumeUp",volume1:"volumeDown",volume2:"volumeUp",volumex:"volumeOff",skipforward:"skipNext",skipback:"skipPrevious",paperclip:"attachFile",link:"share",share2:"share",magnifyingglass:"search",searchicon:"search"};function F(e){return e.replace(/[\s._-]/g,"").toLowerCase()}function _(e){let n=F(e);return ke.get(n)??Te[n]}function k(e,...n){for(let t of n){let i=e[t];if(typeof i==="string"||typeof i==="number"||typeof i==="boolean")return String(i)}return}function Oe(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var T={ForEach:(e,n)=>{let t=k(e,"expression");if(t==null){n.note("unsupported","ForEach","no expression to iterate");return}let i=n.bind(t);if(i.kind!=="binding"){n.note("expression","ForEach",`"${t}" is not a plain path, so there is no list to bind`);return}let r=n.inScope({$item:"",$index:""},()=>n.single(e.children));if(r==null){n.note("unsupported","ForEach","the loop body had nothing to render");return}return{component:"Column",children:{path:i.value.path,componentId:r}}},Define:()=>{return},Use:(e,n)=>{let t=k(e,"def","name");if(t==null){n.note("unsupported","Use","no definition name");return}let i=n.definition(t);if(i==null){n.note("unsupported","Use",`no definition named "${t}" was declared`);return}let r=e.overrides,o={};if(r!=null&&typeof r==="object"&&!Array.isArray(r)){let g=n.bindData(`use_${t}`,r);for(let d of Object.keys(r))o[d]=`${g}/${c(d)}`}let s={...Oe(e.slots)?e.slots:{},...Array.isArray(e.children)&&e.children.length>0?{default:e.children}:{}},a=n.expand(t,()=>n.inScope(o,()=>n.withSlots(s,()=>n.single(i))));if(a==null){n.note("unsupported","Use",`definition "${t}" rendered nothing`);return}return{component:"Column",children:[a]}},Slot:(e,n)=>{let t=k(e,"name")??"default",i=n.slotContent(t)??(Array.isArray(e.children)?e.children:void 0),r=i!=null?n.single(i):void 0;if(r==null){n.note("unsupported","Slot",`slot "${t}" had neither content nor a fallback`);return}return{component:"Column",children:[r]}}};for(let e of["If","Elif","Else","Condition","Match","Case"])T[e]=(n,t)=>{t.note("unsupported",n.type,"A2UI has no declarative conditional; the agent re-sends updateComponents when the shape changes");return};var J=["TableHead","TableBody","TableFooter","TableRow","TableCell","TableHeader","ExpandableRow"];function De(e){if(!Array.isArray(e.columns))return[];let n=[];for(let t of e.columns){if(t==null||typeof t!=="object")continue;let i=t,r=typeof i.accessor==="string"?i.accessor:typeof i.key==="string"?i.key:void 0;if(r==null)continue;n.push({key:r,header:typeof i.header==="string"?i.header:r})}return n}function Ie(e,n){let t=e.rows;if(typeof t==="string"){let i=f(t);if(i.kind==="binding")return i.value.path;n.note("expression","DataTable",`rows expression "${t}" is not a plain path; the table has no data source`);return}if(Array.isArray(t))return n.bindData("rows",t);n.note("unsupported","DataTable","no rows to render");return}function j(e,n){let t=De(e);if(t.length===0){n.note("unsupported","DataTable","no usable column definitions");return}let i=Ie(e,n);if(i==null)return;let r=n.push({component:"Row",children:t.map((a)=>n.push({component:"Text",text:a.header,variant:"caption"})),align:"center"}),o=n.push({component:"Row",children:t.map((a)=>n.push({component:"Text",text:{path:a.key.split(".").join("/")}})),align:"center"}),s=n.push({component:"Column",children:{path:i,componentId:o}});if(e.search===!0||e.paginated===!0)n.note("degraded","DataTable","search and pagination dropped; A2UI Basic has no table controls");return{component:"Column",children:[r,s]}}function Me(e){let n=[],t=(i)=>{if(i.type==="TableRow"||i.type==="ExpandableRow"){n.push(i);return}if(Array.isArray(i.children))for(let r of i.children)t(r)};if(Array.isArray(e.children))for(let i of e.children)t(i);return n}function Pe(e,n){let t=e.type==="TableHeader";if(Array.isArray(e.children)&&e.children.length>0)return n.single(e.children);let i=e.content??e.text??e.label;if(typeof i!=="string"&&typeof i!=="number"&&typeof i!=="boolean")return;let r=String(i),o=h(r);if(o==null){n.note("expression",e.type,`cell expression "${r}" has no A2UI equivalent`);return}return n.push({component:"Text",text:o,...t&&{variant:"caption"}})}function V(e,n){let t=Me(e),i=[];for(let r of t){let s=(Array.isArray(r.children)?r.children:[]).map((a)=>Pe(a,n)).filter((a)=>a!=null);if(s.length===0)continue;i.push(n.push({component:"Row",children:s,align:"center"}))}if(i.length===0){n.note("unsupported","Table","no rows with renderable cells");return}return n.note("degraded","Table","rendered as a Column of Rows; column widths do not align"),{component:"Column",children:i}}function u(e,...n){for(let t of n){let i=e[t];if(typeof i==="string"||typeof i==="number"||typeof i==="boolean")return String(i)}return}function l(e,n,t){let i=u(e,...t?.keys??["content","text","label","title"]);if(i==null){n.note("unsupported",e.type,"no text content to render");return}let r=n.bind(i);if(r.kind==="unbindable")n.note("expression",e.type,`"${r.expression}" is richer than a JSON Pointer; the text was left as written`);let o=t?.prefix??"",s=t?.suffix??"";if(r.kind==="format"&&r.note!=null)n.note("degraded",e.type,r.note);if(r.kind==="binding"||r.kind==="format"||r.kind==="index"){if(o!==""||s!=="")n.note("degraded",e.type,"Markdown emphasis dropped: the text is a data binding");return{component:"Text",text:r.value,...t?.variant!=null&&{variant:t.variant}}}let a=r.kind==="literal"?r.value:i;return{component:"Text",text:`${o}${a}${s}`,...t?.variant!=null&&{variant:t.variant}}}var Re={start:"start",end:"end",center:"center",between:"spaceBetween",around:"spaceAround",evenly:"spaceEvenly",spaceBetween:"spaceBetween",spaceAround:"spaceAround",spaceEvenly:"spaceEvenly"},Ee={start:"start",end:"end",center:"center",stretch:"stretch",baseline:"baseline"};function y(e){return(n,t)=>{let i=t.children(n.children);if(i.length===0){t.note("unsupported",n.type,`${e} requires at least one child and none survived`);return}let r=typeof n.justify==="string"?Re[n.justify]:void 0,o=typeof n.align==="string"?Ee[n.align]:void 0;return{component:e,children:i,...r!=null&&{justify:r},...o!=null&&{align:o}}}}var Ne=["Div","Container","Stack","Grid","GridItem","Page","Pages","Dashboard","DashboardItem","MasterDetail","Detail","Form","Fieldset","CardContent","CardHeader","CardFooter","Accordion","Carousel","SelectGroup","ComboboxGroup","Section","Article","Aside","Header","Footer","Nav","Span"],Be=["ButtonGroup","Toolbar","Inline"],$e={H1:"# ",H2:"## ",H3:"### ",H4:"#### ",H5:"##### ",H6:"###### "},q={Heading:(e,n)=>{let t=typeof e.level==="number"?Math.min(6,Math.max(1,e.level)):1;return l(e,n,{prefix:`${"#".repeat(t)} `})},Text:(e,n)=>l(e,n),P:(e,n)=>l(e,n),Lead:(e,n)=>l(e,n),Large:(e,n)=>l(e,n),Small:(e,n)=>l(e,n,{variant:"caption"}),Muted:(e,n)=>l(e,n,{variant:"caption"}),Label:(e,n)=>l(e,n,{variant:"caption"}),TableCaption:(e,n)=>l(e,n,{variant:"caption"}),BlockQuote:(e,n)=>l(e,n,{prefix:"> "}),Code:(e,n)=>l(e,n,{prefix:"`",suffix:"`"}),Kbd:(e,n)=>l(e,n,{prefix:"`",suffix:"`"}),Markdown:(e,n)=>l(e,n),Badge:(e,n)=>l(e,n,{keys:["label","content"],variant:"caption"}),CardTitle:(e,n)=>l(e,n,{prefix:"**",suffix:"**"}),CardDescription:(e,n)=>l(e,n,{variant:"caption"}),Tooltip:(e,n)=>l(e,n,{variant:"caption"}),AlertTitle:(e,n)=>l(e,n,{prefix:"**",suffix:"**"}),AlertDescription:(e,n)=>l(e,n)};for(let[e,n]of Object.entries($e))q[e]=(t,i)=>l(t,i,{prefix:n});function O(e){return(n,t)=>{let i=t.dyn(u(n,"src","url"));if(i==null){t.note("unsupported",n.type,"no resolvable source URL");return}let r=e==="Video"?void 0:t.dyn(u(n,"alt","description")),o=e==="Video"?t.dyn(u(n,"poster","posterUrl")):void 0;return{component:e,url:i,...r!=null&&{description:r},...o!=null&&{posterUrl:o}}}}var Ue={text:"shortText",email:"shortText",url:"shortText",tel:"shortText",search:"shortText",password:"obscured",number:"number"};function m(e,n){let t=typeof e.name==="string"?e.name:void 0;if(t==null)return;let i=n.bind(`{{ ${t} }}`);return i.kind==="binding"?i.value:void 0}function P(e,n){let t=m(e,n);if(t==null)return;let i=[];if(e.required===!0)i.push({condition:{call:"required",args:{value:t}}});if(e.inputType==="email")i.push({condition:{call:"email",args:{value:t}}});return i.length>0?i:void 0}function Le(e,n){let t=Array.isArray(e.children)?e.children:[],i=[];for(let r of t){let o=u(r,"value");if(o==null){n.note("degraded",e.type,`dropped a ${r.type} child that carries no option value`);continue}i.push({label:u(r,"label")??o,value:o})}return i}function D(e,n,t){if(u(e,"label","name")==null)n.note("degraded",e.type,"no label available for the DateTimeInput");return{component:"DateTimeInput",value:m(e,n)??"",...t}}function I(e){return(n,t)=>{let i=t.dyn(u(n,"label","name"));if(i==null){t.note("unsupported",n.type,"ChoicePicker requires a label and none could be derived");return}let r=Le(n,t);if(r.length===0){t.note("unsupported",n.type,"no options to choose from");return}let o=m(n,t),s=P(n,t);return{component:"ChoicePicker",label:i,variant:e,options:r,...o!=null&&{value:o},...s!=null&&{checks:s}}}}function H(e,n,t){let i=n.dyn(u(e,"label","name"));if(i==null){n.note("unsupported",e.type,"TextField requires a label and none could be derived");return}let r=m(e,n),o=n.dyn(u(e,"placeholder")),s=P(e,n);return{component:"TextField",label:i,variant:t,...r!=null&&{value:r},...o!=null&&{placeholder:o},...s!=null&&{checks:s}}}var M={Input:(e,n)=>{let t=typeof e.inputType==="string"?e.inputType:"text",i=Ue[t];if(i==null)n.note("degraded",e.type,`inputType "${t}" has no A2UI variant; used shortText`);return H(e,n,i??"shortText")},Textarea:(e,n)=>H(e,n,"longText"),Checkbox:(e,n)=>{let t=n.dyn(u(e,"label","name"));if(t==null){n.note("unsupported",e.type,"CheckBox requires a label and none could be derived");return}let i=P(e,n);return{component:"CheckBox",label:t,value:m(e,n)??!1,...i!=null&&{checks:i}}},Slider:(e,n)=>{let t=typeof e.max==="number"?e.max:void 0;if(t==null){n.note("unsupported",e.type,"Slider requires a max and prefab left it open");return}let i=n.dyn(u(e,"label","name")),r=typeof e.min==="number"?e.min:void 0,o=typeof e.step==="number"?e.step:void 0,s=o!=null&&o>0?Math.max(1,Math.round((t-(r??0))/o)):void 0;return{component:"Slider",max:t,value:m(e,n)??r??0,...i!=null&&{label:i},...r!=null&&{min:r},...s!=null&&{steps:s}}},Button:(e,n)=>{let t=u(e,"label","content")??"Button",i=n.action(e.onClick,"Button")??(e.submit===!0?{event:{name:"submit"}}:void 0);if(i==null){n.note("unsupported",e.type,"Button requires an action and none could be derived");return}let r=n.push({component:"Text",text:n.dyn(t)??t}),o=e.variant==="link"||e.variant==="ghost"?"borderless":e.variant==="default"?"primary":"default";return{component:"Button",child:r,action:i,variant:o}},Link:(e,n)=>{let t=u(e,"href","url");if(t==null){n.note("unsupported",e.type,"no href to open");return}let i=u(e,"content","label")??t;return{component:"Button",child:n.push({component:"Text",text:n.dyn(i)??i}),variant:"borderless",action:{functionCall:{call:"openUrl",args:{url:t}}}}},DatePicker:(e,n)=>D(e,n,{enableDate:!0}),TimePicker:(e,n)=>D(e,n,{enableTime:!0}),DateTimePicker:(e,n)=>D(e,n,{enableDate:!0,enableTime:!0}),Select:I("mutuallyExclusive"),RadioGroup:I("mutuallyExclusive"),Combobox:I("mutuallyExclusive")};M.Switch=M.Checkbox;var Fe={Card:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Card","Card requires a child and it had none");return}return{component:"Card",child:t}},Alert:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Alert","no alert body to render");return}let i=typeof e.variant==="string"?e.variant:"default";return n.note("degraded","Alert",`variant "${i}" rendered as a plain Card`),{component:"Card",child:t}},Separator:()=>({component:"Divider"}),Divider:()=>({component:"Divider"}),Icon:(e,n)=>{let t=u(e,"name","icon");if(t==null){n.note("unsupported","Icon","no icon name");return}let i=_(t);if(i==null){n.note("unsupported","Icon",`"${t}" has no equivalent in the A2UI icon set`);return}if(i!==t)n.note("degraded","Icon",`"${t}" mapped to the A2UI icon "${i}"`);return{component:"Icon",name:i}},Metric:(e,n)=>{let t=[],i=u(e,"label","title");if(i!=null)t.push(n.push({component:"Text",text:n.dyn(i)??i,variant:"caption"}));let r=u(e,"value");if(r!=null)t.push(n.push({component:"Text",text:n.dyn(r)??r}));if(t.length===0){n.note("unsupported","Metric","neither a label nor a value to render");return}return n.note("degraded","Metric","rendered as a Column of Text; trend and delta styling dropped"),{component:"Column",children:t}},Tabs:(e,n)=>{let t=Array.isArray(e.children)?e.children:[],i=[];for(let r of t){let o=n.single(r.children);if(o==null)continue;i.push({title:u(r,"title")??"Tab",child:o})}if(i.length===0){n.note("unsupported","Tabs","no tab had renderable content");return}return{component:"Tabs",tabs:i}},Dialog:(e,n)=>{let t=n.single(e.children);if(t==null){n.note("unsupported","Dialog","no dialog body to render");return}let i=e.trigger,r=i!=null?u(i,"label","content")??u(e,"title")??"Open":u(e,"title")??"Open";return{component:"Modal",trigger:(i!=null?n.child(i):void 0)??n.push({component:"Text",text:n.dyn(r)??r}),content:t}},AccordionItem:(e,n)=>{let t=[],i=u(e,"title");if(i!=null)t.push(n.push({component:"Text",text:i,variant:"caption"}));if(t.push(...n.children(e.children)),t.length===0){n.note("unsupported","AccordionItem","nothing to render");return}return n.note("degraded","AccordionItem","rendered expanded; A2UI Basic has no disclosure component"),{component:"Column",children:t}}},A={Column:y("Column"),Row:y("Row"),...q,...M,...Fe,...T,Image:O("Image"),Video:O("Video"),Audio:O("AudioPlayer"),Table:V,DataTable:j};for(let e of Ne)A[e]??=y("Column");for(let e of Be)A[e]??=y("Row");var _e=new Set(["Tab","SelectOption","ComboboxOption","Radio","Option",...J]),Je={LineChart:"charts",BarChart:"charts",AreaChart:"charts",PieChart:"charts",ScatterChart:"charts",RadarChart:"charts",RadialChart:"charts",Histogram:"charts",Sparkline:"charts",Svg:"inline vector graphics",Mermaid:"diagrams",Embed:"embedded frames",DropZone:"file uploads",Ring:"progress rings",Loader:"loading indicators",Progress:"progress bars"};function z(e){return A[e]}function G(e){return _e.has(e)}function W(){return Object.keys(A).sort()}function K(e,n){let t=Je[e.type];if(t!=null){n.note("unsupported",e.type,`${t} are outside the A2UI Basic catalog`);return}if(Array.isArray(e.children)&&e.children.length>0){let i=n.children(e.children);if(i.length>0)return n.note("degraded",e.type,"no Basic-catalog equivalent; flattened to a Column"),{component:"Column",children:i}}if(u(e,"content","text","label","title")!=null)return n.note("degraded",e.type,"no Basic-catalog equivalent; rendered as Text"),l(e,n);n.note("unsupported",e.type,"no Basic-catalog equivalent and nothing to render");return}var p="v1.0",b="https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",Y="application/a2ui+json",X="a2ui://",C="root";var je=x("a2ui");function Ve(e){let n=e.children;if(e.type==="Div"&&typeof e.cssClass==="string"&&e.cssClass.startsWith("pf-app-root")&&Array.isArray(n)&&n.length===1)return n[0];return e}function Z(e,n){if(e.type==="Define"){let t=typeof e.name==="string"?e.name:void 0;if(t!=null&&Array.isArray(e.children))n.set(t,e.children)}if(Array.isArray(e.children))for(let t of e.children)Z(t,n)}class Q{warn;components=new Map;dataModel=new Map;used=new Set([C]);diagnostics=[];definitions=new Map;counter=0;scope={};slots={};expanding=new Set;constructor(e){this.warn=e}bind(e){return f(e,this.scope)}dyn(e){return h(e,this.scope)}inScope(e,n){let t=this.scope;this.scope={...t,...e};try{return n()}finally{this.scope=t}}withSlots(e,n){let t=this.slots;this.slots={...t,...e};try{return n()}finally{this.slots=t}}slotContent(e){return this.slots[e]}definition(e){if(this.expanding.has(e)){this.note("unsupported","Use",`definition "${e}" uses itself; A2UI has no recursive template`);return}return this.definitions.get(e)}expand(e,n){this.expanding.add(e);try{return n()}finally{this.expanding.delete(e)}}note(e,n,t){if(this.diagnostics.push({kind:e,subject:n,detail:t}),this.warn)je.warn(`${e}: ${n} — ${t}`)}allocate(e){let n=typeof e?.id==="string"&&e.id.length>0?e.id:void 0;if(n!=null&&!this.used.has(n))return this.used.add(n),n;let t;do this.counter+=1,t=`c${this.counter}`;while(this.used.has(t));return this.used.add(t),t}push(e){let n=this.allocate();return this.components.set(n,{id:n,...e}),n}bindData(e,n){let t=e,i=0;while(this.dataModel.has(t))i+=1,t=`${e}${i}`;return this.dataModel.set(t,n),`/${c(t)}`}child(e){return this.emit(e,!1)}children(e){if(!Array.isArray(e))return[];let n=[];for(let t of e){if(t==null||typeof t!=="object")continue;let i=this.emit(t,!1);if(i!=null)n.push(i)}return n}single(e){let n=this.children(e);if(n.length===0)return;if(n.length===1)return n[0];return this.push({component:"Column",children:n})}action(e,n){if(e==null)return;if(Array.isArray(e)){if(e.length===0)return;if(e.length>1)this.note("action",n,`${e.length} actions were bound; A2UI carries one, so the rest were dropped`);return this.action(e[0],n)}if(typeof e!=="object")return;let t=e,i=typeof t.action==="string"?t.action:void 0;if(i==null)return;switch(i){case"toolCall":case"callTool":{let r=typeof t.tool==="string"?t.tool:void 0;if(r==null)return;let o=this.eventContext(t.arguments,n);return{event:{name:r,...o!=null&&{context:o}}}}case"sendMessage":return{event:{name:"sendMessage",context:{message:typeof t.message==="string"?t.message:""}}};case"openLink":{let r=typeof t.url==="string"?t.url:typeof t.href==="string"?t.href:void 0;if(r==null)return;return{functionCall:{call:"openUrl",args:{url:r}}}}default:{this.note("action",n,`"${i}" has no renderer-side equivalent; emitted as an agent event`);let{action:r,...o}=t,s=this.eventContext(o,n);return{event:{name:i,...s!=null&&{context:s}}}}}}eventContext(e,n){if(e==null||typeof e!=="object"||Array.isArray(e))return;let t={};for(let[i,r]of Object.entries(e)){if(typeof r==="number"||typeof r==="boolean"||r===null){t[i]=r;continue}if(typeof r!=="string"){this.note("action",n,`argument "${i}" is not a scalar and was dropped from the event context`);continue}let o=f(r);if(o.kind==="unbindable"){this.note("action",n,`argument "${i}" uses "${o.expression}", which A2UI cannot bind; it was dropped`);continue}t[i]=o.kind==="binding"?o.value:o.value}return Object.keys(t).length>0?t:void 0}rollback(e,n){let t=[...this.components.keys()];for(let r=e;r<t.length;r++)if(this.components.delete(t[r]),t[r]!==C)this.used.delete(t[r]);let i=[...this.dataModel.keys()];for(let r=n;r<i.length;r++)this.dataModel.delete(i[r])}emit(e,n){if(typeof e.type!=="string")return;if(G(e.type)){this.note("unsupported",e.type,"only meaningful inside its parent; emitted standalone it has no meaning");return}let t=this.components.size,i=this.dataModel.size,r=n?C:this.allocate(e);this.components.set(r,void 0);let s=(z(e.type)??K)(e,this);if(s==null){this.rollback(t,i);return}return this.components.set(r,{id:r,...s}),r}finish(e,n){let t=n.surfaceId??"prefab";for(let[d,oe]of Object.entries(e.defs??{}))this.definitions.set(d,[oe]);if(Z(e.view,this.definitions),this.emit(Ve(e.view),!0)==null)this.note("unsupported","view","nothing in the view could be expressed in A2UI; the surface is empty");let r=[];for(let d of this.components.values())if(d!=null)r.push(d);let o={...Object.fromEntries(this.dataModel),...e.state??{}},s=Object.keys(o).length>0,a=[],g=n.catalogId??b;if(n.stream===!0){if(a.push({version:p,createSurface:{surfaceId:t,catalogId:g,...n.sendDataModel===!0&&{sendDataModel:!0}}}),r.length>0)a.push({version:p,updateComponents:{surfaceId:t,components:r}});if(s)a.push({version:p,updateDataModel:{surfaceId:t,value:o}})}else a.push({version:p,createSurface:{surfaceId:t,catalogId:g,...n.sendDataModel===!0&&{sendDataModel:!0},...r.length>0&&{components:r},...s&&{dataModel:o}}});return{messages:a,diagnostics:this.diagnostics}}}function ee(e,n){let t=n??{};return new Q(t.warn===!0).finish(e,t)}var ne="0.3.11";function te(e,n){if(e==null||typeof e!=="object"||!("view"in e))throw TypeError('PrefabA2UI.emit: expected a $prefab payload with a "view"');return ee(e,n)}function ie(e){return{messages:e}}var re={emit:te,envelope:ie,mappedTypes:W,VERSION:ne,A2UI_VERSION:p,A2UI_BASIC_CATALOG:b,A2UI_MIME:Y,A2UI_SCHEME:X},qe=re;if(typeof window<"u")window.PrefabA2UI=re;})();
|
package/dist/core/version.d.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* `release.yml` (see `scripts/changelog-release.ts` companion step). Identifies
|
|
10
10
|
* the app to an MCP Apps host (`appInfo.version`) and pins the CDN URL.
|
|
11
11
|
*/
|
|
12
|
-
export declare const VERSION = "0.3.
|
|
12
|
+
export declare const VERSION = "0.3.11";
|
|
13
13
|
/**
|
|
14
14
|
* Wire protocol version emitted in `$prefab.version`.
|
|
15
15
|
*
|
package/dist/core/version.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* `release.yml` (see `scripts/changelog-release.ts` companion step). Identifies
|
|
10
10
|
* the app to an MCP Apps host (`appInfo.version`) and pins the CDN URL.
|
|
11
11
|
*/
|
|
12
|
-
export const VERSION = '0.3.
|
|
12
|
+
export const VERSION = '0.3.11';
|
|
13
13
|
/**
|
|
14
14
|
* Wire protocol version emitted in `$prefab.version`.
|
|
15
15
|
*
|
|
@@ -13,4 +13,4 @@ ${n}
|
|
|
13
13
|
${bt(e.dark," ")}
|
|
14
14
|
}
|
|
15
15
|
}`)}return t.join(`
|
|
16
|
-
`)}function be(e,t){e.setAttribute("data-theme",t),e.classList.toggle("dark",t==="dark"),e.classList.toggle("light",t==="light")}function vt(e,t){if(!t)return;if(t.light)for(let[n,r]of Object.entries(t.light))e.style.setProperty(`--${yt(n)}`,Ct(r));if(t.dark){let r=document.getElementById("prefab-dark-theme");if(!r)r=document.createElement("style"),r.id="prefab-dark-theme",document.head.appendChild(r);r.textContent=kn({dark:t.dark})}}function wt(e,t){if(!e||typeof document>"u")return;let n=(r)=>{for(let[o,i]of Object.entries(e))if(li(o,r))r.preventDefault(),t(i)};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)}function li(e,t){let n=e.toLowerCase().split("+").map((i)=>i.trim()),r=n[n.length-1],o=new Set(n.slice(0,-1));if(o.has("ctrl")!==(t.ctrlKey||t.metaKey))return!1;if(o.has("shift")!==t.shiftKey)return!1;if(o.has("alt")!==t.altKey)return!1;return t.key.toLowerCase()===r}var Sn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"/></svg>',En='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"/></svg>',An={"top-right":"top: 8px; right: 8px;","top-left":"top: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;"};function di(e,t){try{let r=localStorage.getItem(t);if(r==="light"||r==="dark")return r}catch{}let n=e.getAttribute("data-theme")??document.documentElement.getAttribute("data-theme");if(n==="light"||n==="dark")return n;if(typeof window<"u"&&window.matchMedia("(prefers-color-scheme: light)").matches)return"light";return"dark"}function xt(e,t){if(typeof document>"u")return()=>{};let n=t?.position??"top-right",r=t?.storageKey??"prefab-theme",o=t?.syncDocument??!0,i=getComputedStyle(e).position;if(i==="static"||i==="")e.style.position="relative";let s=document.createElement("button");s.className="pf-theme-toggle",s.setAttribute("aria-label","Toggle theme"),s.setAttribute("title","Toggle light/dark"),Object.assign(s.style,{position:"absolute",zIndex:"100",width:"28px",height:"28px",border:"1px solid var(--border, #e5e7eb)",borderRadius:"6px",background:"var(--card, rgba(255,255,255,0.8))",color:"var(--foreground, #333)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",opacity:"0.7",transition:"opacity 0.15s, border-color 0.15s"});let a=An[n]??An["top-right"];for(let d of a.split(";")){let[g,h]=d.split(":").map((y)=>y.trim());if(g&&h)s.style.setProperty(g,h)}s.addEventListener("mouseenter",()=>{s.style.opacity="1"}),s.addEventListener("mouseleave",()=>{s.style.opacity="0.7"});function l(d){if(be(e,d),o)be(document.documentElement,d);s.innerHTML=d==="dark"?En:Sn;try{localStorage.setItem(r,d)}catch{}}let c=di(e,r);l(c),s.addEventListener("click",()=>{let d=e.getAttribute("data-theme")??"dark";l(d==="dark"?"light":"dark")}),e.appendChild(s);let u;if(o)u=new MutationObserver((d)=>{for(let g of d)if(g.type==="attributes"&&g.attributeName==="data-theme"){let h=document.documentElement.getAttribute("data-theme");if((h==="light"||h==="dark")&&h!==e.getAttribute("data-theme")){be(e,h),s.innerHTML=h==="dark"?En:Sn;try{localStorage.setItem(r,h)}catch{}}}}),u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});return()=>{u?.disconnect(),s.remove()}}function _e(e){let t=e?.baseUrl??(typeof window<"u"?window.location.origin:""),n={"Content-Type":"application/json",...e?.headers},r=e?.fetch??globalThis.fetch.bind(globalThis);return{async callTool(o,i){let s=await r(`${t}/mcp/tools/call`,{method:"POST",headers:n,body:JSON.stringify({jsonrpc:"2.0",method:"tools/call",params:{name:o,arguments:i}})});if(!s.ok)throw Error(`MCP tool call failed: ${s.status} ${s.statusText}`);let a=await s.json();if(a.error)throw Error(a.error.message??"MCP tool call returned error");let l=a.result?.content??a.content??[];for(let c of l)if(c.type==="text"&&c.text!==void 0){try{let u=JSON.parse(c.text);if(typeof u==="object"&&u!==null&&"$prefab"in u)return u;return u}catch{}return c.text}return a.result??a},async sendMessage(o){await r(`${t}/mcp/messages`,{method:"POST",headers:n,body:JSON.stringify({message:o})})}}}function Ve(){return{callTool(e){return O.warn(`No MCP transport: callTool('${e}') ignored`),Promise.resolve(null)},sendMessage(e){return O.warn("No MCP transport: sendMessage ignored",e),Promise.resolve()}}}var Rn="0.3.10";function ci(e){return e!==null&&typeof e==="object"&&e.jsonrpc==="2.0"}class xe{hostOrigin;listeners=new Map;protocol="prefab";cleanup;pending=new Map;callIdCounter=0;rpcPending=new Map;rpcIdCounter=0;sentRpcIds=new Set;postFn;_hostSupportsSubscriptions=!1;constructor(e="*"){this.hostOrigin=e}connect(){if(typeof window>"u")return;let e=fi();if(e)this.postFn=(n)=>e.postMessage(n);let t=(n)=>{if(this.hostOrigin!=="*"&&n.origin!==this.hostOrigin)return;let r=n.data;if(ci(r)){this.handleJsonRpc(r);return}let o=r;if(!o?.type.startsWith("prefab:"))return;if(o.type==="prefab:tool-call-response"&&o.id){let s=this.pending.get(o.id);if(s){if(this.pending.delete(o.id),o.payload?.error!=null)s.reject(Error(o.payload.error));else s.resolve(o.payload?.result);return}}let i=this.listeners.get(o.type);if(i)for(let s of i)s(o.payload??{})};window.addEventListener("message",t),this.cleanup=()=>window.removeEventListener("message",t)}async initialize(e){try{return await Promise.any([this.initPrefab(e),this.initJsonRpc(e)])}catch(t){let n=t instanceof AggregateError?t.errors.map((r)=>r.message).join("; "):String(t);throw Error(`Bridge init failed — no host responded. Tried: ${n}`,{cause:t})}}createTransport(){if(this.protocol==="jsonrpc")return this.createJsonRpcTransport();return this.createPrefabTransport()}requestMode(e){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/request-display-mode",{mode:e});else this.sendPrefab("prefab:request-mode",{mode:e})}openLink(e,t){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/open-link",{url:e,target:t});else this.sendPrefab("prefab:open-link",{url:e,target:t})}updateContext(e){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/update-model-context",{structuredContent:e});else this.sendPrefab("prefab:update-context",{context:e})}setupAutoResize(e){if(typeof ResizeObserver>"u")return pi;let t=-1,n=-1,r=(s,a)=>{if(s===t&&a===n)return;if(t=s,n=a,this.protocol==="jsonrpc")this.sendRpcNotification("ui/notifications/size-changed",{width:s,height:a});else this.sendPrefab("prefab:size-changed",{width:s,height:a})},o=new ResizeObserver((s)=>{for(let a of s)if(a.borderBoxSize.length){let l=a.borderBoxSize[0];r(Math.ceil(l.inlineSize),Math.ceil(l.blockSize))}else{let l=a.target.getBoundingClientRect();r(Math.ceil(l.width),Math.ceil(l.height))}});o.observe(e);let i=e.getBoundingClientRect();return r(Math.ceil(i.width),Math.ceil(i.height)),()=>o.disconnect()}notifyPreferredSize(e){if(this.protocol==="jsonrpc")this.sendRpcNotification("ui/notifications/preferred-size",e);else this.sendPrefab("prefab:preferred-size",e)}subscribe(e,t){let n=(r)=>{if(r.uri!==e)return;t(r.contents??r.data??r)};if(this.protocol==="jsonrpc")this.on("prefab:resource-updated",n),this.sendRpcRequest("resources/subscribe",{uri:e});else this.on("prefab:resource-updated",n),this.sendPrefab("prefab:subscribe",{uri:e});return()=>{if(this.off("prefab:resource-updated",n),this.protocol==="jsonrpc")this.sendRpcRequest("resources/unsubscribe",{uri:e});else this.sendPrefab("prefab:unsubscribe",{uri:e})}}get supportsSubscriptions(){return this._hostSupportsSubscriptions}on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);let n=this.listeners.get(e);if(n)n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}disconnect(){this.cleanup?.(),this.listeners.clear();for(let[,e]of this.pending)e.reject(Error("Bridge disconnected"));this.pending.clear();for(let[,e]of this.rpcPending)e.reject(Error("Bridge disconnected"));this.rpcPending.clear(),this.sentRpcIds.clear()}get activeProtocol(){return this.protocol}initPrefab(e){return new Promise((t,n)=>{let r=!1,o=(i)=>{if(r)return;r=!0,this.off("prefab:init-response",o),this.protocol="prefab";let s=i.capabilities;this._hostSupportsSubscriptions=s?.subscriptions===!0,t(i)};this.on("prefab:init-response",o),this.sendPrefab("prefab:init",{capabilities:e}),setTimeout(()=>{if(!r)r=!0,this.off("prefab:init-response",o),n(Error("prefab:init timeout"))},2000)})}createPrefabTransport(){return{callTool:(e,t)=>{let n=`tc-${++this.callIdCounter}`;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.sendPrefab("prefab:tool-call",{tool:e,arguments:t},n),setTimeout(()=>{if(this.pending.has(n))this.pending.delete(n),o(Error(`Tool call '${e}' timed out`))},30000)})},sendMessage:(e)=>(this.sendPrefab("prefab:send-message",{message:e}),Promise.resolve()),subscribe:(e,t)=>this.subscribe(e,t),capabilities:{subscriptions:this._hostSupportsSubscriptions}}}sendPrefab(e,t,n){if(typeof window>"u")return;let r=window.parent!==window?window.parent:window,o={type:e,payload:t,id:n};r.postMessage(o,this.hostOrigin)}handleJsonRpc(e){if(!("method"in e)){let r=this.rpcPending.get(e.id);if(r)if(this.rpcPending.delete(e.id),e.error)r.reject(Error(e.error.message));else r.resolve(e.result);return}let t=e.method,n=e.params??{};if(e.id!=null&&this.sentRpcIds.delete(e.id))return;if(e.id!=null)this.postJsonRpc({jsonrpc:"2.0",id:e.id,result:{}});switch(t){case"ui/notifications/tool-input":this.dispatch("prefab:tool-input",{args:n.arguments??n});break;case"ui/notifications/tool-input-partial":this.dispatch("prefab:tool-input-partial",{args:n.arguments??n});break;case"ui/notifications/tool-result":this.dispatch("prefab:tool-result",{result:n});break;case"ui/notifications/tool-cancelled":this.dispatch("prefab:tool-cancelled",n);break;case"ui/notifications/host-context-changed":{let r={};if(typeof n.theme==="string")r.colorScheme=n.theme;if(typeof n.styles==="object"&&n.styles!==null){let o=n.styles;if(o.variables)r.variables=o.variables;if(typeof o.css?.fonts==="string")r.fontCss=o.css.fonts}this.dispatch("prefab:theme-update",r),this.dispatch("prefab:host-context-changed",n);break}case"ui/resource-teardown":this.dispatch("prefab:teardown",n);break;case"ui/notifications/resource-updated":case"notifications/resources/updated":this.dispatch("prefab:resource-updated",n);break}}initJsonRpc(e){return new Promise((t,n)=>{let r=++this.rpcIdCounter,o=!1;this.rpcPending.set(r,{resolve:(i)=>{if(o)return;o=!0,this.protocol="jsonrpc";let s=i??{},a=s.hostInfo??{},l=s.hostContext??{},c=s.hostCapabilities??{},u;if(typeof l.theme==="string"||typeof l.styles==="object"){if(u={},typeof l.theme==="string")u.colorScheme=l.theme;if(typeof l.styles==="object"&&l.styles!==null){let g=l.styles;if(g.variables)u.variables=g.variables;if(typeof g.css?.fonts==="string")u.fontCss=g.css.fonts}}this.postJsonRpc({jsonrpc:"2.0",method:"ui/notifications/initialized",params:{}});let d=c.resources;this._hostSupportsSubscriptions=c.subscriptions===!0||d?.subscribe===!0,t({hostName:a.name,hostVersion:a.version,capabilities:{toast:!0,navigation:c.openLinks!=null,messaging:!0,displayModes:l.availableDisplayModes??[]},theme:u,toolInput:void 0,meta:l})},reject:(i)=>{if(o)return;o=!0,n(i)}}),this.postJsonRpc({jsonrpc:"2.0",id:r,method:"ui/initialize",params:{protocolVersion:"2026-01-26",appInfo:{name:"prefab",version:Rn},appCapabilities:{...e.displayModes&&{availableDisplayModes:e.displayModes}}}}),setTimeout(()=>{if(!o)o=!0,this.rpcPending.delete(r),n(Error("ui/initialize timeout"))},2000)})}createJsonRpcTransport(){return{callTool:(e,t)=>this.sendRpcRequest("tools/call",{name:e,arguments:t}),sendMessage:(e)=>this.sendRpcRequest("ui/message",{role:"user",content:{type:"text",text:e}}),subscribe:(e,t)=>this.subscribe(e,t),capabilities:{subscriptions:this._hostSupportsSubscriptions}}}sendRpcRequest(e,t){let n=++this.rpcIdCounter;return new Promise((r,o)=>{this.rpcPending.set(n,{resolve:r,reject:o}),this.postJsonRpc({jsonrpc:"2.0",id:n,method:e,params:t}),setTimeout(()=>{if(this.rpcPending.has(n))this.rpcPending.delete(n),o(Error(`JSON-RPC '${e}' timed out`))},30000)})}sendRpcNotification(e,t){this.postJsonRpc({jsonrpc:"2.0",method:e,params:t})}postJsonRpc(e){if(typeof window>"u")return;if(e.id!=null&&typeof e.method==="string")this.sentRpcIds.add(e.id);if(this.postFn)this.postFn(e);else(window.parent!==window?window.parent:window).postMessage(e,this.hostOrigin)}dispatch(e,t){let n=this.listeners.get(e);if(n)for(let r of n)r(t)}}var pi=()=>{};function kt(e,t){if(t.variables)for(let[n,r]of Object.entries(t.variables))e.style.setProperty(n.startsWith("--")?n:`--${n}`,r);if(t.colorScheme&&t.colorScheme!=="auto")e.setAttribute("data-theme",t.colorScheme);if(t.fontCss)ui(t.fontCss)}function ui(e){if(document.getElementById("__prefab-host-fonts"))return;let n=document.createElement("style");n.id="__prefab-host-fonts",n.textContent=e,document.head.appendChild(n)}function Ke(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function fi(){if(typeof window>"u")return;let e=window;if(typeof e.acquireVsCodeApi==="function")try{let t=e.acquireVsCodeApi();if(t!==null&&typeof t==="object"&&"postMessage"in t)return t}catch{return}return}var Tn=["Accordion","AccordionItem","Alert","AlertDescription","AlertTitle","AreaChart","Audio","Badge","BarChart","BlockQuote","Button","ButtonGroup","Calendar","Card","CardContent","CardDescription","CardFooter","CardHeader","CardTitle","Carousel","Checkbox","ChoiceCard","Code","Column","Combobox","ComboboxGroup","ComboboxLabel","ComboboxOption","ComboboxSeparator","Condition","Container","Dashboard","DashboardItem","DataTable","DatePicker","Define","Detail","Dialog","Div","Dot","DropZone","Elif","Else","Embed","ExpandableRow","Field","FieldContent","FieldDescription","FieldError","FieldTitle","ForEach","Form","Grid","GridItem","H1","H2","H3","H4","Heading","Histogram","HoverCard","Icon","If","Image","Input","Kbd","Label","Large","Lead","LineChart","Link","Loader","Markdown","MasterDetail","Mermaid","Metric","Muted","P","Page","Pages","PdfViewer","PieChart","Popover","Progress","RadarChart","RadialChart","Radio","RadioGroup","Ring","Row","ScatterChart","Select","SelectGroup","SelectLabel","SelectOption","SelectSeparator","Separator","Slider","Slot","Small","Span","Sparkline","Svg","Switch","Tab","Table","TableBody","TableCaption","TableCell","TableFooter","TableHead","TableHeader","TableRow","Tabs","Text","Textarea","Tooltip","Use","Video"];var Ln=new Set(Tn);function Et(e,t={}){let n=[],r=t.strict??!1;if(e==null||typeof e!=="object")return n.push({path:"$",message:"Wire data must be a non-null object"}),{valid:!1,errors:n};let o=e;if(o.$prefab==null||typeof o.$prefab!=="object")n.push({path:"$.$prefab",message:"Missing or invalid $prefab header"});else if(typeof o.$prefab.version!=="string")n.push({path:"$.$prefab.version",message:"version must be a string"});if(o.view==null)n.push({path:"$.view",message:'Missing required "view" field'});else St(o.view,"$.view",n,r);if(o.state!==void 0){if(o.state===null||typeof o.state!=="object"||Array.isArray(o.state))n.push({path:"$.state",message:"state must be a plain object"})}if(o.theme!==void 0)gi(o.theme,n);if(o.css!==void 0)Mn(o.css,"$.css",n);if(o.stylesheets!==void 0)Mn(o.stylesheets,"$.stylesheets",n);if(o.mode!==void 0&&o.mode!=="light"&&o.mode!=="dark")n.push({path:"$.mode",message:'mode must be "light" or "dark"'});if(o.defs!==void 0)if(o.defs===null||typeof o.defs!=="object"||Array.isArray(o.defs))n.push({path:"$.defs",message:"defs must be a plain object"});else for(let[i,s]of Object.entries(o.defs))St(s,`$.defs.${i}`,n,r);if(o.keyBindings!==void 0)if(o.keyBindings===null||typeof o.keyBindings!=="object"||Array.isArray(o.keyBindings))n.push({path:"$.keyBindings",message:"keyBindings must be a plain object"});else for(let[i,s]of Object.entries(o.keyBindings))At(s,`$.keyBindings.${i}`,n);return{valid:n.length===0,errors:n}}function St(e,t,n,r){if(e==null||typeof e!=="object"||Array.isArray(e)){n.push({path:t,message:"Component must be a plain object"});return}let o=e;if(typeof o.type!=="string"||o.type.length===0){n.push({path:`${t}.type`,message:'Component must have a non-empty "type" string'});return}if(r&&!Ln.has(o.type))n.push({path:`${t}.type`,message:`Unknown component type: "${o.type}"`});if(o.children!==void 0)if(!Array.isArray(o.children))n.push({path:`${t}.children`,message:"children must be an array"});else for(let s=0;s<o.children.length;s++)St(o.children[s],`${t}.children[${s}]`,n,r);let i=["onClick","on_click","onChange","on_change","onSubmit","on_submit","onMount","on_mount","onClose","on_close"];for(let s of i)if(o[s]!==void 0)At(o[s],`${t}.${s}`,n);for(let[s,a]of Object.entries(o)){if(s==="type"||mi.has(s)||i.includes(s))continue;if(Nn(a)||Array.isArray(a)&&a.some(Nn))n.push({path:`${t}.${s}`,message:`Components under "${s}" are ignored by the renderer; move them into "children"`})}}var mi=new Set(["children","fallback","trigger","empty","else","summary"]);function Nn(e){if(e==null||typeof e!=="object"||Array.isArray(e))return!1;let t=e.type;return typeof t==="string"&&Ln.has(t)}function At(e,t,n){if(Array.isArray(e)){for(let a=0;a<e.length;a++)At(e[a],`${t}[${a}]`,n);return}if(e==null||typeof e!=="object"){n.push({path:t,message:"Action must be an object or array of objects"});return}let r=e,o=typeof r.type==="string"&&r.type.length>0,i=typeof r.action==="string"&&r.action.length>0;if(!o&&!i){n.push({path:`${t}.type`,message:'Action must have a non-empty "type" or "action" string'});return}if((i?r.action:r.type).toLowerCase()==="showtoast"){if(typeof r.message!=="string"||r.message.length===0)n.push({path:`${t}.message`,message:'showToast requires a non-empty "message" string'})}}function Mn(e,t,n){if(!Array.isArray(e)){n.push({path:t,message:`${t} must be an array of strings`});return}for(let r=0;r<e.length;r++)if(typeof e[r]!=="string")n.push({path:`${t}[${r}]`,message:"must be a string"})}function gi(e,t){if(e===null||typeof e!=="object"||Array.isArray(e)){t.push({path:"$.theme",message:"theme must be a plain object"});return}let n=e;for(let r of["light","dark"])if(n[r]!==void 0){if(n[r]===null||typeof n[r]!=="object"||Array.isArray(n[r]))t.push({path:`$.theme.${r}`,message:`theme.${r} must be a plain object`})}}var Z={mount(e,t,n){if(We(),n?.validate!==!1)for(let b of Et(t).errors)O.warn(`wire validation ${b.path}: ${b.message}`);let r=t,o={tracked:[],evalBlocked:!1};if(r.pipes)for(let[b,w]of Object.entries(r.pipes))Hn(b,w,o);let i=new ye(r.state),s;if(n?.transport&&"callTool"in n.transport)s=n.transport;else if(n?.transport)s=_e(n.transport);else s=Ve();let a=n?.onToast??yi,l=new ot;function c(b){let w=b;if(r=w,w.state)i.merge(w.state);if(w.defs)u.defs=w.defs;if(w.theme)vt(e,w.theme);if(w.mode)Pn(e,w.mode);if(w.pipes)for(let[S,N]of Object.entries(w.pipes))Hn(S,N,o);for(let S of d)S.remove();if(d.length=0,d.push(...$n(w.css,w.stylesheets)),On(e,w.layout),g?.(),g=void 0,w.keyBindings)g=wt(w.keyBindings,(S)=>{F(j(S,{store:i,transport:s,scope:{},rerender:()=>f(),remount:c,onToast:a}),"keyBinding")});f()}let u={store:i,scope:{},transport:s,rerender:()=>f(),remount:c,onToast:a,defs:r.defs,destroyRegistry:l};if(vt(e,r.theme),r.mode)Pn(e,r.mode);On(e,r.layout);let d=$n(r.css,r.stylesheets),g;if(r.keyBindings)g=wt(r.keyBindings,(b)=>{F(j(b,{store:i,transport:s,scope:{},rerender:()=>f(),remount:c,onToast:a}),"keyBinding")});let h,y=n?.themeToggle??!0;if(y!==!1)h=xt(e,typeof y==="object"?y:void 0);function f(){l.flush();let b=e.querySelector(".pf-theme-toggle");e.innerHTML="";let w=J(r.view,u);if(e.appendChild(w),b)e.appendChild(b)}return f(),{rerender:()=>f(),update(b){if(i.merge(b.update.state),f(),b.update.actions!=null)F(j(b.update.actions,u),"update action")},store:i,destroy(){l.flush(),h?.(),g?.(),Ft(),Bt();for(let b of d)b.remove();for(let b of o.tracked)Xe(b);e.innerHTML=""}}},isPrefabData(e){return e!=null&&typeof e==="object"&&"$prefab"in e},isPrefabUpdate(e){return e!=null&&typeof e==="object"&&"$prefab"in e&&"update"in e}},hi=new Set(["find","dot","length","upper","lower","truncate","join","first","last","abs","round","number","currency","percent","compact","date","time","datetime","pluralize","default","selectattr","rejectattr"]);function bi(e){if(e instanceof EvalError)return!0;return e instanceof Error&&/unsafe-eval|Content Security Policy|call to Function/i.test(e.message)}function Hn(e,t,n){if(hi.has(e)){O.warn(`wire pipe "${e}" ignored — shadows built-in`);return}if(ke(e)!=null){O.debug(`wire pipe "${e}" — already registered, keeping local implementation`);return}if(n.evalBlocked)return;try{let r=Function("return ("+t+")")();if(typeof r!=="function"){O.warn(`wire pipe "${e}" — source did not evaluate to a function`);return}Ue(e,r),n.tracked.push(e)}catch(r){if(bi(r)){n.evalBlocked=!0,O.warn("wire pipes cannot be hydrated — this host's CSP forbids eval. Pre-register them with "+"prefab.registerPipe() from a companion script (rendererHtml({ scripts })) and they are used as-is.");return}O.warn(`wire pipe "${e}" — failed to hydrate:`,r)}}function yi(e){if(typeof document>"u")return;let t=vi(),n=document.createElement("div"),r=e.variant??"default";n.className=`pf-toast${r!=="default"?` pf-toast--${r}`:""}`,n.setAttribute("data-variant",r),n.style.marginBottom="8px",n.style.transition="opacity 0.3s ease";let o=document.createElement("div");if(o.textContent=e.message,o.style.fontWeight="500",n.appendChild(o),e.description){let s=document.createElement("div");s.textContent=e.description,s.style.fontSize="14px",s.style.color="var(--muted-foreground, #6b7280)",n.appendChild(s)}t.appendChild(n);let i=e.duration??4000;setTimeout(()=>{n.style.opacity="0",setTimeout(()=>n.remove(),300)},i)}function Pn(e,t){if(be(e,t),typeof document<"u")be(document.documentElement,t)}function Ci(e){let t=e.trim();if(t.includes("{")||t.includes("}"))return!1;return/^(https?:)?\/\//i.test(t)||t.startsWith("/")||/\.css(\?|#|$)/i.test(t)}function $n(e,t){let n=[];if(typeof document>"u")return n;for(let r of e??[]){let o=document.createElement("style");o.textContent=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}for(let r of t??[])if(Ci(r)){let o=document.createElement("link");o.rel="stylesheet",o.href=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}else{let o=document.createElement("style");o.textContent=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}return n}function On(e,t){if(e.style.height="",e.style.minHeight="",e.style.maxHeight="",e.style.overflow="",!t)return;if(t.preferredHeight!=null)e.style.height=`${t.preferredHeight}px`;if(t.minHeight!=null)e.style.minHeight=`${t.minHeight}px`;if(t.maxHeight!=null)e.style.maxHeight=`${t.maxHeight}px`,e.style.overflow="auto"}function vi(){let t=document.getElementById("prefab-toast-container");if(!t)t=document.createElement("div"),t.id="prefab-toast-container",t.style.position="fixed",t.style.bottom="16px",t.style.right="16px",t.style.zIndex="9999",t.style.maxWidth="400px",document.body.appendChild(t);return t}if(typeof window<"u"){let e=window;e.PrefabRenderer=Z,e.prefab={app:Ge,mount:Z.mount.bind(Z),isPrefabData:Z.isPrefabData.bind(Z),isPrefabUpdate:Z.isPrefabUpdate.bind(Z),Bridge:xe,isIframe:Ke,registerPipe:Ue,unregisterPipe:Xe,listPipes:$t,registerComponent:p,createThemeToggle:xt,validateWireFormat:Et,setLogLevel:Ht};let t=e.__PREFAB_DATA__;if(t!=null){let n=document.getElementById("prefab-root");if(n)Z.mount(n,t)}}async function Ge(e){We();let t=e?.mode??"auto",n=t==="bridge"||t==="auto"&&Ke(),r,o,i={capabilities:{}};if(n)o=new xe(e?.hostOrigin),o.connect(),i=await o.initialize(e?.capabilities??{toolInput:!0}),r=o.createTransport();else if(e?.transport)r=_e(e.transport);else r=Ve();if(i.theme&&typeof document<"u")kt(document.documentElement,i.theme);if(typeof document<"u"&&!o)xi();let s,a,l,c,u,d=i.toolInput,g;if(o)o.on("prefab:tool-input",(f)=>{let b=f.args??f;if(s)s(b);else d=b}),o.on("prefab:tool-result",(f)=>{let b=f.result??f;if(a)a(b);else g=b}),o.on("prefab:tool-cancelled",()=>{l?.()}),o.on("prefab:tool-input-partial",(f)=>{c?.(f.args??f)}),o.on("prefab:theme-update",(f)=>{if(typeof document<"u")kt(document.documentElement,f)}),o.on("prefab:host-context-changed",(f)=>{u?.(f)});function h(f,...b){let w=Rt(f),S=new ye,N={store:S,scope:{},transport:r,rerender:()=>k(),onToast:void 0};function k(){w.innerHTML="";for(let R of b)w.appendChild(J(R,N))}return k(),{rerender:k,store:S,destroy:()=>{w.innerHTML=""}}}return{callTool:(f,b={})=>r.callTool(f,b),sendMessage:(f)=>r.sendMessage(f),onToolInput:(f)=>{if(s=f,d){let b=d;d=void 0,queueMicrotask(()=>f(b))}},onToolResult:(f)=>{if(a=f,g!==void 0){let b=g;g=void 0,queueMicrotask(()=>f(b))}},onToolCancelled:(f)=>{l=f},onToolInputPartial:(f)=>{c=f},onHostContextChanged:(f)=>{u=f},render:h,mount:(f,b,w)=>{let S=Rt(f);return Z.mount(S,b,{transport:r,...w})},requestMode:(f)=>o?.requestMode(f),openLink:(f,b)=>{if(o)o.openLink(f,b);else if(typeof window<"u")window.open(f,b??"_blank")},updateContext:(f)=>{if(o)o.updateContext(f)},setupAutoResize:(f)=>{if(!o)return wi;let b=typeof f==="string"?Rt(f):f;return o.setupAutoResize(b)},notifyPreferredSize:(f)=>{if(o)o.notifyPreferredSize(f)},host:i,capabilities:i.capabilities,theme:i.theme,transport:r,destroy:()=>o?.disconnect()}}var wi=()=>{};function Rt(e){if(typeof e==="string"){if(typeof document>"u")throw Error("Cannot resolve selector outside browser");let t=document.querySelector(e);if(!t)throw Error(`Element not found: ${e}`);return t}return e}function xi(){function e(){let n=document.body.getAttribute("data-vscode-theme-kind");if(!n)return;let r=n.includes("light")?"light":"dark";document.documentElement.setAttribute("data-theme",r)}e(),new MutationObserver(e).observe(document.body,{attributes:!0,attributeFilter:["data-vscode-theme-kind"]})}var Nt=qe("auto"),Dn="#root";function Tt(e){return Z.isPrefabData(e)}function jn(e){return Z.isPrefabUpdate(e)}function In(e){if(Tt(e))return e;if(e!==null&&typeof e==="object"){let t=e;if(Tt(t.structuredContent))return t.structuredContent;if(Array.isArray(t.content))for(let n of t.content){let r=n;if(r.type==="text"&&typeof r.text==="string")try{let o=JSON.parse(r.text);if(Tt(o))return o}catch{}}}return null}async function Fn(){let e=document.querySelector(Dn);if(!e){Nt.error(`Mount target "${Dn}" not found`);return}let t=e,n=await Ge();n.setupAutoResize(t);let r;function o(i){if(r)r.destroy();if(r=n.mount(t,i),i.layout)n.notifyPreferredSize(i.layout)}n.onToolResult((i)=>{let s=In(i);if(s)o(s);else if(jn(i)&&r)r.update(i)}),n.onToolInput((i)=>{let s=In(i);if(s)o(s);else if(jn(i)&&r)r.update(i)})}function ki(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{Fn().catch((e)=>{Nt.error("Boot failed:",e)})},{once:!0});else queueMicrotask(()=>{Fn().catch((e)=>{Nt.error("Boot failed:",e)})})}ki();})();
|
|
16
|
+
`)}function be(e,t){e.setAttribute("data-theme",t),e.classList.toggle("dark",t==="dark"),e.classList.toggle("light",t==="light")}function vt(e,t){if(!t)return;if(t.light)for(let[n,r]of Object.entries(t.light))e.style.setProperty(`--${yt(n)}`,Ct(r));if(t.dark){let r=document.getElementById("prefab-dark-theme");if(!r)r=document.createElement("style"),r.id="prefab-dark-theme",document.head.appendChild(r);r.textContent=kn({dark:t.dark})}}function wt(e,t){if(!e||typeof document>"u")return;let n=(r)=>{for(let[o,i]of Object.entries(e))if(li(o,r))r.preventDefault(),t(i)};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)}function li(e,t){let n=e.toLowerCase().split("+").map((i)=>i.trim()),r=n[n.length-1],o=new Set(n.slice(0,-1));if(o.has("ctrl")!==(t.ctrlKey||t.metaKey))return!1;if(o.has("shift")!==t.shiftKey)return!1;if(o.has("alt")!==t.altKey)return!1;return t.key.toLowerCase()===r}var Sn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"/></svg>',En='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"/></svg>',An={"top-right":"top: 8px; right: 8px;","top-left":"top: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;"};function di(e,t){try{let r=localStorage.getItem(t);if(r==="light"||r==="dark")return r}catch{}let n=e.getAttribute("data-theme")??document.documentElement.getAttribute("data-theme");if(n==="light"||n==="dark")return n;if(typeof window<"u"&&window.matchMedia("(prefers-color-scheme: light)").matches)return"light";return"dark"}function xt(e,t){if(typeof document>"u")return()=>{};let n=t?.position??"top-right",r=t?.storageKey??"prefab-theme",o=t?.syncDocument??!0,i=getComputedStyle(e).position;if(i==="static"||i==="")e.style.position="relative";let s=document.createElement("button");s.className="pf-theme-toggle",s.setAttribute("aria-label","Toggle theme"),s.setAttribute("title","Toggle light/dark"),Object.assign(s.style,{position:"absolute",zIndex:"100",width:"28px",height:"28px",border:"1px solid var(--border, #e5e7eb)",borderRadius:"6px",background:"var(--card, rgba(255,255,255,0.8))",color:"var(--foreground, #333)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",opacity:"0.7",transition:"opacity 0.15s, border-color 0.15s"});let a=An[n]??An["top-right"];for(let d of a.split(";")){let[g,h]=d.split(":").map((y)=>y.trim());if(g&&h)s.style.setProperty(g,h)}s.addEventListener("mouseenter",()=>{s.style.opacity="1"}),s.addEventListener("mouseleave",()=>{s.style.opacity="0.7"});function l(d){if(be(e,d),o)be(document.documentElement,d);s.innerHTML=d==="dark"?En:Sn;try{localStorage.setItem(r,d)}catch{}}let c=di(e,r);l(c),s.addEventListener("click",()=>{let d=e.getAttribute("data-theme")??"dark";l(d==="dark"?"light":"dark")}),e.appendChild(s);let u;if(o)u=new MutationObserver((d)=>{for(let g of d)if(g.type==="attributes"&&g.attributeName==="data-theme"){let h=document.documentElement.getAttribute("data-theme");if((h==="light"||h==="dark")&&h!==e.getAttribute("data-theme")){be(e,h),s.innerHTML=h==="dark"?En:Sn;try{localStorage.setItem(r,h)}catch{}}}}),u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});return()=>{u?.disconnect(),s.remove()}}function _e(e){let t=e?.baseUrl??(typeof window<"u"?window.location.origin:""),n={"Content-Type":"application/json",...e?.headers},r=e?.fetch??globalThis.fetch.bind(globalThis);return{async callTool(o,i){let s=await r(`${t}/mcp/tools/call`,{method:"POST",headers:n,body:JSON.stringify({jsonrpc:"2.0",method:"tools/call",params:{name:o,arguments:i}})});if(!s.ok)throw Error(`MCP tool call failed: ${s.status} ${s.statusText}`);let a=await s.json();if(a.error)throw Error(a.error.message??"MCP tool call returned error");let l=a.result?.content??a.content??[];for(let c of l)if(c.type==="text"&&c.text!==void 0){try{let u=JSON.parse(c.text);if(typeof u==="object"&&u!==null&&"$prefab"in u)return u;return u}catch{}return c.text}return a.result??a},async sendMessage(o){await r(`${t}/mcp/messages`,{method:"POST",headers:n,body:JSON.stringify({message:o})})}}}function Ve(){return{callTool(e){return O.warn(`No MCP transport: callTool('${e}') ignored`),Promise.resolve(null)},sendMessage(e){return O.warn("No MCP transport: sendMessage ignored",e),Promise.resolve()}}}var Rn="0.3.11";function ci(e){return e!==null&&typeof e==="object"&&e.jsonrpc==="2.0"}class xe{hostOrigin;listeners=new Map;protocol="prefab";cleanup;pending=new Map;callIdCounter=0;rpcPending=new Map;rpcIdCounter=0;sentRpcIds=new Set;postFn;_hostSupportsSubscriptions=!1;constructor(e="*"){this.hostOrigin=e}connect(){if(typeof window>"u")return;let e=fi();if(e)this.postFn=(n)=>e.postMessage(n);let t=(n)=>{if(this.hostOrigin!=="*"&&n.origin!==this.hostOrigin)return;let r=n.data;if(ci(r)){this.handleJsonRpc(r);return}let o=r;if(!o?.type.startsWith("prefab:"))return;if(o.type==="prefab:tool-call-response"&&o.id){let s=this.pending.get(o.id);if(s){if(this.pending.delete(o.id),o.payload?.error!=null)s.reject(Error(o.payload.error));else s.resolve(o.payload?.result);return}}let i=this.listeners.get(o.type);if(i)for(let s of i)s(o.payload??{})};window.addEventListener("message",t),this.cleanup=()=>window.removeEventListener("message",t)}async initialize(e){try{return await Promise.any([this.initPrefab(e),this.initJsonRpc(e)])}catch(t){let n=t instanceof AggregateError?t.errors.map((r)=>r.message).join("; "):String(t);throw Error(`Bridge init failed — no host responded. Tried: ${n}`,{cause:t})}}createTransport(){if(this.protocol==="jsonrpc")return this.createJsonRpcTransport();return this.createPrefabTransport()}requestMode(e){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/request-display-mode",{mode:e});else this.sendPrefab("prefab:request-mode",{mode:e})}openLink(e,t){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/open-link",{url:e,target:t});else this.sendPrefab("prefab:open-link",{url:e,target:t})}updateContext(e){if(this.protocol==="jsonrpc")this.sendRpcRequest("ui/update-model-context",{structuredContent:e});else this.sendPrefab("prefab:update-context",{context:e})}setupAutoResize(e){if(typeof ResizeObserver>"u")return pi;let t=-1,n=-1,r=(s,a)=>{if(s===t&&a===n)return;if(t=s,n=a,this.protocol==="jsonrpc")this.sendRpcNotification("ui/notifications/size-changed",{width:s,height:a});else this.sendPrefab("prefab:size-changed",{width:s,height:a})},o=new ResizeObserver((s)=>{for(let a of s)if(a.borderBoxSize.length){let l=a.borderBoxSize[0];r(Math.ceil(l.inlineSize),Math.ceil(l.blockSize))}else{let l=a.target.getBoundingClientRect();r(Math.ceil(l.width),Math.ceil(l.height))}});o.observe(e);let i=e.getBoundingClientRect();return r(Math.ceil(i.width),Math.ceil(i.height)),()=>o.disconnect()}notifyPreferredSize(e){if(this.protocol==="jsonrpc")this.sendRpcNotification("ui/notifications/preferred-size",e);else this.sendPrefab("prefab:preferred-size",e)}subscribe(e,t){let n=(r)=>{if(r.uri!==e)return;t(r.contents??r.data??r)};if(this.protocol==="jsonrpc")this.on("prefab:resource-updated",n),this.sendRpcRequest("resources/subscribe",{uri:e});else this.on("prefab:resource-updated",n),this.sendPrefab("prefab:subscribe",{uri:e});return()=>{if(this.off("prefab:resource-updated",n),this.protocol==="jsonrpc")this.sendRpcRequest("resources/unsubscribe",{uri:e});else this.sendPrefab("prefab:unsubscribe",{uri:e})}}get supportsSubscriptions(){return this._hostSupportsSubscriptions}on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);let n=this.listeners.get(e);if(n)n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}disconnect(){this.cleanup?.(),this.listeners.clear();for(let[,e]of this.pending)e.reject(Error("Bridge disconnected"));this.pending.clear();for(let[,e]of this.rpcPending)e.reject(Error("Bridge disconnected"));this.rpcPending.clear(),this.sentRpcIds.clear()}get activeProtocol(){return this.protocol}initPrefab(e){return new Promise((t,n)=>{let r=!1,o=(i)=>{if(r)return;r=!0,this.off("prefab:init-response",o),this.protocol="prefab";let s=i.capabilities;this._hostSupportsSubscriptions=s?.subscriptions===!0,t(i)};this.on("prefab:init-response",o),this.sendPrefab("prefab:init",{capabilities:e}),setTimeout(()=>{if(!r)r=!0,this.off("prefab:init-response",o),n(Error("prefab:init timeout"))},2000)})}createPrefabTransport(){return{callTool:(e,t)=>{let n=`tc-${++this.callIdCounter}`;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.sendPrefab("prefab:tool-call",{tool:e,arguments:t},n),setTimeout(()=>{if(this.pending.has(n))this.pending.delete(n),o(Error(`Tool call '${e}' timed out`))},30000)})},sendMessage:(e)=>(this.sendPrefab("prefab:send-message",{message:e}),Promise.resolve()),subscribe:(e,t)=>this.subscribe(e,t),capabilities:{subscriptions:this._hostSupportsSubscriptions}}}sendPrefab(e,t,n){if(typeof window>"u")return;let r=window.parent!==window?window.parent:window,o={type:e,payload:t,id:n};r.postMessage(o,this.hostOrigin)}handleJsonRpc(e){if(!("method"in e)){let r=this.rpcPending.get(e.id);if(r)if(this.rpcPending.delete(e.id),e.error)r.reject(Error(e.error.message));else r.resolve(e.result);return}let t=e.method,n=e.params??{};if(e.id!=null&&this.sentRpcIds.delete(e.id))return;if(e.id!=null)this.postJsonRpc({jsonrpc:"2.0",id:e.id,result:{}});switch(t){case"ui/notifications/tool-input":this.dispatch("prefab:tool-input",{args:n.arguments??n});break;case"ui/notifications/tool-input-partial":this.dispatch("prefab:tool-input-partial",{args:n.arguments??n});break;case"ui/notifications/tool-result":this.dispatch("prefab:tool-result",{result:n});break;case"ui/notifications/tool-cancelled":this.dispatch("prefab:tool-cancelled",n);break;case"ui/notifications/host-context-changed":{let r={};if(typeof n.theme==="string")r.colorScheme=n.theme;if(typeof n.styles==="object"&&n.styles!==null){let o=n.styles;if(o.variables)r.variables=o.variables;if(typeof o.css?.fonts==="string")r.fontCss=o.css.fonts}this.dispatch("prefab:theme-update",r),this.dispatch("prefab:host-context-changed",n);break}case"ui/resource-teardown":this.dispatch("prefab:teardown",n);break;case"ui/notifications/resource-updated":case"notifications/resources/updated":this.dispatch("prefab:resource-updated",n);break}}initJsonRpc(e){return new Promise((t,n)=>{let r=++this.rpcIdCounter,o=!1;this.rpcPending.set(r,{resolve:(i)=>{if(o)return;o=!0,this.protocol="jsonrpc";let s=i??{},a=s.hostInfo??{},l=s.hostContext??{},c=s.hostCapabilities??{},u;if(typeof l.theme==="string"||typeof l.styles==="object"){if(u={},typeof l.theme==="string")u.colorScheme=l.theme;if(typeof l.styles==="object"&&l.styles!==null){let g=l.styles;if(g.variables)u.variables=g.variables;if(typeof g.css?.fonts==="string")u.fontCss=g.css.fonts}}this.postJsonRpc({jsonrpc:"2.0",method:"ui/notifications/initialized",params:{}});let d=c.resources;this._hostSupportsSubscriptions=c.subscriptions===!0||d?.subscribe===!0,t({hostName:a.name,hostVersion:a.version,capabilities:{toast:!0,navigation:c.openLinks!=null,messaging:!0,displayModes:l.availableDisplayModes??[]},theme:u,toolInput:void 0,meta:l})},reject:(i)=>{if(o)return;o=!0,n(i)}}),this.postJsonRpc({jsonrpc:"2.0",id:r,method:"ui/initialize",params:{protocolVersion:"2026-01-26",appInfo:{name:"prefab",version:Rn},appCapabilities:{...e.displayModes&&{availableDisplayModes:e.displayModes}}}}),setTimeout(()=>{if(!o)o=!0,this.rpcPending.delete(r),n(Error("ui/initialize timeout"))},2000)})}createJsonRpcTransport(){return{callTool:(e,t)=>this.sendRpcRequest("tools/call",{name:e,arguments:t}),sendMessage:(e)=>this.sendRpcRequest("ui/message",{role:"user",content:{type:"text",text:e}}),subscribe:(e,t)=>this.subscribe(e,t),capabilities:{subscriptions:this._hostSupportsSubscriptions}}}sendRpcRequest(e,t){let n=++this.rpcIdCounter;return new Promise((r,o)=>{this.rpcPending.set(n,{resolve:r,reject:o}),this.postJsonRpc({jsonrpc:"2.0",id:n,method:e,params:t}),setTimeout(()=>{if(this.rpcPending.has(n))this.rpcPending.delete(n),o(Error(`JSON-RPC '${e}' timed out`))},30000)})}sendRpcNotification(e,t){this.postJsonRpc({jsonrpc:"2.0",method:e,params:t})}postJsonRpc(e){if(typeof window>"u")return;if(e.id!=null&&typeof e.method==="string")this.sentRpcIds.add(e.id);if(this.postFn)this.postFn(e);else(window.parent!==window?window.parent:window).postMessage(e,this.hostOrigin)}dispatch(e,t){let n=this.listeners.get(e);if(n)for(let r of n)r(t)}}var pi=()=>{};function kt(e,t){if(t.variables)for(let[n,r]of Object.entries(t.variables))e.style.setProperty(n.startsWith("--")?n:`--${n}`,r);if(t.colorScheme&&t.colorScheme!=="auto")e.setAttribute("data-theme",t.colorScheme);if(t.fontCss)ui(t.fontCss)}function ui(e){if(document.getElementById("__prefab-host-fonts"))return;let n=document.createElement("style");n.id="__prefab-host-fonts",n.textContent=e,document.head.appendChild(n)}function Ke(){if(typeof window>"u")return!1;try{return window.self!==window.top}catch{return!0}}function fi(){if(typeof window>"u")return;let e=window;if(typeof e.acquireVsCodeApi==="function")try{let t=e.acquireVsCodeApi();if(t!==null&&typeof t==="object"&&"postMessage"in t)return t}catch{return}return}var Tn=["Accordion","AccordionItem","Alert","AlertDescription","AlertTitle","AreaChart","Audio","Badge","BarChart","BlockQuote","Button","ButtonGroup","Calendar","Card","CardContent","CardDescription","CardFooter","CardHeader","CardTitle","Carousel","Checkbox","ChoiceCard","Code","Column","Combobox","ComboboxGroup","ComboboxLabel","ComboboxOption","ComboboxSeparator","Condition","Container","Dashboard","DashboardItem","DataTable","DatePicker","Define","Detail","Dialog","Div","Dot","DropZone","Elif","Else","Embed","ExpandableRow","Field","FieldContent","FieldDescription","FieldError","FieldTitle","ForEach","Form","Grid","GridItem","H1","H2","H3","H4","Heading","Histogram","HoverCard","Icon","If","Image","Input","Kbd","Label","Large","Lead","LineChart","Link","Loader","Markdown","MasterDetail","Mermaid","Metric","Muted","P","Page","Pages","PdfViewer","PieChart","Popover","Progress","RadarChart","RadialChart","Radio","RadioGroup","Ring","Row","ScatterChart","Select","SelectGroup","SelectLabel","SelectOption","SelectSeparator","Separator","Slider","Slot","Small","Span","Sparkline","Svg","Switch","Tab","Table","TableBody","TableCaption","TableCell","TableFooter","TableHead","TableHeader","TableRow","Tabs","Text","Textarea","Tooltip","Use","Video"];var Ln=new Set(Tn);function Et(e,t={}){let n=[],r=t.strict??!1;if(e==null||typeof e!=="object")return n.push({path:"$",message:"Wire data must be a non-null object"}),{valid:!1,errors:n};let o=e;if(o.$prefab==null||typeof o.$prefab!=="object")n.push({path:"$.$prefab",message:"Missing or invalid $prefab header"});else if(typeof o.$prefab.version!=="string")n.push({path:"$.$prefab.version",message:"version must be a string"});if(o.view==null)n.push({path:"$.view",message:'Missing required "view" field'});else St(o.view,"$.view",n,r);if(o.state!==void 0){if(o.state===null||typeof o.state!=="object"||Array.isArray(o.state))n.push({path:"$.state",message:"state must be a plain object"})}if(o.theme!==void 0)gi(o.theme,n);if(o.css!==void 0)Mn(o.css,"$.css",n);if(o.stylesheets!==void 0)Mn(o.stylesheets,"$.stylesheets",n);if(o.mode!==void 0&&o.mode!=="light"&&o.mode!=="dark")n.push({path:"$.mode",message:'mode must be "light" or "dark"'});if(o.defs!==void 0)if(o.defs===null||typeof o.defs!=="object"||Array.isArray(o.defs))n.push({path:"$.defs",message:"defs must be a plain object"});else for(let[i,s]of Object.entries(o.defs))St(s,`$.defs.${i}`,n,r);if(o.keyBindings!==void 0)if(o.keyBindings===null||typeof o.keyBindings!=="object"||Array.isArray(o.keyBindings))n.push({path:"$.keyBindings",message:"keyBindings must be a plain object"});else for(let[i,s]of Object.entries(o.keyBindings))At(s,`$.keyBindings.${i}`,n);return{valid:n.length===0,errors:n}}function St(e,t,n,r){if(e==null||typeof e!=="object"||Array.isArray(e)){n.push({path:t,message:"Component must be a plain object"});return}let o=e;if(typeof o.type!=="string"||o.type.length===0){n.push({path:`${t}.type`,message:'Component must have a non-empty "type" string'});return}if(r&&!Ln.has(o.type))n.push({path:`${t}.type`,message:`Unknown component type: "${o.type}"`});if(o.children!==void 0)if(!Array.isArray(o.children))n.push({path:`${t}.children`,message:"children must be an array"});else for(let s=0;s<o.children.length;s++)St(o.children[s],`${t}.children[${s}]`,n,r);let i=["onClick","on_click","onChange","on_change","onSubmit","on_submit","onMount","on_mount","onClose","on_close"];for(let s of i)if(o[s]!==void 0)At(o[s],`${t}.${s}`,n);for(let[s,a]of Object.entries(o)){if(s==="type"||mi.has(s)||i.includes(s))continue;if(Nn(a)||Array.isArray(a)&&a.some(Nn))n.push({path:`${t}.${s}`,message:`Components under "${s}" are ignored by the renderer; move them into "children"`})}}var mi=new Set(["children","fallback","trigger","empty","else","summary"]);function Nn(e){if(e==null||typeof e!=="object"||Array.isArray(e))return!1;let t=e.type;return typeof t==="string"&&Ln.has(t)}function At(e,t,n){if(Array.isArray(e)){for(let a=0;a<e.length;a++)At(e[a],`${t}[${a}]`,n);return}if(e==null||typeof e!=="object"){n.push({path:t,message:"Action must be an object or array of objects"});return}let r=e,o=typeof r.type==="string"&&r.type.length>0,i=typeof r.action==="string"&&r.action.length>0;if(!o&&!i){n.push({path:`${t}.type`,message:'Action must have a non-empty "type" or "action" string'});return}if((i?r.action:r.type).toLowerCase()==="showtoast"){if(typeof r.message!=="string"||r.message.length===0)n.push({path:`${t}.message`,message:'showToast requires a non-empty "message" string'})}}function Mn(e,t,n){if(!Array.isArray(e)){n.push({path:t,message:`${t} must be an array of strings`});return}for(let r=0;r<e.length;r++)if(typeof e[r]!=="string")n.push({path:`${t}[${r}]`,message:"must be a string"})}function gi(e,t){if(e===null||typeof e!=="object"||Array.isArray(e)){t.push({path:"$.theme",message:"theme must be a plain object"});return}let n=e;for(let r of["light","dark"])if(n[r]!==void 0){if(n[r]===null||typeof n[r]!=="object"||Array.isArray(n[r]))t.push({path:`$.theme.${r}`,message:`theme.${r} must be a plain object`})}}var Z={mount(e,t,n){if(We(),n?.validate!==!1)for(let b of Et(t).errors)O.warn(`wire validation ${b.path}: ${b.message}`);let r=t,o={tracked:[],evalBlocked:!1};if(r.pipes)for(let[b,w]of Object.entries(r.pipes))Hn(b,w,o);let i=new ye(r.state),s;if(n?.transport&&"callTool"in n.transport)s=n.transport;else if(n?.transport)s=_e(n.transport);else s=Ve();let a=n?.onToast??yi,l=new ot;function c(b){let w=b;if(r=w,w.state)i.merge(w.state);if(w.defs)u.defs=w.defs;if(w.theme)vt(e,w.theme);if(w.mode)Pn(e,w.mode);if(w.pipes)for(let[S,N]of Object.entries(w.pipes))Hn(S,N,o);for(let S of d)S.remove();if(d.length=0,d.push(...$n(w.css,w.stylesheets)),On(e,w.layout),g?.(),g=void 0,w.keyBindings)g=wt(w.keyBindings,(S)=>{F(j(S,{store:i,transport:s,scope:{},rerender:()=>f(),remount:c,onToast:a}),"keyBinding")});f()}let u={store:i,scope:{},transport:s,rerender:()=>f(),remount:c,onToast:a,defs:r.defs,destroyRegistry:l};if(vt(e,r.theme),r.mode)Pn(e,r.mode);On(e,r.layout);let d=$n(r.css,r.stylesheets),g;if(r.keyBindings)g=wt(r.keyBindings,(b)=>{F(j(b,{store:i,transport:s,scope:{},rerender:()=>f(),remount:c,onToast:a}),"keyBinding")});let h,y=n?.themeToggle??!0;if(y!==!1)h=xt(e,typeof y==="object"?y:void 0);function f(){l.flush();let b=e.querySelector(".pf-theme-toggle");e.innerHTML="";let w=J(r.view,u);if(e.appendChild(w),b)e.appendChild(b)}return f(),{rerender:()=>f(),update(b){if(i.merge(b.update.state),f(),b.update.actions!=null)F(j(b.update.actions,u),"update action")},store:i,destroy(){l.flush(),h?.(),g?.(),Ft(),Bt();for(let b of d)b.remove();for(let b of o.tracked)Xe(b);e.innerHTML=""}}},isPrefabData(e){return e!=null&&typeof e==="object"&&"$prefab"in e},isPrefabUpdate(e){return e!=null&&typeof e==="object"&&"$prefab"in e&&"update"in e}},hi=new Set(["find","dot","length","upper","lower","truncate","join","first","last","abs","round","number","currency","percent","compact","date","time","datetime","pluralize","default","selectattr","rejectattr"]);function bi(e){if(e instanceof EvalError)return!0;return e instanceof Error&&/unsafe-eval|Content Security Policy|call to Function/i.test(e.message)}function Hn(e,t,n){if(hi.has(e)){O.warn(`wire pipe "${e}" ignored — shadows built-in`);return}if(ke(e)!=null){O.debug(`wire pipe "${e}" — already registered, keeping local implementation`);return}if(n.evalBlocked)return;try{let r=Function("return ("+t+")")();if(typeof r!=="function"){O.warn(`wire pipe "${e}" — source did not evaluate to a function`);return}Ue(e,r),n.tracked.push(e)}catch(r){if(bi(r)){n.evalBlocked=!0,O.warn("wire pipes cannot be hydrated — this host's CSP forbids eval. Pre-register them with "+"prefab.registerPipe() from a companion script (rendererHtml({ scripts })) and they are used as-is.");return}O.warn(`wire pipe "${e}" — failed to hydrate:`,r)}}function yi(e){if(typeof document>"u")return;let t=vi(),n=document.createElement("div"),r=e.variant??"default";n.className=`pf-toast${r!=="default"?` pf-toast--${r}`:""}`,n.setAttribute("data-variant",r),n.style.marginBottom="8px",n.style.transition="opacity 0.3s ease";let o=document.createElement("div");if(o.textContent=e.message,o.style.fontWeight="500",n.appendChild(o),e.description){let s=document.createElement("div");s.textContent=e.description,s.style.fontSize="14px",s.style.color="var(--muted-foreground, #6b7280)",n.appendChild(s)}t.appendChild(n);let i=e.duration??4000;setTimeout(()=>{n.style.opacity="0",setTimeout(()=>n.remove(),300)},i)}function Pn(e,t){if(be(e,t),typeof document<"u")be(document.documentElement,t)}function Ci(e){let t=e.trim();if(t.includes("{")||t.includes("}"))return!1;return/^(https?:)?\/\//i.test(t)||t.startsWith("/")||/\.css(\?|#|$)/i.test(t)}function $n(e,t){let n=[];if(typeof document>"u")return n;for(let r of e??[]){let o=document.createElement("style");o.textContent=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}for(let r of t??[])if(Ci(r)){let o=document.createElement("link");o.rel="stylesheet",o.href=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}else{let o=document.createElement("style");o.textContent=r,o.dataset.prefab="injected",document.head.appendChild(o),n.push(o)}return n}function On(e,t){if(e.style.height="",e.style.minHeight="",e.style.maxHeight="",e.style.overflow="",!t)return;if(t.preferredHeight!=null)e.style.height=`${t.preferredHeight}px`;if(t.minHeight!=null)e.style.minHeight=`${t.minHeight}px`;if(t.maxHeight!=null)e.style.maxHeight=`${t.maxHeight}px`,e.style.overflow="auto"}function vi(){let t=document.getElementById("prefab-toast-container");if(!t)t=document.createElement("div"),t.id="prefab-toast-container",t.style.position="fixed",t.style.bottom="16px",t.style.right="16px",t.style.zIndex="9999",t.style.maxWidth="400px",document.body.appendChild(t);return t}if(typeof window<"u"){let e=window;e.PrefabRenderer=Z,e.prefab={app:Ge,mount:Z.mount.bind(Z),isPrefabData:Z.isPrefabData.bind(Z),isPrefabUpdate:Z.isPrefabUpdate.bind(Z),Bridge:xe,isIframe:Ke,registerPipe:Ue,unregisterPipe:Xe,listPipes:$t,registerComponent:p,createThemeToggle:xt,validateWireFormat:Et,setLogLevel:Ht};let t=e.__PREFAB_DATA__;if(t!=null){let n=document.getElementById("prefab-root");if(n)Z.mount(n,t)}}async function Ge(e){We();let t=e?.mode??"auto",n=t==="bridge"||t==="auto"&&Ke(),r,o,i={capabilities:{}};if(n)o=new xe(e?.hostOrigin),o.connect(),i=await o.initialize(e?.capabilities??{toolInput:!0}),r=o.createTransport();else if(e?.transport)r=_e(e.transport);else r=Ve();if(i.theme&&typeof document<"u")kt(document.documentElement,i.theme);if(typeof document<"u"&&!o)xi();let s,a,l,c,u,d=i.toolInput,g;if(o)o.on("prefab:tool-input",(f)=>{let b=f.args??f;if(s)s(b);else d=b}),o.on("prefab:tool-result",(f)=>{let b=f.result??f;if(a)a(b);else g=b}),o.on("prefab:tool-cancelled",()=>{l?.()}),o.on("prefab:tool-input-partial",(f)=>{c?.(f.args??f)}),o.on("prefab:theme-update",(f)=>{if(typeof document<"u")kt(document.documentElement,f)}),o.on("prefab:host-context-changed",(f)=>{u?.(f)});function h(f,...b){let w=Rt(f),S=new ye,N={store:S,scope:{},transport:r,rerender:()=>k(),onToast:void 0};function k(){w.innerHTML="";for(let R of b)w.appendChild(J(R,N))}return k(),{rerender:k,store:S,destroy:()=>{w.innerHTML=""}}}return{callTool:(f,b={})=>r.callTool(f,b),sendMessage:(f)=>r.sendMessage(f),onToolInput:(f)=>{if(s=f,d){let b=d;d=void 0,queueMicrotask(()=>f(b))}},onToolResult:(f)=>{if(a=f,g!==void 0){let b=g;g=void 0,queueMicrotask(()=>f(b))}},onToolCancelled:(f)=>{l=f},onToolInputPartial:(f)=>{c=f},onHostContextChanged:(f)=>{u=f},render:h,mount:(f,b,w)=>{let S=Rt(f);return Z.mount(S,b,{transport:r,...w})},requestMode:(f)=>o?.requestMode(f),openLink:(f,b)=>{if(o)o.openLink(f,b);else if(typeof window<"u")window.open(f,b??"_blank")},updateContext:(f)=>{if(o)o.updateContext(f)},setupAutoResize:(f)=>{if(!o)return wi;let b=typeof f==="string"?Rt(f):f;return o.setupAutoResize(b)},notifyPreferredSize:(f)=>{if(o)o.notifyPreferredSize(f)},host:i,capabilities:i.capabilities,theme:i.theme,transport:r,destroy:()=>o?.disconnect()}}var wi=()=>{};function Rt(e){if(typeof e==="string"){if(typeof document>"u")throw Error("Cannot resolve selector outside browser");let t=document.querySelector(e);if(!t)throw Error(`Element not found: ${e}`);return t}return e}function xi(){function e(){let n=document.body.getAttribute("data-vscode-theme-kind");if(!n)return;let r=n.includes("light")?"light":"dark";document.documentElement.setAttribute("data-theme",r)}e(),new MutationObserver(e).observe(document.body,{attributes:!0,attributeFilter:["data-vscode-theme-kind"]})}var Nt=qe("auto"),Dn="#root";function Tt(e){return Z.isPrefabData(e)}function jn(e){return Z.isPrefabUpdate(e)}function In(e){if(Tt(e))return e;if(e!==null&&typeof e==="object"){let t=e;if(Tt(t.structuredContent))return t.structuredContent;if(Array.isArray(t.content))for(let n of t.content){let r=n;if(r.type==="text"&&typeof r.text==="string")try{let o=JSON.parse(r.text);if(Tt(o))return o}catch{}}}return null}async function Fn(){let e=document.querySelector(Dn);if(!e){Nt.error(`Mount target "${Dn}" not found`);return}let t=e,n=await Ge();n.setupAutoResize(t);let r;function o(i){if(r)r.destroy();if(r=n.mount(t,i),i.layout)n.notifyPreferredSize(i.layout)}n.onToolResult((i)=>{let s=In(i);if(s)o(s);else if(jn(i)&&r)r.update(i)}),n.onToolInput((i)=>{let s=In(i);if(s)o(s);else if(jn(i)&&r)r.update(i)})}function ki(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{Fn().catch((e)=>{Nt.error("Boot failed:",e)})},{once:!0});else queueMicrotask(()=>{Fn().catch((e)=>{Nt.error("Boot failed:",e)})})}ki();})();
|