@chatpanel/events 0.429.0 โ†’ 0.432.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ const v="1.0",p="https://chatpanel.net/a2ui/chap/v1/catalog.json",f="https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",e=(r,i)=>({name:r,kind:"string",...i}),n=(r,i,l)=>({name:r,kind:"enum",values:i,...l}),m=["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"],d=["start","center","end","stretch"],h=Object.freeze({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:"โš ",sunny:"โ˜€",cloudy:"โ˜",rain:"๐ŸŒง",snow:"โ„",storm:"โ›ˆ",wind:"๐Ÿ’จ",trendingUp:"โ†—",trendingDown:"โ†˜",time:"๐Ÿ•’",link:"๐Ÿ”—",place:"๐Ÿ“",money:"๐Ÿ’ฐ",chart:"๐Ÿ“Š"}),c=Object.freeze({catalogId:p,version:"1.0",components:Object.freeze({Text:{about:"a line or paragraph of text",props:[e("text",{required:!0}),n("variant",["h1","h2","h3","body","caption"])]},Image:{about:"an https image",props:[{name:"url",kind:"url",required:!0},e("description"),n("fit",["contain","cover","fill","none","scaleDown"]),n("variant",["icon","avatar","smallFeature","mediumFeature","largeFeature","header"])]},Icon:{about:"a small glyph",props:[{name:"name",kind:"icon",required:!0}]},Row:{about:"children side by side",props:[{name:"children",kind:"children",required:!0},n("justify",m),n("align",d)]},Column:{about:"children stacked",props:[{name:"children",kind:"children",required:!0},n("justify",m),n("align",d)]},List:{about:"a list, often from _template",props:[{name:"children",kind:"children",required:!0},n("direction",["vertical","horizontal"]),n("align",d)]},Card:{about:"a bordered box around one child",props:[{name:"child",kind:"child",required:!0}]},Tabs:{about:"tabbed panes",props:[{name:"tabs",kind:"tabs",required:!0}]},Divider:{about:"a rule",props:[n("axis",["horizontal","vertical"])]},Button:{about:"a button that sends an Event or runs openUrl",props:[{name:"child",kind:"child",required:!0},n("variant",["default","primary","borderless"]),{name:"action",kind:"action",required:!0}]},TextField:{about:"a text input bound to a path",props:[e("label",{required:!0}),e("value",{required:!0,bindable:!0}),e("placeholder"),n("variant",["longText","number","shortText","obscured"])]},CheckBox:{about:"a checkbox bound to a path",props:[e("label",{required:!0}),{name:"value",kind:"boolean",required:!0,bindable:!0}]},ChoicePicker:{about:"choose one or many",props:[e("label"),n("variant",["multipleSelection","mutuallyExclusive"]),{name:"options",kind:"options",required:!0},{name:"value",kind:"list",required:!0,bindable:!0},n("displayStyle",["checkbox","chips"])]},Slider:{about:"a number slider bound to a path",props:[e("label"),{name:"min",kind:"number"},{name:"max",kind:"number",required:!0},{name:"value",kind:"number",required:!0,bindable:!0},{name:"steps",kind:"number"}]},DateTimeInput:{about:"a date/time input bound to a path",props:[e("value",{required:!0,bindable:!0}),{name:"enableDate",kind:"boolean"},{name:"enableTime",kind:"boolean"},e("label")]},Table:{about:"columns + rows (rows: arrays or objects keyed by column)",props:[{name:"columns",kind:"list",required:!0},{name:"rows",kind:"rows",required:!0},e("caption")]},Stat:{about:"a big number with a label",props:[e("label",{required:!0}),e("value",{required:!0}),e("delta"),n("trend",["up","down","flat"])]},Badge:{about:"a short coloured tag",props:[e("text",{required:!0}),n("tone",["neutral","good","warn","bad","info"])]},Link:{about:"a link the person opens",props:[e("text",{required:!0}),{name:"url",kind:"url",required:!0}]},Chart:{about:"a small bar or line chart",props:[n("kind",["bar","line"],{required:!0}),{name:"labels",kind:"list",required:!0},{name:"values",kind:"list",required:!0},e("title"),e("unit")]}}),functions:Object.freeze({formatString:{args:[e("value",{required:!0})],returns:"string"},formatNumber:{args:[{name:"value",kind:"number",required:!0},{name:"decimals",kind:"number"},{name:"grouping",kind:"boolean"}],returns:"string"},formatCurrency:{args:[{name:"value",kind:"number",required:!0},e("currency",{required:!0}),{name:"decimals",kind:"number"},{name:"grouping",kind:"boolean"}],returns:"string"},formatDate:{args:[e("value",{required:!0}),e("format",{required:!0})],returns:"string"},pluralize:{args:[{name:"value",kind:"number",required:!0},e("zero"),e("one"),e("two"),e("few"),e("many"),e("other",{required:!0})],returns:"string"},openUrl:{args:[{name:"url",kind:"url",required:!0}],returns:"void",user:!0}})}),g=new Map([[p,c],[f,c]]);function q(r){return g.get(String(r||""))||null}function k(r,i){const l=i.props||i.args||[];return`${r}(${l.map(u=>u.name+(u.required?"":"?")).join(", ")})`}const y=Object.freeze(["Card","Column","Row","List","Text","Icon","Stat","Badge","Table","Chart","Link","Button","ChoicePicker"]);function $(r=c,{components:i=y}={}){const l=i.filter(a=>r.components[a]),u=l.map(a=>k(a,r.components[a])),s=[];for(const a of l)for(const t of r.components[a].props)t.kind==="enum"&&["variant","tone","trend","kind"].includes(t.name)&&s.push(`${a}.${t.name} ${t.values.join("|")}`);return["For a card, table, chart or choice, add ONE ```a2ui block (A2UI Express) after a short sentence. Plain questions get plain text.",`Components: ${u.join(" ")}`,`Enums: ${s.join("; ")}. Icons: sunny cloudy rain snow check warning info star place time money link.`,'One statement per line; root = โ€ฆ is the top; args positional or name=value, _ skips; $/x = value sets data, $/x reads it; _template($/list, Comp) repeats per item, $field reads the item; action: Event("name", {k: $/x}) or openUrl("https://โ€ฆ"); ChoicePicker options are strings.','Example:\n```a2ui\n$/days = [{d: "Mon", t: "18ยฐ"}, {d: "Tue", t: "21ยฐ"}]\nroot = Card(Column([Text("Paris", "h2"), Stat("Now", "19ยฐC", "+2ยฐ", "up"), List(_template($/days, Row([Text($d), Text($t, "caption")])))]))\n```'].join(`
2
+ `)}const o="common_types.json#/$defs/";function b(r){switch(r.kind){case"string":case"url":return{$ref:`${o}DynamicString`};case"number":return{$ref:`${o}DynamicNumber`};case"boolean":return{$ref:`${o}DynamicBoolean`};case"enum":return{type:"string",enum:[...r.values]};case"icon":return{type:"string",enum:Object.keys(h)};case"child":return{$ref:`${o}Child`};case"children":return{$ref:`${o}ChildList`};case"action":return{$ref:`${o}Action`};case"list":return{$ref:`${o}DynamicStringList`};case"rows":return{$ref:`${o}DynamicValue`};case"tabs":return{type:"array",items:{type:"object",properties:{title:{$ref:`${o}DynamicString`},child:{$ref:`${o}Child`}},required:["title","child"]}};case"options":return{type:"array",items:{type:"object",properties:{label:{$ref:`${o}DynamicString`},value:{type:"string"}},required:["label","value"]}};default:return{}}}function x(r=c){const i={};for(const[u,s]of Object.entries(r.components)){const a={component:{const:u}};for(const t of s.props)a[t.name]=b(t);i[u]={type:"object",description:s.about,allOf:[{$ref:`${o}ComponentCommon`},{properties:a,required:["component",...s.props.filter(t=>t.required).map(t=>t.name)]}],unevaluatedProperties:!1}}const l={};for(const[u,s]of Object.entries(r.functions)){const a={};for(const t of s.args)a[t.name]=b(t);l[u]={type:"object",returnType:s.returns,...s.user?{requiresUserActivation:!0}:{},properties:{"@call":{const:u},args:{type:"object",properties:a,required:s.args.filter(t=>t.required).map(t=>t.name)}},required:["@call","args"]}}return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:r.catalogId,catalogId:r.catalogId,protocolVersion:r.version,title:"Chap",description:"The components a Chap reply may contain.",components:i,functions:l}}export{v as A2UI_VERSION,f as BASIC_CATALOG_ID,c as CHAP_CATALOG,p as CHAP_CATALOG_ID,h as ICONS,y as PROMPT_COMPONENTS,q as catalogFor,$ as describeExpress,k as signatureOf,x as toCatalogJson};
package/a2ui-chart.js ADDED
@@ -0,0 +1 @@
1
+ const v=320,H=160,e={l:34,r:8,t:22,b:26},S=24;function h(s){return String(s??"").replace(/[&<>"']/g,r=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[r])}function g(s){const r=Math.abs(s);return r>=1e9?(s/1e9).toFixed(1).replace(/\.0$/,"")+"B":r>=1e6?(s/1e6).toFixed(1).replace(/\.0$/,"")+"M":r>=1e4?(s/1e3).toFixed(1).replace(/\.0$/,"")+"k":Number.isInteger(s)?String(s):s.toFixed(1)}function N({kind:s="bar",labels:r=[],values:F=[],title:u="",unit:d=""}={}){const c=F.slice(0,S).map(t=>Number.isFinite(Number(t))?Number(t):0),y=c.map((t,i)=>String(r[i]??"").slice(0,10)),f=c.length,o=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 160" width="320" height="160" font-family="system-ui,sans-serif" font-size="10">'];if(u&&o.push(`<text x="${e.l}" y="13" font-size="11" font-weight="600" fill="#7a8494">${h(String(u).slice(0,60))}</text>`),!f)return o.push("</svg>"),o.join("");const $=Math.max(0,...c),a=Math.min(0,...c),b=$-a||1,w=320-e.l-e.r,m=160-e.t-e.b,n=t=>e.t+m-(t-a)/b*m;o.push(`<line x1="${e.l}" x2="${320-e.r}" y1="${n(0).toFixed(1)}" y2="${n(0).toFixed(1)}" stroke="#8a93a3" stroke-opacity=".5"/>`),o.push(`<text x="${e.l-4}" y="${(n($)+3).toFixed(1)}" text-anchor="end" fill="#8a93a3">${h(g($)+d)}</text>`),a<0&&o.push(`<text x="${e.l-4}" y="${(n(a)+3).toFixed(1)}" text-anchor="end" fill="#8a93a3">${h(g(a)+d)}</text>`);const l=w/f,M=Math.ceil(f/8);if(y.forEach((t,i)=>{i%M||o.push(`<text x="${(e.l+l*(i+.5)).toFixed(1)}" y="152" text-anchor="middle" fill="#8a93a3">${h(t)}</text>`)}),s==="line"){const t=c.map((i,x)=>`${(e.l+l*(x+.5)).toFixed(1)},${n(i).toFixed(1)}`);o.push(`<polyline points="${t.join(" ")}" fill="none" stroke="#4f7fd6" stroke-width="2" stroke-linejoin="round"/>`);for(const i of t){const[x,p]=i.split(",");o.push(`<circle cx="${x}" cy="${p}" r="2.5" fill="#4f7fd6"/>`)}}else{const t=Math.max(2,l*.62);c.forEach((i,x)=>{const p=n(Math.max(i,0)),k=Math.max(1,Math.abs(n(i)-n(0)));o.push(`<rect x="${(e.l+l*x+(l-t)/2).toFixed(1)}" y="${p.toFixed(1)}" width="${t.toFixed(1)}" height="${k.toFixed(1)}" rx="2" fill="${i<0?"#d4694f":"#4f7fd6"}"/>`)})}return o.push("</svg>"),o.join("")}export{N as chartSvg};
@@ -0,0 +1,5 @@
1
+ import{A2UI_VERSION as D,CHAP_CATALOG as H}from"./a2ui-catalog.js";const U=64*1024,F=400,L=/[\p{ID_Start}_]/u,V=/[\p{ID_Continue}]/u,X=/[^\s,()[\]{}=:"]/u;function G(a){const f=[];let t=0,r=1;const w=(s,v,i)=>f.push({t:s,v,line:r,...i});for(;t<a.length;){const s=a[t];if(s===`
2
+ `){w("nl"),r++,t++;continue}if(s===" "||s===" "||s==="\r"){t++;continue}if(s==="#"||s==="/"&&a[t+1]==="/"){for(;t<a.length&&a[t]!==`
3
+ `;)t++;continue}if("()[]{},:=".includes(s)){w(s),t++;continue}if(s==='"'||(s==="r"||s==="R")&&a[t+1]==='"'){const i=s!=='"';i&&t++;const x=a.startsWith('"""',t)?'"""':'"';t+=x.length;let o="",u=!1;for(;t<a.length;){if(a.startsWith(x,t)){t+=x.length,u=!0;break}const g=a[t];if(g===`
4
+ `&&r++,g==="\\"&&!i){const k=a[t+1];o+=k==="n"?`
5
+ `:k==="t"?" ":k==='"'?'"':k==="\\"?"\\":k==="$"?"\\$":"\\"+(k??""),t+=2;continue}o+=g,t++}if(!u)return{toks:f,error:{line:r,message:"unterminated string"}};w("str",o);continue}const v=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(a.slice(t,t+40));if(v&&(/[\d.]/.test(s)||(s==="-"||s==="+")&&/[\d.]/.test(a[t+1]||""))){const i=Number(v[0]);if(!Number.isFinite(i))return{toks:f,error:{line:r,message:`number out of range: ${v[0]}`}};w("num",i),t+=v[0].length;continue}if(s==="$"){let i=t+1;for(;i<a.length&&X.test(a[i]);)i++;w("path",a.slice(t+1,i)),t=i;continue}if(s==="?"||s==="@"){let i=t+1;for(;i<a.length&&V.test(a[i]);)i++;if(i===t+1)return{toks:f,error:{line:r,message:`stray "${s}"`}};w(s==="?"?"check":"sys",a.slice(t,i)),t=i;continue}if(L.test(s)){let i=t+1;for(;i<a.length&&V.test(a[i]);)i++;w("id",a.slice(t,i)),t=i;continue}return{toks:f,error:{line:r,message:`unexpected character "${s}"`}}}return w("eof"),{toks:f}}class C extends Error{constructor(f,t){super(f),this.line=t}}function K(a){let f=0;const t=(o=0)=>a[f+o],r=()=>a[f++],w=o=>{const u=r();if(u.t!==o)throw new C(`expected "${o}" but found ${u.t==="eof"?"the end":`"${u.v??u.t}"`}`,u.line);return u},s=()=>{for(;t().t==="nl";)f++};function v(o,u){const g=[];for(s();t().t!==o;){if(g.push(u()),s(),t().t===","){r(),s();continue}if(t().t!==o)throw new C(`expected "," or "${o}"`,t().line)}return r(),g}function i(){const o=t();switch(o.t){case"str":return r(),{t:"lit",v:o.v};case"num":return r(),{t:"lit",v:o.v};case"path":return r(),{t:"path",p:o.v};case"[":return r(),{t:"arr",items:v("]",i)};case"{":return r(),{t:"map",entries:v("}",()=>{const u=r();if(u.t!=="id"&&u.t!=="str")throw new C("expected a key",u.line);return w(":"),s(),[u.v,i()]})};case"check":{r();const u=t().t==="("?(r(),v(")",i)):[];return{t:"check",name:o.v.slice(1),args:u}}case"sys":case"id":{if(r(),o.t==="id"&&t().t!=="(")return o.v==="true"||o.v==="false"?{t:"lit",v:o.v==="true"}:o.v==="null"?{t:"lit",v:null}:o.v==="_"?{t:"skip"}:{t:"var",name:o.v};w("(");const u=v(")",()=>{if(t().t==="id"&&(t(1).t==="="||t(1).t===":")){const g=r().v;return r(),s(),{name:g,value:i()}}return{value:i()}});return{t:"call",name:o.v,args:u}}default:throw new C(`unexpected ${o.t==="eof"?"end":`"${o.v??o.t}"`}`,o.line)}}const b=[],x=[];for(;t().t!=="eof";){if(t().t==="nl"){f++;continue}const o=f,u=t().line;try{let g=null;if((t().t==="id"||t().t==="path")&&t(1).t==="="){const d=r();r(),s(),g=d.t==="path"?{path:d.v}:{name:d.v}}const k=i();if(t().t!=="nl"&&t().t!=="eof")throw new C("expected the end of the statement",t().line);b.push({target:g,value:k,line:u})}catch(g){if(!(g instanceof C))throw g;for(x.push({line:g.line??u,message:g.message}),f=o+1;t().t!=="eof"&&!(a[f-1].t==="nl"&&(t().t==="id"||t().t==="path")&&t(1).t==="=");)f++}if(b.length>F){x.push({line:u,message:"too many statements"});break}}return{statements:b,errors:x}}class l extends Error{}class j extends l{}const z=new Set(["id"]);function B(a,f,t){const r=f.split("/").slice(1).map(v=>v.replace(/~1/g,"/").replace(/~0/g,"~"));if(!r.length||r.length===1&&r[0]===""){if(!t||typeof t!="object"||Array.isArray(t))throw new l("only a map can replace the whole data model");for(const v of Object.keys(a))delete a[v];Object.assign(a,t);return}let w=a;for(let v=0;v<r.length-1;v++){const i=r[v];(w[i]==null||typeof w[i]!="object")&&(w[i]=/^(?:0|[1-9]\d{0,3}|10000)$/.test(r[v+1])?[]:{}),w=w[i]}const s=r[r.length-1];if(Array.isArray(w)&&/^\d+$/.test(s))for(;w.length<Number(s);)w.push(null);t===null?Array.isArray(w)?w[s]=null:delete w[s]:w[s]=t}function Z(a,{catalog:f=H,surfaceId:t="main",partial:r=!1}={}){const w=String(a??"").slice(0,U),s=[],v=G(w);let i=v.toks;if(v.error){r||s.push(v.error);let d=i.length;for(;d>0&&i[d-1].t!=="nl";)d--;i=i.slice(0,d),i.push({t:"eof",line:v.error.line})}const b=K(i),x=b.statements.length?b.statements[b.statements.length-1].line:0;for(const d of b.errors)r&&d.line>=x||s.push(d);const o=[];let u={surfaceId:t,update:!1,sendDataModel:!1,statements:[]};const g=()=>{(u.statements.length||u.explicit)&&o.push(u)},k=[];for(const d of b.statements){const E=d.value;if(!d.target&&E.t==="call"&&(E.name==="surface"||E.name==="deleteSurface")){const O=E.args.find(S=>!S.name)?.value;if(!O||O.t!=="lit"||typeof O.v!="string"){s.push({line:d.line,message:`${E.name}() needs a surface id string`});continue}if(E.name==="deleteSurface"){g(),u={surfaceId:t,update:!1,sendDataModel:!1,statements:[]},k.push({version:D,deleteSurface:{surfaceId:O.v}});continue}g();const I=Object.fromEntries(E.args.filter(S=>S.name).map(S=>[S.name,S.value]));u={surfaceId:O.v,update:I.update?.v===!0,sendDataModel:I.sendDataModel?.v===!0,statements:[],explicit:!0};continue}u.statements.push(d)}g();for(const d of o)J(d,f,k,s,r);return{messages:k,errors:s}}function J(a,f,t,r,w){const s=new Map,v=[],i=[];for(const e of a.statements){if(e.target?.path!=null){v.push(e);continue}if(e.target?.name){const n=e.target.name;if(["true","false","null","_"].includes(n)){r.push({line:e.line,message:`"${n}" cannot be a variable name`});continue}s.set(n,e);continue}if(e.value.t==="call"&&Object.prototype.hasOwnProperty.call(f.components,e.value.name)){i.push(e);continue}r.push({line:e.line,message:"a statement must assign: name = Component(...) or $/path = value"})}if(i.length&&!s.has("root")&&!a.update){const e=i.length===1?i[0].value:{t:"call",name:"Column",args:[{value:{t:"arr",items:i.map(n=>n.value)}}]};s.set("root",{target:{name:"root"},value:e,line:i[0].line})}else if(i.length)for(const e of i)r.push({line:e.line,message:"a statement must assign: name = Component(...)"});const b=[],x=new Set,o=new Set,u=new Set,g=e=>Object.prototype.hasOwnProperty.call(f.components,e),k=e=>Object.prototype.hasOwnProperty.call(f.functions,e);function d(e,n,h){if(e.t==="call"&&g(e.name))return O(e,n,h);if(e.t==="var"){const p=s.get(e.name);if(!p){if(a.update||!s.has("root")||w)return e.name;throw new l(`"${e.name}" is not defined`)}if(o.has(e.name))throw new j;if(p.value.t!=="call"||!g(p.value.name))throw new l(`"${e.name}" is not a component`);return E(e.name)}if(e.t==="lit"&&typeof e.v=="string")return a.update||!s.has("root")?e.v:O({t:"call",name:"Text",args:[{value:e}]},n,h);throw new l("expected a component here")}function E(e){const n=s.get(e),h=n.value.args.find(c=>c.name==="id")?.value,p=h?.t==="lit"&&typeof h.v=="string"?h.v:e;if(x.has(e))return p;if(u.has(e))throw new l(`"${e}" contains itself`);u.add(e);try{O(n.value,p,n.line),x.add(e)}catch(c){throw!(c instanceof l)||c instanceof j?c:(o.add(e),r.push({line:n.line,message:`${e}: ${c.message}`}),new j)}finally{u.delete(e)}return p}function O(e,n,h){const p=f.components[e.name];if(!p)throw new l(`unknown component ${e.name}`);const c=e.args.find(m=>m.name==="id")?.value;c?.t==="lit"&&typeof c.v=="string"&&(n=c.v);const y={id:n,component:e.name};let $=0;for(const m of e.args){let _;if(m.name){if(z.has(m.name))continue;if(_=p.props.find(A=>A.name===m.name),!_)throw new l(`${e.name} has no "${m.name}" โ€” ${T(e.name,p)}`)}else if(_=p.props[$++],!_)throw new l(`too many arguments to ${T(e.name,p)}`);if(m.value.t!=="skip")try{y[_.name]=I(_,m.value,`${n}_${_.name}`,h)}catch(A){if(_.required||A instanceof j||!(A instanceof l))throw A;r.push({line:h,message:`${n}: ${A.message} (left out)`})}}for(const m of p.props)if(m.required&&!(m.name in y))throw new l(`${e.name} needs "${m.name}" โ€” ${T(e.name,p)}`);return b.push(y),n}function I(e,n,h,p){switch(e.kind){case"child":return d(n,h,p);case"children":{if(n.t==="call"&&n.name==="_template"){const[y,$]=n.args.map(m=>m.value);if(!y||y.t!=="path"||!$)throw new l("_template($/list, Component) needs a path and a component");return{componentId:d($,`${h}_item`,p),path:y.p}}if(n.t!=="arr")throw new l(`"${e.name}" takes a list [ โ€ฆ ] or _template(โ€ฆ)`);const c=[];return n.items.forEach((y,$)=>{try{c.push(d(y,`${h}_${$}`,p))}catch(m){if(m instanceof j)return;if(!(m instanceof l))throw m;r.push({line:p,message:`${h}_${$}: ${m.message}`})}}),c}case"action":return S(n);case"enum":{if(n.t!=="lit"||!e.values.includes(n.v))throw new l(`"${e.name}" is one of ${e.values.join(", ")}`);return n.v}case"tabs":{if(n.t!=="arr")throw new l('tabs takes [{title: "โ€ฆ", child: Component}]');return n.items.map((c,y)=>{if(c.t!=="map")throw new l('each tab is {title: "โ€ฆ", child: Component}');const $=new Map(c.entries);if(!$.has("title")||!$.has("child"))throw new l("each tab needs title and child");return{title:M($.get("title")),child:d($.get("child"),`${h}_${y}`,p)}})}case"options":{if(n.t!=="arr")throw new l('options takes [{label: "โ€ฆ", value: "โ€ฆ"}]');return n.items.map(c=>{if(c.t==="lit"&&typeof c.v=="string")return{label:c.v,value:c.v};if(c.t!=="map")throw new l("each option is {label, value}");const y=new Map(c.entries),$=y.get("value");return{label:M(y.get("label")??$),value:$?.t==="lit"?String($.v):""}})}default:return M(n)}}function S(e){if(e.t==="var"){const n=s.get(e.name);if(!n)throw new l(`"${e.name}" is not defined`);return S(n.value)}if(e.t==="lit"&&typeof e.v=="string"&&/^[\w-]{1,64}$/.test(e.v))return{event:{name:e.v,context:{}}};if(e.t!=="call")throw new l('an action is Event("name", {โ€ฆ}) or openUrl("https://โ€ฆ")');if(e.name==="Event"){const n=e.args.filter(m=>!m.name).map(m=>m.value),h=Object.fromEntries(e.args.filter(m=>m.name).map(m=>[m.name,m.value]));for(const m of Object.keys(h))if(m!=="context"&&m!=="userMessage")throw new l(`Event has no "${m}"`);const p=n[0];if(!p||p.t!=="lit"||typeof p.v!="string"||!p.v)throw new l("Event needs a name string");const c=h.context??n[1],y={};if(c){if(c.t!=="map")throw new l("the Event context is a map {key: value}");for(const[m,_]of c.entries)y[m]=M(_)}const $={name:p.v,context:y};return h.userMessage&&($.userMessage=M(h.userMessage)),{event:$}}if(k(e.name))return{functionCall:R(e)};throw new l(`unknown action ${e.name}`)}function R(e){const n=f.functions[e.name];if(!n)throw new l(`unknown function ${e.name}`);const h={};let p=0;for(const c of e.args){const y=c.name?n.args.find($=>$.name===c.name):n.args[p++];if(!y)throw new l(`bad argument to ${T(e.name,n)}`);c.value.t!=="skip"&&(h[y.name]=M(c.value))}for(const c of n.args)if(c.required&&!(c.name in h))throw new l(`${e.name} needs "${c.name}"`);return{"@call":e.name,args:h}}function M(e){switch(e.t){case"lit":return e.v;case"path":return{"@path":e.p};case"arr":return e.items.map(M);case"map":return Object.fromEntries(e.entries.map(([n,h])=>[n,M(h)]));case"var":{const n=s.get(e.name);if(!n)throw new l(`"${e.name}" is not defined`);if(n.value.t==="call"&&g(n.value.name))throw new l(`"${e.name}" is a component, not a value`);return M(n.value)}case"call":if(e.name==="@index"){const n=e.args[0]?.value;return{"@call":"@index",args:n?.t==="lit"?{offset:n.v}:{}}}if(k(e.name))return R(e);throw g(e.name)?new l(`${e.name} is a component; it goes in a child slot`):new l(`unknown function ${e.name}`);default:throw new l("expected a value")}}const N={},q=[];for(const e of v)try{const n=P(e.value);a.update||!s.has("root")?q.push({path:e.target.path||"/",value:n}):B(N,e.target.path,n)}catch(n){if(!(n instanceof l))throw n;r.push({line:e.line,message:n.message})}const W=s.has("root")?["root",...[...s.keys()].filter(e=>e!=="root")]:[...s.keys()];for(const e of W){const n=s.get(e);if(n.value.t==="call"&&!g(n.value.name)&&!k(n.value.name)&&!["Event","_template"].includes(n.value.name)&&!n.value.name.startsWith("@")){r.push({line:n.line,message:`${e}: unknown component ${n.value.name} โ€” the components are ${Object.keys(f.components).join(", ")}`});continue}if(!(n.value.t!=="call"||!g(n.value.name))&&!o.has(e))try{E(e)}catch(h){if(h instanceof j)continue;if(!(h instanceof l))throw h;r.push({line:n.line,message:`${e}: ${h.message}`})}}if(s.has("root")&&!a.update){const e={surfaceId:a.surfaceId,catalogId:f.catalogId};a.sendDataModel&&(e.sendDataModel=!0),e.components=b,Object.keys(N).length&&(e.dataModel=N),t.push({version:D,createSurface:e})}else{b.length&&t.push({version:D,updateComponents:{surfaceId:a.surfaceId,components:b}});for(const e of q)t.push({version:D,updateDataModel:{surfaceId:a.surfaceId,path:e.path,value:e.value}})}}function P(a){switch(a.t){case"lit":return a.v;case"arr":return a.items.map(P);case"map":return Object.fromEntries(a.entries.map(([f,t])=>[f,P(t)]));default:throw new l("data values are literals: strings, numbers, lists and maps")}}function T(a,f){const t=f.props||f.args||[];return`${a}(${t.map(r=>r.name+(r.required?"":"?")).join(", ")})`}export{Z as compileExpress};
package/a2ui-html.js ADDED
@@ -0,0 +1 @@
1
+ import{chartSvg as p}from"./a2ui-chart.js";function e(t){return String(t??"").replace(/[&<>"']/g,s=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[s])}const r=(...t)=>t.filter(Boolean).join(" "),n=(t,s)=>s==null||s===""?"":` ${t}="${e(s)}"`;function o(t,s){return t.children.map(a=>$(a,s)).join("")}function $(t,s=!1){const a=b(t,s);return t.weight&&!s&&a?`<div class="a2ui-weight-${t.weight}">${a}</div>`:a}function b(t,s){const a=t.props;switch(t.type){case"Text":{const i=a.variant||"body",l=s?"span":i==="h1"?"h3":i==="h2"?"h4":i==="h3"?"h5":"p";return`<${l} class="${r("a2ui-text",`a2ui-text-${i}`)}">${e(a.text)}</${l}>`}case"Image":return a.url?`<img class="${r("a2ui-image",a.variant&&`a2ui-image-${a.variant}`,a.fit&&`a2ui-fit-${a.fit}`)}" src="${e(a.url)}" alt="${e(a.description||"")}" loading="lazy" referrerpolicy="no-referrer">`:"";case"Icon":return`<span class="a2ui-icon" aria-hidden="true">${e(a.glyph)}</span>`;case"Row":case"Column":case"List":{if(s)return`<span class="a2ui-inline">${o(t,!0)}</span>`;const i=t.type==="List"?a.direction==="horizontal"?"row":"column":t.type.toLowerCase();return`<${t.type==="List"?'div role="list"':"div"} class="${r("a2ui-stack",`a2ui-${i}`,a.justify&&`a2ui-justify-${a.justify}`,a.align&&`a2ui-align-${a.align}`)}">${o(t)}</div>`}case"Card":return`<div class="a2ui-card">${o(t)}</div>`;case"Divider":return`<hr class="${r("a2ui-divider",a.axis==="vertical"&&"a2ui-divider-v")}">`;case"Tabs":{const i=t.tabs||[],l=i.map((d,u)=>`<button type="button" class="${r("a2ui-tab",u===0&&"is-active")}" data-a2ui-tab="${u}">${e(d.title)}</button>`).join(""),c=i.map((d,u)=>`<div class="a2ui-tabpane" data-a2ui-pane="${u}"${u?" hidden":""}>${$(d.node)}</div>`).join("");return`<div class="a2ui-tabs"><div class="a2ui-tabbar" role="tablist">${l}</div>${c}</div>`}case"Button":return`<button type="button" class="${r("a2ui-btn",`a2ui-btn-${a.variant||"default"}`)}" data-a2ui-key="${e(t.key)}"${t.hasAction?"":" disabled"}>${o(t,!0)}</button>`;case"TextField":{const i=a.variant==="number"?"number":a.variant==="obscured"?"password":"text",l=a.variant==="longText"?`<textarea class="a2ui-input"${n("data-a2ui-bind",t.bind)}${n("placeholder",a.placeholder)} rows="3">${e(a.value)}</textarea>`:`<input class="a2ui-input" type="${i}"${n("data-a2ui-bind",t.bind)}${n("placeholder",a.placeholder)} value="${e(a.value)}" data-a2ui-type="${i==="number"?"number":"string"}">`;return`<label class="a2ui-field"><span class="a2ui-label">${e(a.label)}</span>${l}</label>`}case"CheckBox":return`<label class="a2ui-check"><input type="checkbox"${n("data-a2ui-bind",t.bind)} data-a2ui-type="boolean"${a.value?" checked":""}> <span>${e(a.label)}</span></label>`;case"ChoicePicker":{const i=a.variant!=="mutuallyExclusive",l=new Set(a.value||[]),c=`a2ui-${e(t.key)}`,d=(a.options||[]).map(u=>`<label class="a2ui-choice"><input type="${i?"checkbox":"radio"}" name="${c}" value="${e(u.value)}"${n("data-a2ui-bind",t.bind)} data-a2ui-type="list"${l.has(u.value)?" checked":""}> <span>${e(u.label)}</span></label>`).join("");return`<fieldset class="${r("a2ui-choices",a.displayStyle==="chips"&&"a2ui-chips")}">${a.label?`<legend class="a2ui-label">${e(a.label)}</legend>`:""}${d}</fieldset>`}case"Slider":return`<label class="a2ui-field"><span class="a2ui-label">${e(a.label)}</span><input class="a2ui-slider" type="range"${n("min",a.min??0)}${n("max",a.max)}${n("step",a.steps?(a.max-(a.min??0))/a.steps:"any")} value="${e(a.value??0)}"${n("data-a2ui-bind",t.bind)} data-a2ui-type="number"></label>`;case"DateTimeInput":{const i=a.enableTime&&a.enableDate!==!1?"datetime-local":a.enableTime?"time":"date";return`<label class="a2ui-field"><span class="a2ui-label">${e(a.label)}</span><input class="a2ui-input" type="${i}" value="${e(a.value)}"${n("data-a2ui-bind",t.bind)} data-a2ui-type="string"></label>`}case"Table":{const i=(a.columns||[]).map(c=>`<th>${e(c)}</th>`).join(""),l=(a.rows||[]).map(c=>`<tr>${c.map(d=>`<td>${e(d)}</td>`).join("")}</tr>`).join("");return`<div class="a2ui-table-wrap"><table class="a2ui-table">${a.caption?`<caption>${e(a.caption)}</caption>`:""}<thead><tr>${i}</tr></thead><tbody>${l}</tbody></table></div>`}case"Stat":return`<div class="a2ui-stat"><span class="a2ui-stat-label">${e(a.label)}</span><span class="a2ui-stat-value">${e(a.value)}</span>${a.delta?`<span class="${r("a2ui-stat-delta",a.trend&&`a2ui-trend-${a.trend}`)}">${e(a.delta)}</span>`:""}</div>`;case"Badge":return`<span class="${r("a2ui-badge",`a2ui-tone-${a.tone||"neutral"}`)}">${e(a.text)}</span>`;case"Link":return a.url?`<a class="md-link a2ui-link" data-href="${e(a.url)}" role="link" tabindex="0">${e(a.text)}</a>`:`<span class="a2ui-link">${e(a.text)}</span>`;case"Chart":return`<img class="a2ui-chart" alt="${e(a.title||"chart")}" src="data:image/svg+xml;utf8,${encodeURIComponent(p(a))}">`;case"Missing":case"Truncated":return"";default:return""}}function h(t){return t?.root?`<div class="a2ui-surface" data-a2ui-surface="${e(t.surfaceId)}">${$(t.root)}</div>`:""}export{h as renderA2uiHtml};
package/a2ui-reply.js ADDED
@@ -0,0 +1,11 @@
1
+ import{compileExpress as x}from"./a2ui-express.js";import{createSurfaceSet as d}from"./a2ui-surface.js";import{renderA2uiText as y}from"./a2ui-text.js";import{CHAP_CATALOG as h}from"./a2ui-catalog.js";const A=Object.freeze(["a2ui","a2ui-json"]);function _(r){return A.includes(String(r||"").toLowerCase())}function v(r){const e=String(r??"");return e.includes("<a2ui")?e.replace(/<a2ui-json>\s*([\s\S]*?)\s*<\/a2ui-json>/g,(s,t)=>`
2
+ \`\`\`a2ui-json
3
+ ${t}
4
+ \`\`\`
5
+ `).replace(/<a2ui>\s*([\s\S]*?)\s*<\/a2ui>/g,(s,t)=>`
6
+ \`\`\`a2ui
7
+ ${t}
8
+ \`\`\`
9
+ `):e}function j(r){try{const e=JSON.parse(String(r||"").trim());return{messages:Array.isArray(e)?e:[e],errors:[]}}catch(e){return{messages:[],errors:[{line:0,message:`not JSON: ${String(e.message||e).slice(0,120)}`}]}}}function J(r,{lang:e="a2ui",surfaceId:s="main",urlPolicy:t,now:g,partial:p=!1,catalog:S=h}={}){const a=String(e).toLowerCase()==="a2ui-json"?j(r):x(r,{catalog:S,surfaceId:s,partial:p}),o=d({urlPolicy:t,now:g}),u=[...a.errors];let l=null;for(const c of a.messages)u.push(...o.apply(c)),c?.createSurface?.surfaceId&&(l=c.createSurface.surfaceId);const f=l||s,n=o.has(f)?o.resolve(f):null,i=!!n&&n.root.type!=="Missing";return{surfaces:o,tree:i?n:null,text:i?y(n):"",messages:a.messages,errors:u,ok:i,trivial:i&&m(n.root)}}function m(r){return r.type==="Text"?!0:(r.type==="Card"||r.type==="Column")&&r.children.length===1?m(r.children[0]):!1}function N(r){const e=r?.action;if(!e)return"";const s=e.userMessage||String(e.name||"").replace(/[_-]+/g," ").trim(),t=e.context&&Object.keys(e.context).length?` ${JSON.stringify(e.context).slice(0,2e3)}`:"";return`${s}
10
+
11
+ (chose "${e.name}" in the card${t})`}export{A as A2UI_FENCES,J as a2uiBlock,N as actionTurnText,v as fencesFromTags,_ as isA2uiFence};
@@ -0,0 +1 @@
1
+ import{A2UI_VERSION as U,catalogFor as q,ICONS as V}from"./a2ui-catalog.js";const $=Object.freeze({components:400,depth:24,nodes:1500,templateRows:200,dataBytes:256*1024,text:4e3,surfaces:32}),_=/^[\p{ID_Start}_][\p{ID_Continue}]{0,63}$/u,K=new Set(["@accessibility","@catalogId","@metadata","@checks"]);function Z(e,{image:n=!1}={}){const t=String(e||"").trim();return n&&/^data:image\/(png|jpe?g|gif|webp|avif)[;,]/i.test(t)||/^https:\/\/[^\s"'<>]+$/i.test(t)?t:""}function O(e,n){return e===null||["string","number","boolean"].includes(typeof e)?!0:Array.isArray(e)?e.every(t=>O(t,n)):typeof e!="object"?!1:"@path"in e?typeof e["@path"]=="string"&&Object.keys(e).length===1:"@call"in e?z(e,n):Object.entries(e).every(([t,r])=>!t.startsWith("@")&&O(r,n))}function z(e,n,{action:t=!1}={}){const r=e["@call"];if(r==="@index")return!0;const p=n.functions[r];return!p||p.user&&!t||e.args!=null&&(typeof e.args!="object"||Array.isArray(e.args))?!1:Object.entries(e.args||{}).every(([h,c])=>p.args.some(f=>f.name===h)&&O(c,n))}function Q(e,n,t){switch(e.kind){case"enum":return typeof n=="string"&&e.values.includes(n);case"icon":return typeof n=="string"&&n in V||n&&typeof n=="object"&&"@path"in n;case"child":return typeof n=="string"&&_.test(n);case"children":return Array.isArray(n)?n.length<=$.components&&n.every(r=>typeof r=="string"&&_.test(r)):!!n&&typeof n=="object"&&typeof n.componentId=="string"&&_.test(n.componentId)&&typeof n.path=="string";case"action":{if(!n||typeof n!="object")return!1;if(n.event){const r=n.event;return typeof r.name=="string"&&r.name.length<=64&&(r.context==null||typeof r.context=="object"&&O(r.context,t))&&(r.userMessage==null||O(r.userMessage,t))}return n.functionCall?z(n.functionCall,t,{action:!0}):!1}case"tabs":return Array.isArray(n)&&n.length<=12&&n.every(r=>r&&O(r.title,t)&&typeof r.child=="string"&&_.test(r.child));case"options":return Array.isArray(n)&&n.length<=50&&n.every(r=>r&&O(r.label,t)&&typeof r.value=="string");default:return O(n,t)}}function X(e,n,t=""){const r=[],p=(f,b,M="VALIDATION_FAILED")=>r.push({code:M,surfaceId:t,path:f,message:b});if(!e||typeof e!="object"||Array.isArray(e))return p("","a component is an object"),{component:null,errors:r};if(typeof e.id!="string"||!_.test(e.id))return p("/id",`bad component id ${JSON.stringify(e.id)}`),{component:null,errors:r};const h=n.components[e.component];if(!h)return p(`/${e.id}`,`unknown component ${JSON.stringify(e.component)}`),{component:null,errors:r};const c={id:e.id,component:e.component};for(const[f,b]of Object.entries(e)){if(f==="id"||f==="component")continue;if(f==="weight"){typeof b=="number"&&b>=0&&b<=12?c.weight=Math.round(b):p(`/${e.id}/weight`,"weight is a number from 0 to 12");continue}if(f.startsWith("@")){if(f.startsWith("@@"))continue;if(!K.has(f)){p(`/${e.id}/${f}`,`unknown directive ${f}`);continue}f==="@accessibility"&&b&&typeof b=="object"&&(c[f]={label:typeof b.label=="string"?b.label.slice(0,200):void 0});continue}const M=h.props.find(w=>w.name===f);if(!M){p(`/${e.id}/${f}`,`${e.component} has no "${f}"`);continue}if(b!==null){if(!Q(M,b,n)){p(`/${e.id}/${f}`,`bad value for ${e.component}.${f}`);continue}c[f]=b}}for(const f of h.props)if(f.required&&!(f.name in c))return p(`/${e.id}/${f.name}`,`${e.component} needs "${f.name}"`),{component:null,errors:r};return{component:c,errors:r}}function x(e){return String(e).split("/").slice(1).map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~"))}function R(e,n){if(n===""||n==="/")return e;let t=e;for(const r of x(n)){if(t==null||typeof t!="object"||!Object.prototype.hasOwnProperty.call(t,r))return;t=t[r]}return t}function v(e,n,t){const r=x(n);if(!r.length||r.length===1&&r[0]==="")return t;const p=e&&typeof e=="object"?e:{};let h=p;for(let f=0;f<r.length-1;f++){const b=r[f];if(b==="__proto__"||b==="constructor"||b==="prototype")return p;(h[b]==null||typeof h[b]!="object")&&(h[b]=/^\d+$/.test(r[f+1])?[]:{}),h=h[b]}const c=r[r.length-1];return c==="__proto__"||c==="constructor"||c==="prototype"||(t===null?Array.isArray(h)?h[c]=null:delete h[c]:h[c]=t),p}function E(e,n){const t=String(e||"");return t.startsWith("/")?t:`${n||""}/${t}`.replace(/\/+/g,"/")}const H=typeof Intl<"u"&&typeof Intl.NumberFormat=="function";function L(e){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:NaN}function J(e,n){const[t,r]=Math.abs(e).toFixed(n).split(".");return(e<0?"-":"")+t.replace(/\B(?=(\d{3})+(?!\d))/g,",")+(r?"."+r:"")}function ee(e,n,t=!0){const r=L(e);if(Number.isNaN(r))return"";const p=Number.isFinite(n)?Math.max(0,Math.min(10,n)):Number.isInteger(r)?0:2;if(H)try{return new Intl.NumberFormat(void 0,{minimumFractionDigits:p,maximumFractionDigits:p,useGrouping:t!==!1}).format(r)}catch{}return t===!1?r.toFixed(p):J(r,p)}function te(e,n,t,r=!0){const p=L(e);if(Number.isNaN(p))return"";const h=/^[A-Za-z]{3}$/.test(String(n||""))?String(n).toUpperCase():"USD",c=Number.isFinite(t)?Math.max(0,Math.min(4,t)):2;if(H)try{return new Intl.NumberFormat(void 0,{style:"currency",currency:h,minimumFractionDigits:c,maximumFractionDigits:c,useGrouping:r!==!1}).format(p)}catch{}const f={USD:"$",EUR:"โ‚ฌ",GBP:"ยฃ",JPY:"ยฅ",INR:"โ‚น"}[h];return f?`${p<0?"-":""}${f}${J(Math.abs(p),c)}`:`${h} ${J(p,c)}`}const W=["January","February","March","April","May","June","July","August","September","October","November","December"],Y=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function ne(e,n){const t=new Date(typeof e=="number"?e:String(e??""));if(Number.isNaN(t.getTime()))return String(e??"");const r=c=>String(c).padStart(2,"0"),p=t.getHours()%12||12,h={yyyy:t.getFullYear(),yy:r(t.getFullYear()%100),MMMM:W[t.getMonth()],MMM:W[t.getMonth()].slice(0,3),MM:r(t.getMonth()+1),M:t.getMonth()+1,dd:r(t.getDate()),d:t.getDate(),EEEE:Y[t.getDay()],E:Y[t.getDay()].slice(0,3),HH:r(t.getHours()),H:t.getHours(),hh:r(p),h:p,mm:r(t.getMinutes()),ss:r(t.getSeconds()),a:t.getHours()<12?"AM":"PM"};return String(n||"yyyy-MM-dd").slice(0,64).replace(/'([^']*)'|yyyy|yy|MMMM|MMM|MM|M|dd|d|EEEE|E{1,3}|HH|H|hh|h|mm|ss|a/g,(c,f)=>f??String(h[c]??h[c[0]]??c))}function re(e){const n=L(e.value);let t=n===1?"one":"other";if(H&&typeof Intl.PluralRules=="function")try{t=new Intl.PluralRules().select(n)}catch{}return n===0&&e.zero!=null?String(e.zero):String(e[t]??e.other??"")}function ie({urlPolicy:e=Z,now:n=()=>""}={}){const t=new Map;function r(o){const s=[],a=(S,I,k,C="")=>(s.push({code:S,surfaceId:I,path:C,message:k}),s);if(!o||typeof o!="object"||Array.isArray(o))return a("VALIDATION_FAILED","","a message is an object");if(String(o.version||"").replace(/^v/,"")!==U)return a("VALIDATION_FAILED","",`unsupported A2UI version ${JSON.stringify(o.version)}`);const d=Object.keys(o).filter(S=>S!=="version");if(d.length!==1)return a("VALIDATION_FAILED","","a message has exactly one body");const A=d[0],l=o[A]||{},i=l.surfaceId;if(typeof i!="string"||!i||i.length>64)return a("VALIDATION_FAILED","","surfaceId is required");if(A==="createSurface"){if(t.has(i))return a("INTEGRITY_ERROR",i,`surface ${i} already exists`);if(t.size>=$.surfaces)return a("VALIDATION_FAILED",i,"too many surfaces");const S=q(l.catalogId);if(!S)return a("VALIDATION_FAILED",i,`unknown catalog ${JSON.stringify(l.catalogId)}`);const I={id:i,catalog:S,catalogId:l.catalogId,components:new Map,data:{}};return t.set(i,I),l.dataModel!=null&&s.push(...h(I,"/",l.dataModel)),l.components!=null&&s.push(...p(I,l.components)),s}const D=t.get(i);return A==="deleteSurface"?(t.delete(i),s):D?A==="updateComponents"?p(D,l.components):A==="updateDataModel"?"value"in l?h(D,l.path??"/",l.value):a("VALIDATION_FAILED",i,"updateDataModel needs a value"):a("INVALID_FUNCTION_CALL",i,`${A} is not accepted from a model`):a("VALIDATION_FAILED",i,`no surface ${i}`)}function p(o,s){const a=[];if(!Array.isArray(s))return[{code:"VALIDATION_FAILED",surfaceId:o.id,path:"/components",message:"components is a list"}];for(const m of s){if(o.components.size>=$.components&&!o.components.has(m?.id)){a.push({code:"VALIDATION_FAILED",surfaceId:o.id,path:"/components",message:`more than ${$.components} components`});break}const{component:d,errors:A}=X(m,o.catalog,o.id);a.push(...A),d&&o.components.set(d.id,d)}return a}function h(o,s,a){let m=0;try{m=JSON.stringify(a??null).length}catch{m=1/0}if(m>$.dataBytes)return[{code:"VALIDATION_FAILED",surfaceId:o.id,path:s,message:"data model too large"}];const d=a==null?null:JSON.parse(JSON.stringify(a));if(s==="/"||s===""){if(!d||typeof d!="object"||Array.isArray(d))return[{code:"VALIDATION_FAILED",surfaceId:o.id,path:s,message:"the whole data model must be a map"}];o.data=d}else o.data=v(o.data,s,d);return[]}function c(o,s,a,m){return s==null||typeof s!="object"?s:Array.isArray(s)?s.map(d=>c(o,d,a,m)):"@path"in s?R(o.data,E(s["@path"],a)):"@call"in s?f(o,s,a,m):Object.fromEntries(Object.entries(s).map(([d,A])=>[d,c(o,A,a,m)]))}function f(o,s,a,m){const d=s["@call"],A=o.catalog.functions[d];if(d==="@index")return m==null?"":m+L(s.args?.offset||0);if(!A||A.user)return"";const l={};for(const[i,D]of Object.entries(s.args||{}))l[i]=c(o,D,a,m);switch(d){case"formatString":return b(o,String(l.value??""),a);case"formatNumber":return ee(l.value,l.decimals,l.grouping);case"formatCurrency":return te(l.value,l.currency,l.decimals,l.grouping);case"formatDate":return ne(l.value,l.format);case"pluralize":return re(l);default:return""}}function b(o,s,a){return s.replace(/\\\$\{|\$\{([^}]{1,200})\}/g,(m,d)=>{if(d==null)return"${";const A=d.trim();return/^[\w/~.-]+$/.test(A)?M(R(o.data,E(A,a))):""})}function M(o){if(o==null)return"";if(typeof o=="string")return o.slice(0,$.text);if(typeof o=="number"||typeof o=="boolean")return String(o);try{return JSON.stringify(o).slice(0,$.text)}catch{return""}}function w(o){const s=t.get(o);if(!s)return null;let a=0;const m=new Map;function d(l,i,D,S,I){if(++a>$.nodes)return{key:`k${a}`,id:l,type:"Truncated",props:{},children:[]};const k=s.components.get(l);if(!k)return{key:`k${a}`,id:l,type:"Missing",props:{},children:[]};if(D>$.depth||S.has(l))return{key:`k${a}`,id:l,type:"Truncated",props:{},children:[]};const C=s.catalog.components[k.component],y={key:`k${a}`,id:l,type:k.component,props:{},children:[]};k.weight&&(y.weight=k.weight),m.set(y.key,{id:l,scope:i,index:I});const F=new Set(S).add(l);for(const N of C.props){const u=k[N.name];if(u!==void 0)switch(N.kind){case"child":y.children.push(d(u,i,D+1,F,I));break;case"children":if(Array.isArray(u))for(const g of u)y.children.push(d(g,i,D+1,F,I));else{const g=E(u.path,i),j=R(s.data,g);(Array.isArray(j)?j.slice(0,$.templateRows):[]).forEach((oe,P)=>y.children.push(d(u.componentId,`${g}/${P}`,D+1,F,P)))}break;case"tabs":y.tabs=u.map(g=>({title:M(c(s,g.title,i,I)),node:d(g.child,i,D+1,F,I)}));break;case"options":y.props.options=u.map(g=>({label:M(c(s,g.label,i,I)),value:g.value}));break;case"action":y.hasAction=!0,y.action=u.event?"event":u.functionCall?.["@call"]||"";break;case"url":y.props[N.name]=e(M(c(s,u,i,I)),{image:k.component==="Image"})||"";break;case"icon":{const g=M(c(s,u,i,I));y.props.icon=V[g]?g:"info",y.props.glyph=V[y.props.icon];break}case"list":{const g=c(s,u,i,I),j=Array.isArray(g)?g:g==null||g===""?[]:[g];y.props[N.name]=j.slice(0,$.templateRows).map(T=>typeof T=="number"?T:M(T)),N.bindable&&u&&typeof u=="object"&&"@path"in u&&(y.bind=E(u["@path"],i));break}case"rows":{const g=c(s,u,i,I);y.props.rows=Array.isArray(g)?g.slice(0,$.templateRows):[];break}case"number":{const g=L(c(s,u,i,I));y.props[N.name]=Number.isNaN(g)?void 0:g,N.bindable&&u&&typeof u=="object"&&"@path"in u&&(y.bind=E(u["@path"],i));break}case"boolean":{y.props[N.name]=c(s,u,i,I)===!0||c(s,u,i,I)==="true",N.bindable&&u&&typeof u=="object"&&"@path"in u&&(y.bind=E(u["@path"],i));break}case"enum":y.props[N.name]=u;break;default:y.props[N.name]=M(c(s,u,i,I)),N.bindable&&u&&typeof u=="object"&&"@path"in u&&(y.bind=E(u["@path"],i))}}if(y.type==="Table"){const N=y.props.columns||[];y.props.rows=y.props.rows.map(u=>(Array.isArray(u)?u:N.map(g=>u&&typeof u=="object"?u[g]??u[String(g).toLowerCase()]:"")).map(M))}return y.type==="Chart"&&(y.props.values=(y.props.values||[]).map(L).map(N=>Number.isNaN(N)?0:N)),y}const A=d("root","",0,new Set,void 0);return{surfaceId:o,root:A,keys:m}}function B(o,s){const a=o&&t.get(o.surfaceId),m=o?.keys.get(s);if(!a||!m)return null;const A=a.components.get(m.id)?.action;if(!A)return null;if(A.event){const i=A.event,D={};for(const[I,k]of Object.entries(i.context||{}))D[I]=c(a,k,m.scope,m.index);const S={version:U,action:{name:i.name,surfaceId:a.id,sourceComponentId:m.id,timestamp:n(),context:D}};return i.userMessage!=null&&(S.action.userMessage=M(c(a,i.userMessage,m.scope,m.index))),{kind:"event",message:S}}const l=A.functionCall;if(l?.["@call"]==="openUrl"){const i=e(M(c(a,l.args?.url,m.scope,m.index)),{image:!1});return i?{kind:"openUrl",url:i}:null}return null}function G(o,s,a){const m=t.get(o);return!m||typeof s!="string"||!s.startsWith("/")?!1:h(m,s,a).length===0}return{apply:r,resolve:w,click:B,setValue:G,has:o=>t.has(o),data:o=>t.get(o)?.data}}export{$ as LIMITS,ie as createSurfaceSet,Z as defaultUrlPolicy,te as formatCurrency,ne as formatDate,ee as formatNumber,X as validateComponent};
package/a2ui-text.js ADDED
@@ -0,0 +1,2 @@
1
+ function a(e){return String(e??"").replace(/\s+/g," ").trim()}function i(e){switch(e.type){case"Text":return a(e.props.text);case"Icon":return e.props.glyph||"";case"Badge":return`[${a(e.props.text)}]`;case"Link":return e.props.url?`${a(e.props.text)} (${e.props.url})`:a(e.props.text);case"Stat":return`${a(e.props.label)}: ${a(e.props.value)}${e.props.delta?` (${a(e.props.delta)})`:""}`;case"Button":return`[${e.children.map(i).filter(Boolean).join(" ")}]`;case"Row":return e.children.map(i).filter(Boolean).join(" ยท ");case"Column":return e.children.map(i).filter(Boolean).join(" โ€” ");case"List":return e.children.map(i).filter(Boolean).join(" ยท ");default:return null}}function c(e,s){const t=e.props;switch(e.type){case"Text":{const r=a(t.text);if(!r)return;s.push(t.variant==="h1"||t.variant==="h2"||t.variant==="h3"?`**${r}**`:r);return}case"Row":{const r=i(e);r&&s.push(r);return}case"List":if(t.direction==="horizontal"){const r=i(e);r&&s.push(r);return}for(const r of e.children)c(r,s);return;case"Column":case"Card":for(const r of e.children)c(r,s);return;case"Tabs":for(const r of e.tabs||[])s.push(`**${a(r.title)}**`),c(r.node,s);return;case"Divider":s.push("---");return;case"Image":t.description&&s.push(`[image: ${a(t.description)}]`);return;case"Table":{const r=(t.columns||[]).map(a);if(!r.length)return;t.caption&&s.push(a(t.caption)),s.push(`| ${r.join(" | ")} |`,`| ${r.map(()=>"---").join(" | ")} |`);for(const n of t.rows||[])s.push(`| ${r.map((o,l)=>a(n[l]).replace(/\|/g,"\\|")).join(" | ")} |`);return}case"Chart":{t.title&&s.push(`**${a(t.title)}**`),s.push((t.labels||[]).map((r,n)=>`${a(r)} ${t.values?.[n]??""}${t.unit||""}`).join(" ยท "));return}case"TextField":case"DateTimeInput":s.push(`${a(t.label)}: ${a(t.value)||"____"}`);return;case"CheckBox":s.push(`${t.value?"[x]":"[ ]"} ${a(t.label)}`);return;case"Slider":s.push(`${a(t.label)}: ${t.value??""}`);return;case"ChoicePicker":{const r=new Set(t.value||[]);s.push(`${t.label?a(t.label)+": ":""}${(t.options||[]).map(n=>r.has(n.value)?`(โ€ข) ${a(n.label)}`:`( ) ${a(n.label)}`).join(" ")}`);return}default:{const r=i(e);r&&s.push(r)}}}function p(e){if(!e?.root)return"";const s=[];return c(e.root,s),s.join(`
2
+ `)}export{p as renderA2uiText};
@@ -0,0 +1,12 @@
1
+ import{ICONS as y}from"./a2ui-catalog.js";const w="(Chap shows the person a card with these figures. Answer in one or two sentences with what matters for their question โ€” do not draw a card of it or list every figure again.)",x=8*1024;function l(n){return n==null?"null":typeof n=="number"?Number.isFinite(n)?String(n):"null":typeof n=="boolean"?String(n):Array.isArray(n)?`[${n.map(l).join(", ")}]`:typeof n=="object"?`{${Object.entries(n).map(([t,r])=>`${JSON.stringify(String(t))}: ${l(r)}`).join(", ")}}`:`"${String(n).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\t/g,"\\t")}"`}const C=/^(?:united states(?: of america)?|usa|us|liberia|myanmar|burma)$/i;function m(n){const t=String(n||"").toLowerCase();return/thunder|storm/.test(t)?"storm":/snow|sleet|blizzard|ice/.test(t)?"snow":/rain|drizzle|shower/.test(t)?"rain":/sun|clear/.test(t)?"sunny":/wind/.test(t)?"wind":/cloud|overcast|fog|mist|haze/.test(t)?"cloudy":"info"}function S(n){const t=new Date(`${String(n||"")}T12:00:00`);return Number.isNaN(t.getTime())?String(n||""):["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()]}function F(n,{place:t=""}={}){if(!n?.now)return"";const r=C.test(String(n.area?.country||"").trim()),o=(i,f)=>{const $=r?f:i;return $==null?"":`${Math.round($)}ยฐ`},e=n.now,c=o(e.tempC,e.tempF);if(!c)return"";const a=t||[n.area?.name,n.area?.region&&n.area.region!==n.area?.name?n.area.region:"",n.area?.country].filter(Boolean).join(", ")||n.query||"Weather",s=o(e.feelsLikeC,e.feelsLikeF),u=r?e.windMph!=null?`${e.windMph} mph`:"":e.windKph!=null?`${e.windKph} km/h`:"",h=[e.humidity!=null?`Humidity ${e.humidity}%`:"",u?`Wind ${u}${e.windDir?` ${e.windDir}`:""}`:"",e.uv!=null?`UV ${e.uv}`:""].filter(Boolean).map(i=>({f:i})),g=(n.days||[]).map((i,f)=>({d:f===0?"Today":S(i.date),i:m(i.condition),t:[o(i.maxC,i.maxF),o(i.minC,i.minF)].filter(Boolean).join(" / "),r:i.chanceOfRain!=null?`${i.chanceOfRain}% rain`:""})).filter(i=>i.t),p=m(e.condition);return[`$/w = ${l({place:a,now:`${c}${r?"F":"C"}`,cond:e.condition||"",feels:s?`Feels like ${s}`:""})}`,`$/days = ${l(g)}`,`$/facts = ${l(h)}`,'head = Row([Icon("'+(y[p]?p:"info")+'"), Column([Text($/w/place, "h3"), Text($/w/cond, "caption")])])','reading = Row([Stat("Now", $/w/now, $/w/feels)])','extras = List(_template($/facts, Badge($f)), "horizontal")','forecast = List(_template($/days, Row([Text($d), Icon($i), Text($t), Text($r, "caption")])))',"root = Card(Column([head, reading, extras, forecast]))"].join(`
2
+ `)}function d(n){const t=n&&typeof n=="object"?n.card:null;if(!t||typeof t!="object")return null;const r=t.lang==="a2ui-json"?"a2ui-json":t.lang==="a2ui"||t.lang==null?"a2ui":null,o=typeof t.source=="string"?t.source.trim():"";return!r||!o||o.length>x||o.includes("```")?null:{lang:r,source:o}}function j(n){if(!d(n))return n;const t=typeof n.text=="string"?n.text:"";return{...n,text:`${t}
3
+
4
+ ${w}`}}const N=/(?:^|\n)[ \t]{0,3}```a2ui(?:-json)?[^\n]*\n[\s\S]*?\n[ \t]{0,3}```[ \t]*(?=\n|$)|<a2ui(?:-json)?>[\s\S]*?<\/a2ui(?:-json)?>/g;function T(n,t=[]){const r=(t||[]).filter(Boolean);if(!r.length)return n;const o=(typeof n=="string"?n:"").replace(N,"").replace(/\n{3,}/g,`
5
+
6
+ `),e=[],c=new Set;for(const a of r)c.has(a.source)||(c.add(a.source),e.push(`\`\`\`${a.lang}
7
+ ${a.source}
8
+ \`\`\``));return`${o.replace(/\s+$/,"")}${o.trim()?`
9
+
10
+ `:""}${e.join(`
11
+
12
+ `)}`}function O(n=[]){const t=Array.isArray(n)?n:[];for(let r=t.length-1;r>=0;r--)if(t[r]?.role==="user")return(t[r].attachments||[]).map(o=>o?.kind==="prefetch"?d(o):null).filter(Boolean);return[]}function R(n,{prior:t=[]}={}){const r=[...t];return{tools:n&&typeof n.execute=="function"?{...n,execute:async(e,c,a)=>{const s=await n.execute(e,c,a),u=d(s);return u?(r.push(u),j(s)):s}}:n,list:()=>[...r],apply:e=>T(e,r)}}export{w as CARD_SHOWN_NOTE,T as appendCards,d as cardOf,O as cardsFromAttachments,m as conditionIcon,R as createCardCollector,l as exprLit,F as weatherCard,j as withCardNote};
package/endpoint-jobs.js CHANGED
@@ -1 +1 @@
1
- const b=Object.freeze(["chat","embed","rerank","stt","tts"]),f=e=>{try{return new URL(e).origin}catch{return""}},n=Object.freeze({openai:{embed:{adapter:"openai-embeddings"},stt:{adapter:"openai"},tts:{adapter:"openai"}},groq:{stt:{adapter:"openai"}},"gemini-api-key":{embed:{adapter:"openai-embeddings"}},"cloudflare-workers-ai":{embed:{adapter:"openai-embeddings"},rerank:{adapter:"cloudflare-rerank",url:e=>e.replace(/\/v1$/,"")},stt:{adapter:"cloudflare",url:e=>e.replace(/\/v1$/,"")},models:["@cf/baai/bge-reranker-base","@cf/openai/whisper","@cf/openai/whisper-large-v3-turbo","@cf/baai/bge-base-en-v1.5","@cf/baai/bge-m3"]},mistral:{embed:{adapter:"openai-embeddings"}},together:{embed:{adapter:"openai-embeddings"},rerank:{adapter:"rerank-standard",url:e=>f(e)}},deepinfra:{embed:{adapter:"openai-embeddings"}},fireworks:{embed:{adapter:"openai-embeddings"}},cohere:{embed:{adapter:"openai-embeddings"},rerank:{adapter:"rerank-standard",url:()=>"https://api.cohere.com"}},elevenlabs:{stt:{adapter:"elevenlabs"},tts:{adapter:"elevenlabs"},noChat:!0,models:["scribe_v1","eleven_multilingual_v2","eleven_flash_v2_5","eleven_turbo_v2_5"]},"openai-compatible":{embed:{adapter:"openai-embeddings"},stt:{adapter:"openai"},tts:{adapter:"openai"}}}),m=[[/(^|\.)api\.openai\.com$/,"openai"],[/(^|\.)api\.groq\.com$/,"groq"],[/(^|\.)generativelanguage\.googleapis\.com$/,"gemini-api-key"],[/(^|\.)api\.cloudflare\.com$/,"cloudflare-workers-ai"],[/(^|\.)api\.mistral\.ai$/,"mistral"],[/(^|\.)api\.together\.(ai|xyz)$/,"together"],[/(^|\.)api\.deepinfra\.com$/,"deepinfra"],[/(^|\.)api\.fireworks\.ai$/,"fireworks"],[/(^|\.)api\.cohere\.(ai|com)$/,"cohere"],[/(^|\.)api\.elevenlabs\.io$/,"elevenlabs"]];function s(e){for(const r of[e?.providerPreset,e?.preset])if(r&&n[r])return r;let t="";try{t=new URL(String(e?.baseUrl||"")).hostname}catch{return""}for(const[r,a]of m)if(r.test(t))return a;return(e?.kind||"openai")==="openai"?"openai-compatible":""}function c(e){const t=String(e||"").toLowerCase();return t?/rerank/.test(t)?["rerank"]:/whisper|transcribe|scribe|(^|[/_-])stt([/_-]|$)|parakeet/.test(t)?["stt"]:/(^|[/_-])sts([/_-]|$)|speech-to-speech|voice-changer/.test(t)?["s2s"]:/(^|[/_-])tts([/_-]|$)|^tts-|eleven_|text-to-speech|melotts|kokoro|(^|[/_-])voice/.test(t)?["tts"]:/embed|(^|[/@_-])(bge|e5|gte)[-_]|nomic-embed|mxbai|jina-embeddings/.test(t)?["embed"]:["chat"]:[]}function u(e){const t=n[s(e)]?.models||[],r=[e?.model,...Array.isArray(e?.modelOptions)?e.modelOptions.map(a=>typeof a=="string"?a:a?.id):[],...t];return[...new Set(r.filter(a=>typeof a=="string"&&a))]}function g(e,t){const r=(Array.isArray(e?.modelOptions)?e.modelOptions:[]).find(a=>a&&typeof a=="object"&&a.id===t);return Array.isArray(r?.jobs)?r.jobs:null}function O(e){return!!e&&e.jobsOnly!==!0&&!n[s(e)]?.noChat}function $(e){const t=n[s(e)]||{},r=Object.fromEntries(b.map(a=>[a,[]]));for(const a of u(e))for(const o of g(e,a)||c(a))(o==="chat"?t.noChat||e?.jobsOnly===!0:!t[o])||r[o].push(a);return r}const h=(e,t)=>`ep-${String(e?.id||"x").replace(/[^A-Za-z0-9_.:-]/g,"").slice(0,24)}-${String(t).replace(/[^A-Za-z0-9_.:-]/g,"-").slice(-30)}`.slice(0,64);function S(e,t,r){const a=n[s(e)]?.[t];return!a||!e?.id||!r?null:{provider:"endpoint",endpoint:String(e.id),model:String(r),adapter:a.adapter,id:h(e,r),label:`${e.name||e.id} ยท ${r}`}}const v=e=>!!e&&typeof e=="object"&&e.provider==="endpoint"&&typeof e.endpoint=="string"&&!!e.endpoint;function j(e,t=[]){if(!v(e))return e;const r=Array.isArray(t)?t:[],a=r.find(i=>i?.endpointId===e.endpoint)||r.find(i=>i?.id===e.endpoint)||null;if(!a||typeof a.baseUrl!="string"||!/^https?:\/\//.test(a.baseUrl))return null;const o=n[s({baseUrl:a.baseUrl,kind:a.protocol==="anthropic"?"anthropic":"openai"})]||{},l=Object.entries(o).find(([i,d])=>i!=="models"&&d&&typeof d=="object"&&d.adapter===e.adapter),p=a.baseUrl.replace(/\/+$/,"");return{provider:"remote",url:l?.[1]?.url?l[1].url(p):p,adapter:e.adapter,model:e.model,...a.apiKey?{token:a.apiKey}:{},...e.id?{id:e.id}:{},...e.label?{label:e.label}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},endpoint:e.endpoint}}const y=Object.freeze([{id:"chat",label:"Chat"},{id:"stt",label:"Speech to text"},{id:"tts",label:"Voices"},{id:"embed",label:"Embeddings"},{id:"rerank",label:"Reranking"}]),k=new Set(["ollama","lmstudio","llamacpp","vllm"]);function w(e,t){const r=String(e?.id||"");return t==="chat"?e?.jobsOnly!==!0&&!n[r]?.noChat:r==="custom"?!!n["openai-compatible"][t]:k.has(r)?t==="embed":!!n[r]?.[t]}function x(e=[],t="chat"){return(Array.isArray(e)?e:[]).filter(r=>c(typeof r=="string"?r:r?.id).includes(t))}export{b as ENDPOINT_JOBS,y as MODEL_TYPES,n as VENDOR_JOBS,S as endpointEntry,$ as endpointJobs,v as isEndpointRef,c as modelJobsOf,x as modelsOfType,w as presetServes,j as resolveEndpointRef,O as servesChat,s as vendorOf};
1
+ const f=Object.freeze(["chat","embed","rerank","stt","tts"]),m=e=>{try{return new URL(e).origin}catch{return""}},i=Object.freeze({openai:{embed:{adapter:"openai-embeddings"},stt:{adapter:"openai"},tts:{adapter:"openai"}},groq:{stt:{adapter:"openai"}},"gemini-api-key":{embed:{adapter:"openai-embeddings"}},"cloudflare-workers-ai":{embed:{adapter:"openai-embeddings"},rerank:{adapter:"cloudflare-rerank",url:e=>e.replace(/\/v1$/,"")},stt:{adapter:"cloudflare",url:e=>e.replace(/\/v1$/,"")},models:["@cf/baai/bge-reranker-base","@cf/openai/whisper","@cf/openai/whisper-large-v3-turbo","@cf/baai/bge-base-en-v1.5","@cf/baai/bge-m3"]},mistral:{embed:{adapter:"openai-embeddings"}},together:{embed:{adapter:"openai-embeddings"},rerank:{adapter:"rerank-standard",url:e=>m(e)}},deepinfra:{embed:{adapter:"openai-embeddings"}},fireworks:{embed:{adapter:"openai-embeddings"}},cohere:{embed:{adapter:"openai-embeddings"},rerank:{adapter:"rerank-standard",url:()=>"https://api.cohere.com"}},elevenlabs:{stt:{adapter:"elevenlabs"},tts:{adapter:"elevenlabs"},noChat:!0,models:["scribe_v1","eleven_multilingual_v2","eleven_flash_v2_5","eleven_turbo_v2_5"]},"openai-compatible":{embed:{adapter:"openai-embeddings"},stt:{adapter:"openai"},tts:{adapter:"openai"}}}),u=[[/(^|\.)api\.openai\.com$/,"openai"],[/(^|\.)api\.groq\.com$/,"groq"],[/(^|\.)generativelanguage\.googleapis\.com$/,"gemini-api-key"],[/(^|\.)api\.cloudflare\.com$/,"cloudflare-workers-ai"],[/(^|\.)api\.mistral\.ai$/,"mistral"],[/(^|\.)api\.together\.(ai|xyz)$/,"together"],[/(^|\.)api\.deepinfra\.com$/,"deepinfra"],[/(^|\.)api\.fireworks\.ai$/,"fireworks"],[/(^|\.)api\.cohere\.(ai|com)$/,"cohere"],[/(^|\.)api\.elevenlabs\.io$/,"elevenlabs"]];function n(e){for(const t of[e?.providerPreset,e?.preset])if(t&&i[t])return t;let r="";try{r=new URL(String(e?.baseUrl||"")).hostname}catch{return""}for(const[t,a]of u)if(t.test(r))return a;return(e?.kind||"openai")==="openai"?"openai-compatible":""}function p(e){const r=String(e||"").toLowerCase();return r?/rerank/.test(r)?["rerank"]:/whisper|transcribe|scribe|(^|[/_-])stt([/_-]|$)|parakeet/.test(r)?["stt"]:/(^|[/_-])sts([/_-]|$)|speech-to-speech|voice-changer/.test(r)?["s2s"]:/(^|[/_-])tts([/_-]|$)|^tts-|eleven_|text-to-speech|melotts|kokoro|(^|[/_-])voice/.test(r)?["tts"]:/embed|(^|[/@_-])(bge|e5|gte)[-_]|nomic-embed|mxbai|jina-embeddings/.test(r)?["embed"]:["chat"]:[]}function g(e){const r=i[n(e)]?.models||[],t=[e?.model,...Array.isArray(e?.modelOptions)?e.modelOptions.map(a=>typeof a=="string"?a:a?.id):[],...r];return[...new Set(t.filter(a=>typeof a=="string"&&a))]}function h(e,r){const t=(Array.isArray(e?.modelOptions)?e.modelOptions:[]).find(a=>a&&typeof a=="object"&&a.id===r);return Array.isArray(t?.jobs)?t.jobs:null}function S(e){return!!e&&e.jobsOnly!==!0&&!i[n(e)]?.noChat}function $(e){const r=i[n(e)]||{},t=Object.fromEntries(f.map(a=>[a,[]]));for(const a of g(e))for(const o of h(e,a)||p(a))(o==="chat"?r.noChat||e?.jobsOnly===!0:!r[o])||t[o].push(a);return t}const v=(e,r)=>`ep-${String(e?.id||"x").replace(/[^A-Za-z0-9_.:-]/g,"").slice(0,24)}-${String(r).replace(/[^A-Za-z0-9_.:-]/g,"-").slice(-30)}`.slice(0,64);function x(e,r,t){const a=i[n(e)]?.[r];return!a||!e?.id||!t?null:{provider:"endpoint",endpoint:String(e.id),model:String(t),adapter:a.adapter,id:v(e,t),label:`${e.name||e.id} ยท ${t}`}}const _=e=>!!e&&typeof e=="object"&&e.provider==="endpoint"&&typeof e.endpoint=="string"&&!!e.endpoint;function A(e,r=[]){if(!_(e))return e;const t=Array.isArray(r)?r:[],a=t.find(s=>s?.endpointId===e.endpoint)||t.find(s=>s?.id===e.endpoint)||null;if(!a||typeof a.baseUrl!="string"||!/^https?:\/\//.test(a.baseUrl))return null;const o=i[n({baseUrl:a.baseUrl,kind:a.protocol==="anthropic"?"anthropic":"openai"})]||{},l=Object.entries(o).find(([s,d])=>s!=="models"&&d&&typeof d=="object"&&d.adapter===e.adapter),c=a.baseUrl.replace(/\/+$/,"");return{provider:"remote",url:l?.[1]?.url?l[1].url(c):c,adapter:e.adapter,model:e.model,...a.apiKey?{token:a.apiKey}:{},...e.id?{id:e.id}:{},...e.label?{label:e.label}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},...b(e.voice)?{voice:e.voice}:{},endpoint:e.endpoint}}const j=Object.freeze([{id:"chat",label:"Chat"},{id:"stt",label:"Speech to text"},{id:"tts",label:"Voices"},{id:"embed",label:"Embeddings"},{id:"rerank",label:"Reranking"}]),k=new Set(["ollama","lmstudio","llamacpp","vllm"]);function w(e,r){const t=String(e?.id||"");return r==="chat"?e?.jobsOnly!==!0&&!i[t]?.noChat:t==="custom"?!!i["openai-compatible"][r]:k.has(t)?r==="embed":!!i[t]?.[r]}function E(e=[],r="chat"){return(Array.isArray(e)?e:[]).filter(t=>p(typeof t=="string"?t:t?.id).includes(r))}const O=Object.freeze(["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"]),b=e=>/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""));function z(e){const r=n(e),t=String(e?.baseUrl||"").replace(/\/+$/,"");return r==="elevenlabs"?{url:`${t}/voices`,headers:e?.apiKey?{"xi-api-key":e.apiKey}:{}}:r==="openai"||r==="openai-compatible"?{voices:O.map(a=>({id:a,name:a}))}:null}function C(e){return(Array.isArray(e?.voices)?e.voices:Array.isArray(e)?e:[]).map(t=>({id:String(t?.voice_id||t?.id||""),name:String(t?.name||t?.voice_id||t?.id||""),...t?.category?{note:String(t.category)}:{}})).filter(t=>b(t.id))}export{f as ENDPOINT_JOBS,j as MODEL_TYPES,O as OPENAI_VOICES,i as VENDOR_JOBS,x as endpointEntry,$ as endpointJobs,_ as isEndpointRef,b as isVoiceId,p as modelJobsOf,E as modelsOfType,C as normalizeVoices,w as presetServes,A as resolveEndpointRef,S as servesChat,n as vendorOf,z as voiceListRequest};