buckyos 0.7.159 → 0.7.162

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
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="component.json",t="composition.json",s="aiws-manifest.json",i=".aiws-build.json",n="aiws-template/1";class o extends Error{constructor(e){super(e.filter((e=>"error"===e.severity)).map((e=>`${e.file?`${e.file}: `:""}${e.message}`)).join("; ")||"invalid control source"),this.name="AiwsSourceError",this.diagnostics=e}}const r=new TextEncoder,a=new TextDecoder;function c(e,t){return`${e.replace(/\/+$/,"")}/${t}`}function l(e){return e.replace(/[/\\\u0000-\u001f]/g," ").replace(/^\.+/,"").trim().slice(0,80)||"Workspace"}async function d(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),(e=>e.toString(16).padStart(2,"0"))).join("")}async function f(e){const t=[];for(const[s,i]of e)t.push([s,await d(i)]);return t.sort(((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0)),`sha256:${await d(r.encode(JSON.stringify(t)))}`}function p(e){return JSON.stringify([...e].sort(((e,t)=>e.name.localeCompare(t.name))).map((e=>[e.name,e.obj_id??e.etag??""])))}const u=4194304;function m(e){let t="";for(let s=0;s<e.length;s+=32768)t+=String.fromCharCode(...e.subarray(s,s+32768));return btoa(t)}async function h(e,t,s=[]){let i=e.reduce(((e,t)=>e+t.bytes.length),0);const n=new Map;if(i>u){if(!t)throw new o([{file:"",severity:"error",message:"a control's inline files are limited to 4194304 bytes per build"}]);for(const s of[...e].sort(((e,t)=>t.bytes.length-e.bytes.length))){if(i<=u)break;n.set(s.name,await t(s.name,s.bytes)),i-=s.bytes.length}}const r=[...s];for(const o of e){const e=n.get(o.name);r.push(e?{name:o.name,obj_id:e}:{name:o.name,base64:m(o.bytes)})}return r.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:0))}async function y(e,t,s){var i;const n=[],r=[];for(const a of t)if(null==(i=a.obj_id)?void 0:i.startsWith("cyfile:"))n.push({name:a.name,obj_id:a.obj_id});else{if(!a.node_id)throw new o([{file:a.name,severity:"error",message:"the file service did not name this file"}]);r.push({name:a.name,bytes:new Uint8Array(await(await e.readFile(a.node_id)).arrayBuffer())})}return h(r,s,n)}const g=["manifest_version","ident","kind","title","description","host_api","accepts","allow_no_source","default_size","config_schema","bindings","entry","assets","catalog","agent","deps","events"],b=["type","enum","default","required","title","description","minimum","maximum","minLength","maxLength","properties","items"],v=/^[a-z0-9][a-z0-9._-]{0,63}$/,$=/^did:[a-z0-9]+:[^/#\s]+$/,w=/^[a-z][a-z0-9_]{0,31}$/,_=/^did:[a-z0-9]+:[^/#\s]+#[a-z0-9][a-z0-9._-]{0,63}$/,k="needs manifest_version 2 (raise it in component.json)",j="needs manifest_version 3 (raise it in component.json)",x=["string","number","boolean","object","entity"],S=["text","value","metric","bar","list","badge"],O=["kind","text","label","bind","by","format","limit"],A=["open_source","activate_editor","open_definition"],N=["text","number","select","boolean","color"];function E(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function I(e){return e.length>0&&r.encode(e).length<=255&&!e.includes("\0")&&e.split("/").every((e=>e.length>0&&!e.startsWith(".")))}function z(e){const t=E(e)?e.properties:void 0;return E(t)?t:{}}function J(e,t,s,i){for(const n of e.matchAll(/\{\{([^}]*)\}\}/g)){const e=n[1].trim();e.startsWith("config.")?e.slice(7)in s||i(`${t}: {{${e}}} names no property of config_schema`):i(`${t}: only {{config.<key>}} may be used here`)}}function T(e,t,s){if(e&&"object"==typeof e&&!Array.isArray(e))for(const[i,n]of Object.entries(e))if(b.includes(i)){if("properties"===i&&n&&"object"==typeof n)for(const[e,i]of Object.entries(n))T(i,`${t}/properties/${e}`,s);"items"===i&&T(n,`${t}/items`,s)}else s.push(`${t}/${i}: keyword ${i} is outside the supported subset`);else s.push(`${t}: a schema is an object`)}function q(e,t={},s="declarative.json"){const i=[],n=(e,t)=>i.push({file:s,severity:"error",message:e,...t?{code:t}:{}}),o=e=>i.push({file:s,severity:"warning",message:e});let r;try{const t=JSON.parse(e);if(!E(t))return n("a declarative definition is a JSON object"),i;r=t}catch(f){return n(f instanceof Error?f.message:String(f)),i}const a=E(t.bindings)?t.bindings:{},c=z(t.configSchema),l=(e,t)=>{if("string"==typeof e)J(e,t,c,n);else if(Array.isArray(e))e.forEach(((e,s)=>l(e,`${t}[${s}]`)));else if(E(e))for(const[s,i]of Object.entries(e))l(i,`${t}.${s}`)},d=(e,s)=>{void 0!==e&&(Array.isArray(e)?e.forEach(((e,i)=>{const r=`${s}[${i}]`;if(E(e))if("button"!==e.kind){"string"==typeof e.kind&&S.includes(e.kind)||n(`${r}.kind ${JSON.stringify(e.kind)}: one of ${[...S,"button"].join(", ")}`);for(const t of Object.keys(e))O.includes(t)||o(`${r}: key ${t} is ignored by the interpreter`);if(void 0===e.format||["text","number","percent","currency"].includes(e.format)||n(`${r}.format ${JSON.stringify(e.format)}: text, number, percent or currency`),"string"==typeof e.bind&&e.bind.includes(".")){const t=e.bind.slice(0,e.bind.indexOf("."));"props"===t||t in a||o(`${r}.bind ${JSON.stringify(e.bind)}: ${t} is not a declared binding, so it reads the field ${JSON.stringify(e.bind)} of the main source`)}}else((e,s)=>{void 0!==t.manifestVersion&&t.manifestVersion<3&&n(`${s}: a button ${j}`);for(const t of Object.keys(e))["kind","label","emit","params"].includes(t)||o(`${s}: key ${t} is ignored by the interpreter`);"string"==typeof e.label&&e.label||n(`${s}.label: the button's text (required)`),"string"==typeof e.emit&&e.emit?t.events&&!t.events.includes(e.emit)&&n(`${s}.emit ${e.emit}: not an event of component.json`,"EVENT_UNDECLARED"):n(`${s}.emit: the event the button raises (required)`),void 0!==e.params&&(E(e.params)?l(e.params,`${s}.params`):n(`${s}.params must be an object`))})(e,r);else n(`${r} must be an object`)})):n(`${s} must be an array`))};for(const[p,u]of Object.entries(r))"layout"===p?"stack"!==u&&"row"!==u&&n("layout: stack or row"):"items"===p?d(u,"items"):"view"===p?d(E(u)?u.items:void 0,"view.items"):"accent"===p?"string"!=typeof u&&n("accent must be a colour string"):"actions"===p?(Array.isArray(u)?u:[]).forEach(((e,t)=>{const s=E(e)?e:{};"string"==typeof s.command&&A.includes(s.command)||n(`actions[${t}].command: one of ${A.join(", ")}`),"string"==typeof s.id&&"string"==typeof s.label||n(`actions[${t}] needs id and label`)})):"inspector"===p?(Array.isArray(u)?u:[]).forEach(((e,t)=>{const s=E(e)?e:{};"string"==typeof s.kind&&N.includes(s.kind)||n(`inspector[${t}].kind: one of ${N.join(", ")}`),"string"==typeof s.key&&"string"==typeof s.label||n(`inspector[${t}] needs key and label`)})):o(`key ${p} is not part of the declarative vocabulary`);return void 0===r.items&&void 0===r.view&&o("no items: the control draws nothing"),i}function C(e,s,i=t,n={}){const o=[],a=(e,t)=>o.push({file:i,severity:"error",message:e,...t?{code:t}:{}});let c;try{const t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return a("a composition is a JSON object { layout, slots, chrome?, events? }"),o;c=t}catch(y){return a(y instanceof Error?y.message:String(y)),o}const l=z(s),d=(e,t)=>J(e,t,l,a),f=(e,t,s)=>{"number"==typeof e&&e>=0&&e<=s||("string"==typeof e&&/^\s*\{\{.*\}\}\s*$/.test(e)?d(e,t):a(`${t}: a number in [0, ${s}] or {{config.<key>}}`))};for(const t of Object.keys(c))["layout","slots","chrome","events"].includes(t)||a(`unknown key ${t} (a composition says layout, slots, chrome and events)`);const p=c.layout;let u="stack";if(p&&"object"==typeof p){"stack"===p.algorithm||"fixed"===p.algorithm||"grid"===p.algorithm?u=p.algorithm:a(`layout.algorithm ${JSON.stringify(p.algorithm)}: stack, fixed or grid (the algorithms the host ships)`);for(const[e,t]of Object.entries(p))if("algorithm"!==e)if("direction"!==e&&"spacing"!==e||"stack"===u)if("columns"!==e&&"gap"!==e||"grid"===u)if("direction"===e)"column"!==t&&"row"!==t&&a("layout.direction: column or row");else if("spacing"===e)f(t,"layout.spacing",2e3);else if("columns"===e)(!Number.isInteger(t)||t<1||t>12)&&a("layout.columns: an integer in [1, 12]");else if("gap"===e)f(t,"layout.gap",2e3);else if("padding"===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const[s,i]of Object.entries(t))["t","r","b","l"].includes(s)||a(`layout.padding.${s}: t, r, b or l`),f(i,`layout.padding.${s}`,2e3);else f(t,"layout.padding",2e3);else a(`layout: unknown key ${e}`);else a(`layout.${e} belongs to the grid layout`);else a(`layout.${e} belongs to the stack layout`);"grid"===u&&void 0===p.columns&&a("layout.columns (1…12) required: the cells of a grid row")}else a("layout { algorithm: stack | fixed | grid } required");const m=c.slots&&"object"==typeof c.slots&&!Array.isArray(c.slots)?c.slots:null;if(m){Object.keys(m).length>16&&a("at most 16 slots");for(const[e,t]of Object.entries(m)){const s=`slots.${e}`;if(w.test(e)||a(`${s}: a slot name is [a-z][a-z0-9_]{0,31}`),!t||"object"!=typeof t||Array.isArray(t)){a(`${s} must be an object`);continue}const i=t;for(const[e,t]of Object.entries(i))if("accepts"===e){if(!Array.isArray(t)||0===t.length||t.length>32){a(`${s}.accepts: 1…32 entries (cell:<ident>, a view type, container)`);continue}for(const e of t)"string"==typeof e&&e.startsWith("cell:")?(!_.test(e.slice(5))||r.encode(e.slice(5)).length>128)&&a(`${s}.accepts ${JSON.stringify(e)}: cell:<author_did>#<name>`):"container"===e||"string"==typeof e&&v.test(e)||a(`${s}.accepts ${JSON.stringify(e)}: cell:<ident>, a view type or container`)}else"min"===e?(!Number.isInteger(t)||t<0||t>64)&&a(`${s}.min: an integer in [0, 64]`):"max"===e?(!Number.isInteger(t)||t<1||t>1e3)&&a(`${s}.max: an integer in [1, 1000]`):"placement"===e?"stack"!==t&&"top"!==t&&"bottom"!==t&&"free"!==t?a(`${s}.placement: stack, top, bottom or free`):"fixed"===u&&"free"!==t?a(`${s}.placement: a fixed layout keeps every child where it is (free)`):"grid"===u&&"stack"!==t&&a(`${s}.placement: a grid fills its cells with the slots' children in slot order (stack)`):"title"===e?("string"!=typeof t||t.length>256)&&a(`${s}.title: at most 256 characters`):a(`${s}: unknown key ${e}`);Number.isInteger(i.min)&&Number.isInteger(i.max)&&i.min>i.max&&a(`${s}: min exceeds max`)}}else a("slots { <name>: { accepts?, min?, max?, placement? } } required");const h=c.chrome;if(void 0!==h)if(!h||"object"!=typeof h||Array.isArray(h))a("chrome must be an object");else for(const[t,r]of Object.entries(h)){const e=`chrome.${t}`;if("background"===t||"border"===t)"string"==typeof r&&r.length<=64?d(r,e):a(`${e}: a colour (≤ 64 characters) or {{config.<key>}}`);else if("radius"===t)f(r,e,200);else if("empty"===t)"string"==typeof r&&r.length<=1e3?d(r,e):a(`${e}: a text of at most 1000 characters`);else if("title"===t){const t=r;if(!t||"object"!=typeof t||Array.isArray(t)){a(`${e}: { text, slot? }`);continue}for(const[e,s]of Object.entries(t))"text"===e?"string"==typeof s&&s.length<=256?d(s,"chrome.title.text"):a("chrome.title.text: at most 256 characters"):"slot"===e?"string"==typeof s&&m&&s in m||a(`chrome.title.slot ${JSON.stringify(s)}: a slot of this composition`):a(`chrome.title: unknown key ${e}`);"string"!=typeof t.text&&a("chrome.title.text required")}else a(`chrome: unknown key ${t} (background, radius, border, title, empty)`)}if(void 0!==c.events)if(void 0!==n.manifestVersion&&n.manifestVersion<3&&a(`events ${j}`),E(c.events)){Object.keys(c.events).length>16&&a("events: at most 16");for(const[e,t]of Object.entries(c.events)){const s=`events.${e}`;if(w.test(e)||a(`${s}: an event name is [a-z][a-z0-9_]{0,31}`),!E(t)){a(`${s} must be an object { from: { slot, event }, title?, description? }`);continue}for(const[e,n]of Object.entries(t))"title"===e?("string"!=typeof n||n.length>256)&&a(`${s}.title: at most 256 characters`):"description"===e?("string"!=typeof n||n.length>4e3)&&a(`${s}.description: at most 4000 characters`):"from"!==e&&a(`${s}: unknown key ${e} (from, title, description)`);const i=t.from;if(!E(i)){a(`${s}.from { slot, event } required: the child event it re-raises`);continue}for(const e of Object.keys(i))"slot"!==e&&"event"!==e&&a(`${s}.from: unknown key ${e} (slot, event)`);const o="string"==typeof i.event&&w.test(i.event)?i.event:void 0;o||a(`${s}.from.event: an event name [a-z][a-z0-9_]{0,31}`);const r="string"==typeof i.slot&&m?m[i.slot]:void 0;if(!E(r)){a(`${s}.from.slot ${JSON.stringify(i.slot)}: a slot of this composition`);continue}if(!o)continue;const c=(Array.isArray(r.accepts)?r.accepts:[]).filter((e=>"string"==typeof e&&e.startsWith("cell:"))).map((e=>e.slice(5)));if(0===c.length){a(`${s}: slot ${i.slot} accepts no cell:<ident>, so no control there declares ${o}`,"EVENT_UNDECLARED");continue}c.map((e=>{var t;return null==(t=n.cellEvents)?void 0:t.call(n,e)})).every((e=>void 0!==e&&!e.includes(o)))&&a(`${s}: no control slot ${i.slot} accepts (${c.join(", ")}) declares the event ${o}`,"EVENT_UNDECLARED")}}else a("events must be an object { <name>: { from: { slot, event }, title?, description? } }");return o}function W(t,s,i,n){const o=[],a=e,c=e=>o.push({file:a,severity:"error",message:e});let l;try{const e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return c("must be a JSON object"),o;l=e}catch(O){return c(O instanceof Error?O.message:String(O)),o}for(const e of Object.keys(l))g.includes(e)||c(`unknown key ${e}`);const d=l.manifest_version,f="number"==typeof d&&Number.isInteger(d)&&d>=1?d:0;f?f>3&&c(`manifest_version ${d} is newer than this client reads (3)`):c("manifest_version (1…3) required");const p=f>0&&f<3,u=l.ident;let m="";u&&"object"==typeof u?("string"==typeof u.author_did&&$.test(u.author_did)||c("ident.author_did must be a DID (did:<method>:<id>)"),"string"==typeof u.name&&v.test(u.name)||c("ident.name must be [a-z0-9][a-z0-9._-]{0,63}"),"string"==typeof u.author_did&&"string"==typeof u.name&&(m=`${u.author_did}#${u.name}`,r.encode(m).length>128&&c("an identity is at most 128 bytes"))):c("ident { author_did, name } required");const h="composite"===l.kind;if("declarative"===l.kind||"html"===l.kind||h||c("kind must be declarative, html or composite"),h&&1===f&&c(`kind composite ${k}`),h)for(const e of["accepts","allow_no_source"])void 0!==l[e]&&c(`${e}: a composite is a container of Blocks, not a Cell showing data`);if(("string"!=typeof l.title||!l.title||l.title.length>256)&&c("title: 1…256 characters"),void 0!==l.config_schema){const e=[];T(l.config_schema,"config_schema",e),e.forEach(c)}if(void 0!==l.bindings)if(l.bindings&&"object"==typeof l.bindings)for(const e of Object.keys(l.bindings))w.test(e)&&"props"!==e||c(`binding name ${e}: [a-z][a-z0-9_]{0,31}, not props`);else c("bindings must be an object");if(void 0!==l.deps)if(!Array.isArray(l.deps)||l.deps.length>32)c("deps: at most 32 identities <author_did>#<name>");else if(l.deps.length>0&&1===f)c(`deps ${k}`);else{const e=new Set;for(const t of l.deps)"string"==typeof t&&_.test(t)?t===m?c("deps: a control cannot depend on itself"):e.has(t)&&c(`deps lists ${t} twice`):c(`deps: ${JSON.stringify(t)} is not an identity <author_did>#<name>`),e.add(String(t))}let y=[];if(void 0!==l.events){if(h)c("events: a composite declares its events in composition.json (events.<name>.from re-raises an event of a child)");else if(p)c(`events ${j}`);else{const e=[];!function(e,t){if(E(e)){Object.keys(e).length>16&&t.push("events: at most 16");for(const[s,i]of Object.entries(e)){const e=`events.${s}`;if(w.test(s)||t.push(`${e}: an event name is [a-z][a-z0-9_]{0,31}`),E(i)){for(const[s,n]of Object.entries(i))"title"===s?("string"!=typeof n||n.length>256)&&t.push(`${e}.title: at most 256 characters`):"description"===s?("string"!=typeof n||n.length>4e3)&&t.push(`${e}.description: at most 4000 characters`):"params"!==s&&t.push(`${e}: unknown key ${s} (title, description, params)`);if(void 0!==i.params)if(E(i.params)){Object.keys(i.params).length>16&&t.push(`${e}.params: at most 16`);for(const[s,n]of Object.entries(i.params)){const i=`${e}.params.${s}`;if(w.test(s)||t.push(`${i}: a param name is [a-z][a-z0-9_]{0,31}`),E(n)){for(const[e,s]of Object.entries(n))"type"===e?"string"==typeof s&&x.includes(s)||t.push(`${i}.type: ${x.join(", ")}`):"required"===e?"boolean"!=typeof s&&t.push(`${i}.required must be a boolean`):"description"===e?("string"!=typeof s||s.length>1e3)&&t.push(`${i}.description: at most 1000 characters`):t.push(`${i}: unknown key ${e} (type, required, description)`);void 0===n.type&&t.push(`${i}.type required`)}else t.push(`${i} must be an object { type, required?, description? }`)}}else t.push(`${e}.params must be an object { <param>: { type, required?, description? } }`)}else t.push(`${e} must be an object { title?, description?, params? }`)}}else t.push("events must be an object { <name>: { title?, description?, params? } }")}(l.events,e),e.forEach(c)}!h&&E(l.events)&&(y=Object.keys(l.events))}const b=e=>"string"==typeof e&&s.includes(e),S=new Set([a]);if("html"===l.kind){const e=l.entry;if(e&&"object"==typeof e&&"string"==typeof e.html)for(const[t,s]of Object.entries(e))b(s)?S.add(String(s)):c(`entry.${t} ${JSON.stringify(s)} is not in the directory`);else c("entry must be { html, css?, js? }");void 0!==l.host_api&&2!==l.host_api&&3!==l.host_api?c("host_api: the HTML Block host speaks API 2 and 3"):3===l.host_api&&p&&c(`host_api 3 ${j}`),y.length>0&&3!==l.host_api&&o.push({file:a,severity:"warning",message:"events: an HTML control raises them with aiws.emit, which is host API 3 (set host_api to 3)"})}else if("declarative"===l.kind||h){if(b(l.entry)){S.add(String(l.entry));const e=null==i?void 0:i(String(l.entry)),t=f||void 0;void 0!==e&&h?o.push(...C(e,l.config_schema,String(l.entry),{manifestVersion:t,cellEvents:n})):void 0!==e&&o.push(...q(e,{bindings:l.bindings,events:y,configSchema:l.config_schema,manifestVersion:t},String(l.entry)))}else c(`entry ${JSON.stringify(l.entry)} is not in the directory`);h&&void 0!==l.host_api&&c("host_api: a composite runs no code of its own (its layout and chrome are the host's)"),h||void 0===l.host_api||1===l.host_api||c("host_api: the declarative interpreter is version 1")}for(const e of Array.isArray(l.assets)?l.assets:[])b(e)?S.add(String(e)):c(`asset ${JSON.stringify(e)} is not in the directory`);void 0!==l.agent&&(b(l.agent)?S.add(String(l.agent)):c(`agent ${JSON.stringify(l.agent)} is not in the directory`));for(const e of s)I(e)?S.has(e)||o.push({file:e,severity:"warning",message:"not named by component.json: kept in the source snapshot only"}):o.push({file:e,severity:"error",message:"a file of a source directory: a relative path whose parts do not start with '.'"});return o}function D(e){if(!e||"object"!=typeof e)throw new o([{file:s,severity:"error",message:"must be a JSON object"}]);const t=e,i=t.manifest_version;if("number"!=typeof i||i<1)throw new o([{file:s,severity:"error",message:"manifest_version required"}]);if(i>3)throw new o([{file:s,severity:"error",message:`manifest_version ${i} needs a newer client (this one reads 3)`}]);if("aiws"!==t.purpose)throw new o([{file:s,severity:"error",message:"purpose must be aiws"}]);if(!Array.isArray(t.controls))throw new o([{file:s,severity:"error",message:"controls must be an array"}]);return{manifest_version:i,purpose:"aiws",host_api:t.host_api??{},controls:t.controls,workspace_templates:Array.isArray(t.workspace_templates)?t.workspace_templates:[]}}const B=/^[a-z0-9][a-z0-9-]{0,63}$/;function L(e){return`templates/${e}/`}async function F(e,t){const s=L(t),i=[];for(const[n,o]of e)n.startsWith(s)&&i.push([n.slice(s.length),o]);return f(i)}function M(e,t){if(!E(e))return["a template is an object { id, title, snapshot, digest, requires, description?, params?, reset? }"];const s=[];for(const n of Object.keys(e))["id","title","description","snapshot","digest","requires","params","reset"].includes(n)||s.push(`unknown key ${n}`);"string"==typeof e.id&&B.test(e.id)?e.snapshot!==`${L(e.id)}snapshot.json`&&s.push(`snapshot must be ${L(e.id)}snapshot.json`):s.push("id: [a-z0-9][a-z0-9-]{0,63}"),("string"!=typeof e.title||!e.title||e.title.length>256)&&s.push("title: 1…256 characters"),void 0!==e.description&&("string"!=typeof e.description||e.description.length>4e3)&&s.push("description: at most 4000 characters"),"string"==typeof e.digest&&/^sha256:[0-9a-f]{64}$/.test(e.digest)||s.push("digest: sha256:<64 hex digits>");const i=e.requires;if(E(i)){for(const e of Object.keys(i))"host_api"!==e&&"controls"!==e&&s.push(`requires: unknown key ${e}`);if(void 0!==i.host_api)if(E(i.host_api))for(const[e,t]of Object.entries(i.host_api))("html"!==e&&"declarative"!==e||!Number.isInteger(t)||t<1)&&s.push(`requires.host_api.${e}: html or declarative, a positive integer`);else s.push("requires.host_api must be an object { html?, declarative? }");if(!Array.isArray(i.controls)||i.controls.length>256)s.push("requires.controls: at most 256 identities");else{const e=new Set;for(const n of i.controls)"string"==typeof n&&t.has(n)?e.has(n)&&s.push(`requires.controls lists ${n} twice`):s.push(`requires.controls: ${JSON.stringify(n)} is not a control of this manifest`),e.add(n)}}else s.push("requires { host_api?, controls } required");if(void 0!==e.params)if(!E(e.params)||Object.keys(e.params).length>32)s.push("params: an object of at most 32 { type, title?, default? }");else for(const[n,o]of Object.entries(e.params)){const e=`params.${n}`;if(w.test(n)||s.push(`${e}: a param name is [a-z][a-z0-9_]{0,31}`),E(o)){for(const[t,i]of Object.entries(o))"type"===t?"string"!==i&&"number"!==i&&"boolean"!==i&&s.push(`${e}.type: string, number or boolean`):"title"===t?("string"!=typeof i||i.length>256)&&s.push(`${e}.title: at most 256 characters`):"default"===t?["string","number","boolean"].includes(typeof i)||s.push(`${e}.default: a string, number or boolean`):s.push(`${e}: unknown key ${t} (type, title, default)`);void 0===o.type&&s.push(`${e}.type required`)}else s.push(`${e} must be an object { type, title?, default? }`)}if(void 0!==e.reset){const t=E(e.reset)?e.reset.tables:void 0;!E(e.reset)||Object.keys(e.reset).some((e=>"tables"!==e))?s.push("reset: { tables }"):void 0!==t&&(!Array.isArray(t)||t.length>64||new Set(t).size!==t.length||t.some((e=>"string"!=typeof e||!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e))))&&s.push("reset.tables: at most 64 distinct table ids")}return s}async function R(e,t,s){const i=/[*?[\]\\]/.test(s)?void 0:s;return(await e.list("string"==typeof t?t:{ref:t},{limit:i?10:1e3,...i?{filter:{name_glob:i}}:{}},["base","ident"])).entries.find((e=>e.name===s))}async function P(e,t){const s=t.split("/").filter(Boolean);if(0===s.length)throw new Error(`not a folder path: ${t}`);let i=(await e.stat(`/${s[0]}`)).ref;for(const n of s.slice(1)){const s=await R(e,i,n);if(s&&"dir"!==s.target.kind)throw new o([{file:n,severity:"error",message:`${n} in ${t} is not a folder`}]);i=s?s.target.ref:(await e.mkdir({ref:i},n)).ref}return i}async function V(e,t){const s=t.split("/").filter(Boolean);if(0===s.length)return null;let i=(await e.stat(`/${s[0]}`)).ref;for(const n of s.slice(1)){const t=await R(e,i,n);if(!t||"dir"!==t.target.kind)return null;i=t.target.ref}return i}async function U(t,s){const i=await V(t,s);return null!==i&&void 0!==await R(t,i,e)}async function G(e,t,s,i){const n="string"==typeof t?await P(e,t):t;await e.uploadFile(n,s,i,{overwrite:!0})}const H=e=>new Promise((t=>setTimeout(t,e)));async function K(e,t){const s=[],i=[],n=async(t,o,r)=>{var a,c,l;let d;do{const f=await e.list("string"==typeof t?t:{ref:t},{limit:500,...d?{cursor:d}:{}},["base","ident"]);for(const e of f.entries){if(e.name.startsWith("."))continue;const t=`${o}${e.name}`;if("dir"===e.target.kind){r>=8?i.push({file:t,severity:"error",message:"sub-folders nest at most 8 levels"}):await n(e.target.ref,`${t}/`,r+1);continue}if("file"!==e.target.kind){i.push({file:t,severity:"error",message:"only files and folders belong to a control source"});continue}const d=e.target.ref,f="object"===d.type?d.obj_id:"string"==typeof(null==(a=e.target.attrs)?void 0:a.obj_id)?e.target.attrs.obj_id:void 0;s.push({name:t,...f?{obj_id:f}:{},..."live"===d.type?{node_id:d.node_id}:{},..."string"==typeof(null==(c=e.target.attrs)?void 0:c.etag)?{etag:e.target.attrs.etag}:{},..."number"==typeof(null==(l=e.target.attrs)?void 0:l.size)?{size:e.target.attrs.size}:{}})}d=f.truncated?f.next_cursor:void 0}while(d)};if(await n(t,"",0),0===s.length&&i.push({file:"",severity:"error",message:`${t} holds no files`}),s.length>64&&i.push({file:"",severity:"error",message:"a control holds at most 64 files"}),i.some((e=>"error"===e.severity)))throw new o(i);return s.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:0))}async function X(e,t,s,i){const n=s.lastIndexOf("/");await G(e,n<0?t:c(t,s.slice(0,n)),n<0?s:s.slice(n+1),i)}async function Y(e,t){const s=[];for(const i of t){if(!i.node_id)throw new o([{file:i.name,severity:"error",message:"the file service did not name this file"}]);s.push([i.name,new Uint8Array(await(await e.readFile(i.node_id)).arrayBuffer())])}return f(s)}async function Q(e,t){try{const s=await R(e,t,i),n="live"===(null==s?void 0:s.target.ref.type)?s.target.ref.node_id:void 0;if(!n)return null;const o=await e.readFile(n);return await o.json()}catch{return null}}async function Z(e,t,s){await G(e,t,i,r.encode(`${JSON.stringify(s,null,2)}\n`))}exports.AIWS_BUILD_STATE_FILE=i,exports.AIWS_COMPONENT_FILE=e,exports.AIWS_COMPOSITION_FILE=t,exports.AIWS_DECLARATIVE_API_VERSION=1,exports.AIWS_HTML_API_VERSION=3,exports.AIWS_MANIFEST_FILE=s,exports.AIWS_MANIFEST_VERSION=3,exports.AIWS_MAX_INLINE_BYTES=u,exports.AIWS_MAX_SOURCE_FILES=64,exports.AIWS_TEMPLATE_FORMAT=n,exports.AiwsSourceError=o,exports.aiwsContentDigest=f,exports.aiwsTemplateDigest=F,exports.buildControl=async function(e,t,s,i,n={}){const o=await K(t,i),r=await Q(t,i),a=r&&r.workspace_id===s?{def_rev:r.def_rev,dir_rev:r.dir_rev}:void 0,c=await e.extBuild(s,{files:await y(t,o,n.upload),...n.folderId?{folder_id:n.folderId}:{},...a?{expect:a}:{},...n.force?{force:!0}:{},...n.dryRun?{dry_run:!0}:{},...n.migration?{migration:n.migration}:{}});return n.dryRun||"string"!=typeof c.def_entity_id||"number"!=typeof c.def_rev||await Z(t,i,{workspace_id:s,def_entity_id:c.def_entity_id,def_rev:c.def_rev,dir_rev:Number(c.dir_rev??0),ident:String(c.ident??""),at:(new Date).toISOString()}),{...c,files:o}},exports.buildFiles=y,exports.checkComponent=W,exports.checkComposition=C,exports.checkDeclarative=q,exports.collectSources=K,exports.compatManifest=D,exports.controlSkeleton=function(s){const i=s.title??s.name;if("composite"===s.kind){const n="fixed"===s.algorithm,o=s.slots??{items:{placement:n?"free":"stack",title:"Items"}},r={layout:n?{algorithm:"fixed",padding:12}:{algorithm:"stack",direction:"column",spacing:"{{config.gap}}",padding:12},slots:o,chrome:{background:"{{config.background}}",radius:12,title:{text:"{{config.title}}"},empty:"Drop Blocks here"}},a={manifest_version:3,ident:{author_did:s.authorDid,name:s.name},kind:"composite",title:i,description:`${i}: a panel of Blocks`,default_size:{w:320,h:360},config_schema:{type:"object",properties:{title:{type:"string",title:"Title",default:i},background:{type:"string",title:"Background",default:"#f6f7fb"},gap:{type:"integer",title:"Gap (px)",default:8,minimum:0,maximum:64}}},entry:t,deps:s.deps??[],catalog:{group:"custom",description:`${i}`},agent:"AGENT.md"},c=Object.keys(o).map((e=>`\`${e}\``)).join(", ");return{[e]:`${JSON.stringify(a,null,2)}\n`,[t]:`${JSON.stringify(r,null,2)}\n`,"AGENT.md":`# ${i}\n\nA composite: an instance is a \`buckyos.container { kind: "composite", def_ref }\`; put Blocks under it with \`slot\` set to one of ${c}. Config: \`title\`, \`background\`, \`gap\`.\n`}}const n={manifest_version:3,ident:{author_did:s.authorDid,name:s.name},kind:s.kind??"declarative",title:i,description:`${i}: a control of this Workspace`,accepts:["buckyos.table-source","buckyos.record"],allow_no_source:!0,default_size:{w:260,h:140},config_schema:{type:"object",properties:{label:{type:"string",title:"Label",default:i}}},bindings:{data:{accepts:["buckyos.table-source"],title:"Data",description:"The table this control summarizes"}},catalog:{group:"custom",description:`${i}`},agent:"AGENT.md"},o=`# ${i}\n\nBind \`data\` to a table. Config: \`label\` (text).\n`;if("html"===s.kind){const t={clicked:{title:"Clicked",description:"Raised when someone clicks the button (in run mode)",params:{count:{type:"number",description:"Rows of the bound table"}}}};return{[e]:`${JSON.stringify({...n,host_api:3,events:t,entry:{html:"view.html",css:"style.css",js:"behavior.js"}},null,2)}\n`,"view.html":'<div class="card"><div class="label" id="label"></div><div class="value" id="value">—</div><button id="go" type="button">Go</button></div>\n',"style.css":".card{font:14px system-ui;padding:12px}.label{opacity:.7}.value{font-size:28px;font-weight:600}\n","behavior.js":["document.getElementById('label').textContent = (aiws.context.config || {}).label || ''","var count = 0","if (aiws.bindings.data) aiws.input('data').rows().then(function (rows) { count = rows.length; document.getElementById('value').textContent = String(count) })","// the public event of component.json: an instance binds handlers to it in its `on` (host API 3)","document.getElementById('go').addEventListener('click', function () { aiws.emit('clicked', { count: count }) })",""].join("\n"),"AGENT.md":`${o}Event: \`clicked\` (\`count\`), raised by its button; bind handlers to it in the instance's \`on\`.\n`}}return{[e]:`${JSON.stringify({...n,entry:"declarative.json"},null,2)}\n`,"declarative.json":`${JSON.stringify({layout:"stack",items:[{kind:"metric",label:i,bind:"data.count",format:"number"},{kind:"text",text:"Rows of the bound table"}]},null,2)}\n`,"AGENT.md":o}},exports.createControlSource=async function(t,s,i){const n=await P(t,s),a=await t.list({ref:n},{limit:500},["base"]).catch((()=>null));if(null==a?void 0:a.entries.some((t=>t.name===e)))throw new o([{file:e,severity:"error",message:`${s} already holds a control`}]);for(const[e,o]of Object.entries(i))await G(t,n,e,r.encode(o));return n},exports.ensureFolder=P,exports.exportBundle=async function(e,t,i,n){const o=await e.extExport(t,i,"package"),a=new Map;a.set(s,r.encode(`${JSON.stringify(o.manifest,null,2)}\n`));for(const s of o.files)a.set(s.path,void 0!==s.text?r.encode(s.text):await n(t,String(s.obj_id)));return{manifest:D(o.manifest),files:a,controls:o.controls}},exports.findFolder=V,exports.folderName=l,exports.hasControlSource=U,exports.homeControlDir=function(e,t,s){return`/home/${e}/AI Workspace/${l(t)}/controls/${s}`},exports.homeExportDir=function(e,t){return`/home/${e}/AI Workspace/exports/${t}`},exports.isSourcePath=I,exports.joinPath=c,exports.packBuildFiles=h,exports.pullControl=async function(e,t,s,i,n,o){const a=(await e.extExport(s,[i],"pull")).controls[0];await P(t,n);for(const l of a.files)await X(t,n,l.name,void 0!==l.text?r.encode(l.text):await o(s,String(l.obj_id)));const c={workspace_id:s,def_entity_id:a.entity_id,def_rev:a.def_rev,dir_rev:a.dir_rev,ident:a.ident,at:(new Date).toISOString()};return await Z(t,n,c),{files:a.files.map((e=>e.name)),state:c}},exports.readBuildState=Q,exports.slotCells=function(e){const t=new Set;for(const s of Object.values(e.slots??{}))for(const e of s.accepts??[])e.startsWith("cell:")&&t.add(e.slice(5));return[...t].sort()},exports.sourceStateKey=function(e){return`aiws:src:${e}`},exports.sourcesDigest=Y,exports.sourcesKey=p,exports.templateDir=L,exports.unbuiltChanges=async function(e,t,s,i,n){var o;if(!(await U(t,n)))return null;const r=await Y(t,await K(t,n)),a=await e.extExport(s,[i],"pull"),c=String((null==(o=a.controls[0])?void 0:o.digest)??"");return{changed:r!==c,home:r,built:c}},exports.verifyBundle=async function(t){var i,r;const c=t.get(s);if(!c)throw new o([{file:s,severity:"error",message:"missing"}]);let l;try{l=JSON.parse(a.decode(c))}catch(g){throw new o([{file:s,severity:"error",message:String(g)}])}const d=D(l),p=[],u=d.workspace_templates;u.length>0&&d.manifest_version<3&&p.push({file:s,severity:"error",message:`Workspace templates need manifest_version 3 (raise it in ${s})`}),u.length>32&&p.push({file:s,severity:"error",message:"at most 32 Workspace templates"}),0===d.controls.length&&0===u.length&&p.push({file:s,severity:"error",message:"lists no control"});const m=new Map;for(const s of d.controls){const i="string"==typeof s.dir?t.get(`${s.dir}${e}`):void 0;try{const e=i?JSON.parse(a.decode(i)):void 0;E(e)&&m.set(s.ident,E(e.events)?Object.keys(e.events):[])}catch{}}const h=new Set;for(const n of d.controls){if("string"!=typeof n.dir||!/^controls\/[a-z0-9][a-z0-9._-]{0,70}\/$/.test(n.dir)||h.has(n.dir)){p.push({file:s,severity:"error",message:`control ${n.ident}: bad or repeated dir`});continue}h.add(n.dir);const o=[...t].filter((([e])=>e.startsWith(n.dir))).map((([e,t])=>[e.slice(n.dir.length),t]));await f(o)!==n.digest&&p.push({file:n.dir,severity:"error",message:"the files do not match the manifest digest"});const c=o.find((([t])=>t===e));if(!c){p.push({file:`${n.dir}${e}`,severity:"error",message:"missing"});continue}const l=e=>{const t=o.find((([t])=>t===e));return t?a.decode(t[1]):void 0};for(const e of W(a.decode(c[1]),o.map((([e])=>e)),l,(e=>m.get(e))))p.push({...e,file:`${n.dir}${e.file}`});try{const e=JSON.parse(a.decode(c[1]));`${null==(i=e.ident)?void 0:i.author_did}#${null==(r=e.ident)?void 0:r.name}`===n.ident&&e.kind===n.kind||p.push({file:n.dir,severity:"error",message:"ident and kind must match its component.json"}),JSON.stringify([...e.deps??[]].sort())!==JSON.stringify([...n.deps??[]].sort())&&p.push({file:n.dir,severity:"error",message:"deps must match its component.json"})}catch{}}const y=new Set(d.controls.map((e=>e.ident)));for(const e of d.controls)for(const t of e.deps??[])y.has(t)||p.push({file:s,severity:"error",message:`${e.ident} depends on ${t}, which the bundle does not carry`});for(const[e,o]of u.entries()){const i=E(o)&&"string"==typeof o.id?`template ${o.id}`:`workspace_templates[${e}]`;for(const e of M(o,y))p.push({file:s,severity:"error",message:`${i}: ${e}`});if(!E(o)||"string"!=typeof o.id||!B.test(o.id))continue;const r=L(o.id);if(h.has(r)){p.push({file:s,severity:"error",message:`${i} is listed twice`});continue}h.add(r);const c=t.get(`${r}snapshot.json`);let l;try{l=c?JSON.parse(a.decode(c)).format:void 0}catch{l=void 0}c?l!==n&&p.push({file:`${r}snapshot.json`,severity:"error",message:`not a template snapshot (format ${n})`}):p.push({file:`${r}snapshot.json`,severity:"error",message:"missing"}),await F(t,o.id)!==o.digest&&p.push({file:r,severity:"error",message:"the files do not match the template digest"})}for(const e of t.keys())e===s||[...h].some((t=>e.startsWith(t)))||p.push({file:e,severity:"error",message:"belongs to no control or template of the manifest"});return{manifest:d,diagnostics:p}},exports.watchControl=async function(e,t,s,i={}){var n,o;let r,a="",c=Promise.resolve();const l=()=>{c=c.then((async()=>{let i;try{i=await K(e,t)}catch{return}const n=p(i);n!==a&&(a=n,await s(i))})).catch((()=>{}))};for(l();!(null==(n=i.signal)?void 0:n.aborted);){const s=await e.list(t,{limit:1},["base"]),n=e.watch({tokens:s.watch_token?[s.watch_token]:[],signal:i.signal});try{for await(const e of n)r&&clearTimeout(r),r=setTimeout(l,i.debounceMs??500)}catch{if(null==(o=i.signal)?void 0:o.aborted)break;await H(2e3)}finally{n.close()}}r&&clearTimeout(r),await c},exports.writeBuildState=Z,exports.writeHomeFile=G,exports.writeSourceFile=X;
2
+ //# sourceMappingURL=aiws_ext.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiws_ext.cjs","sources":["../src/aiws_ext.ts"],"sourcesContent":["/**\n * AI Workspace extension controls (buckyos src/frame/aiworkspace/README.md “Extension controls”), shared by the\n * Desktop and the CLI: a control's source lives in a home folder of the Zone file service (files may sit in\n * sub-folders: their names are relative paths, Q23); `build` lists it over NFSP and hands each file's object to\n * `ext.build`, `pull` writes a Workspace snapshot back, `watch` rebuilds on change; bundles (the AIWS manifest plus\n * `controls/<dir>/<path>` and Workspace templates under `templates/<id>/`) are what exports, packages and the library\n * carry.\n * Runs in browsers and Deno (fetch, crypto.subtle); no dependencies.\n */\nimport type { AiWorkspaceClient, AiwsMigration, AiwsTemplateItem } from './aiworkspace_client'\nimport type { NfspClient, WireRef } from './nfsp'\n\n/** The two service calls these drivers make (an `AiWorkspaceClient`, or a host's own session with the same shape). */\nexport type AiwsExtRpc = Pick<AiWorkspaceClient, 'extBuild' | 'extExport'>\n\n/** Puts bytes into the Zone's named store as a FileObject the caller may read and answers its `cyfile:` id (the\n * Desktop's asset upload, the CLI's NDM upload): what a build sends by reference when inline bytes would exceed the\n * service's limit (Q22). */\nexport type AiwsUploader = (name: string, bytes: Uint8Array) => Promise<string>\n\nexport const AIWS_COMPONENT_FILE = 'component.json'\n/** The entry of a composite control (P1). */\nexport const AIWS_COMPOSITION_FILE = 'composition.json'\nexport const AIWS_MANIFEST_FILE = 'aiws-manifest.json'\n/** A client's own record of the base it last built or pulled (never part of the source snapshot: dot files are not). */\nexport const AIWS_BUILD_STATE_FILE = '.aiws-build.json'\n/** The newest component.json / AIWS manifest version this module reads (older ones stay readable, Q19). Version 2\n * adds `kind: composite` and non-empty `deps`; version 3 `events`, the declarative `button`, composite `events` and\n * Workspace templates. */\nexport const AIWS_MANIFEST_VERSION = 3\n/** The newest HTML Block host API (`window.aiws` v3: `emit`, `createBlock { parent, slot }`, `context.interactive`;\n * hosts run 2 and 3) and the declarative interpreter version. */\nexport const AIWS_HTML_API_VERSION = 3\nexport const AIWS_DECLARATIVE_API_VERSION = 1\n/** The `format` of a Workspace template's `snapshot.json` (Q32). */\nexport const AIWS_TEMPLATE_FORMAT = 'aiws-template/1'\nexport const AIWS_MAX_SOURCE_FILES = 64\n\n/**\n * One file of a source folder. `obj_id` is set when the file service holds it as a named-store FileObject (`cyfile:`):\n * the service then reads it by reference. Files of a native home folder have none (their `obj_id`, when the file\n * service reports one, is a `sha256:` content hash the service cannot fetch): their bytes travel with the build.\n */\nexport interface AiwsSourceFile { name: string; obj_id?: string; node_id?: string; etag?: string; size?: number }\nexport interface AiwsDiagnostic {\n file: string\n line?: number\n col?: number\n severity: 'error' | 'warning'\n message: string\n /** `DEP_MISSING`: a `deps` entry or a slot's `cell:<ident>` names no definition of the Workspace; `EVENT_UNDECLARED`:\n * a composite re-raises an event no `cell:<ident>` of that slot declares, or a button emits an undeclared event. */\n code?: string\n /** Blocks whose contract a rebuild would break. */\n instances?: { entity_id: string; title?: string | null }[]\n /** Definitions that build on the one a rebuild would narrow. */\n dependents?: { ident: string; def_entity_id: string }[]\n}\nexport interface AiwsBuildState { workspace_id: string; def_entity_id: string; def_rev: number; dir_rev: number; ident?: string; at?: string }\nexport interface AiwsManifestControl { ident: string; name: string; kind: string; version: number; digest: string; dir: string; title?: string; description?: string; catalog?: Record<string, unknown>; deps?: string[] }\nexport interface AiwsManifest { manifest_version: number; purpose: 'aiws'; host_api?: Record<string, number>; controls: AiwsManifestControl[]; workspace_templates: AiwsTemplateItem[] }\nexport interface AiwsBundle { manifest: AiwsManifest; files: Map<string, Uint8Array> }\n\n/** A source directory that cannot be built as it is (not a service refusal: `diagnostics` say why). */\nexport class AiwsSourceError extends Error {\n readonly diagnostics: AiwsDiagnostic[]\n constructor(diagnostics: AiwsDiagnostic[]) {\n super(diagnostics.filter((d) => d.severity === 'error').map((d) => `${d.file ? `${d.file}: ` : ''}${d.message}`).join('; ') || 'invalid control source')\n this.name = 'AiwsSourceError'\n this.diagnostics = diagnostics\n }\n}\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nexport function joinPath(dir: string, name: string): string {\n return `${dir.replace(/\\/+$/, '')}/${name}`\n}\n\n/** A Workspace title as one folder name (no `/`, no leading dot). */\nexport function folderName(title: string): string {\n const cleaned = title.replace(/[/\\\\\\u0000-\\u001f]/g, ' ').replace(/^\\.+/, '').trim()\n return cleaned.slice(0, 80) || 'Workspace'\n}\n\n/** The suggested home folder of a control (README: a suggestion; the definition never stores it). */\nexport function homeControlDir(owner: string, workspaceTitle: string, name: string): string {\n return `/home/${owner}/AI Workspace/${folderName(workspaceTitle)}/controls/${name}`\n}\n\n/** Where a client writes an export bundle before packing it. */\nexport function homeExportDir(owner: string, pkg: string): string {\n return `/home/${owner}/AI Workspace/exports/${pkg}`\n}\n\n/** `user_state` key under which each person remembers the home folder of a definition. */\nexport function sourceStateKey(defEntityId: string): string {\n return `aiws:src:${defEntityId}`\n}\n\n// ---- digests (same canonical forms as the service: store/src/ext.rs)\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as ArrayBuffer)\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** `sha256:` over `[[name, sha256 hex of its bytes], …]` sorted by name: a control's content digest. */\nexport async function aiwsContentDigest(files: Iterable<[string, Uint8Array]>): Promise<string> {\n const pairs: [string, string][] = []\n for (const [name, bytes] of files) pairs.push([name, await sha256Hex(bytes)])\n pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n return `sha256:${await sha256Hex(encoder.encode(JSON.stringify(pairs)))}`\n}\n\n/** What a set of sources is, for \"nothing changed since the last build\" (names, objects or versions). */\nexport function sourcesKey(files: AiwsSourceFile[]): string {\n return JSON.stringify([...files].sort((a, b) => a.name.localeCompare(b.name)).map((f) => [f.name, f.obj_id ?? f.etag ?? '']))\n}\n\n/** Bytes a single build may carry inline (the service's limit). */\nexport const AIWS_MAX_INLINE_BYTES = 4 * 1024 * 1024\n\nfunction base64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n return btoa(binary)\n}\n\nexport type AiwsBuildFile = { name: string; obj_id: string } | { name: string; base64: string }\n\n/**\n * The `files` of `ext.build` from bytes the client holds: inline while the total stays within the service's limit;\n * beyond it, the largest files go to the named store through `upload` and are sent by reference (Q22) — without an\n * uploader the build is refused. `byRef` are files already held as FileObjects.\n */\nexport async function packBuildFiles(files: { name: string; bytes: Uint8Array }[], upload?: AiwsUploader, byRef: { name: string; obj_id: string }[] = []): Promise<AiwsBuildFile[]> {\n let total = files.reduce((n, f) => n + f.bytes.length, 0)\n const uploaded = new Map<string, string>()\n if (total > AIWS_MAX_INLINE_BYTES) {\n if (!upload) throw new AiwsSourceError([{ file: '', severity: 'error', message: `a control's inline files are limited to ${AIWS_MAX_INLINE_BYTES} bytes per build` }])\n for (const f of [...files].sort((a, b) => b.bytes.length - a.bytes.length)) {\n if (total <= AIWS_MAX_INLINE_BYTES) break\n uploaded.set(f.name, await upload(f.name, f.bytes))\n total -= f.bytes.length\n }\n }\n const out: AiwsBuildFile[] = [...byRef]\n for (const f of files) {\n const obj = uploaded.get(f.name)\n out.push(obj ? { name: f.name, obj_id: obj } : { name: f.name, base64: base64(f.bytes) })\n }\n return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n}\n\n/** The `files` of `ext.build`: FileObjects by reference, everything else read over the file service and sent inline\n * (or, past the inline limit, uploaded through `upload`). */\nexport async function buildFiles(nfsp: NfspClient, files: AiwsSourceFile[], upload?: AiwsUploader): Promise<AiwsBuildFile[]> {\n const byRef: { name: string; obj_id: string }[] = []\n const inline: { name: string; bytes: Uint8Array }[] = []\n for (const f of files) {\n if (f.obj_id?.startsWith('cyfile:')) { byRef.push({ name: f.name, obj_id: f.obj_id }); continue }\n if (!f.node_id) throw new AiwsSourceError([{ file: f.name, severity: 'error', message: 'the file service did not name this file' }])\n inline.push({ name: f.name, bytes: new Uint8Array(await (await nfsp.readFile(f.node_id)).arrayBuffer()) })\n }\n return packBuildFiles(inline, upload, byRef)\n}\n\n// ---- component.json pre-check (the service's composer is authoritative; this catches the usual mistakes early)\n\nconst COMPONENT_KEYS = ['manifest_version', 'ident', 'kind', 'title', 'description', 'host_api', 'accepts', 'allow_no_source', 'default_size', 'config_schema', 'bindings', 'entry', 'assets', 'catalog', 'agent', 'deps', 'events']\nconst SCHEMA_KEYWORDS = ['type', 'enum', 'default', 'required', 'title', 'description', 'minimum', 'maximum', 'minLength', 'maxLength', 'properties', 'items']\nconst NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/\nconst DID = /^did:[a-z0-9]+:[^/#\\s]+$/\nconst BINDING = /^[a-z][a-z0-9_]{0,31}$/\nconst IDENT = /^did:[a-z0-9]+:[^/#\\s]+#[a-z0-9][a-z0-9._-]{0,63}$/\nconst V2_HINT = 'needs manifest_version 2 (raise it in component.json)'\nconst V3_HINT = 'needs manifest_version 3 (raise it in component.json)'\nconst EVENT_PARAM_TYPES = ['string', 'number', 'boolean', 'object', 'entity']\nconst ITEM_KINDS = ['text', 'value', 'metric', 'bar', 'list', 'badge']\nconst ITEM_KEYS = ['kind', 'text', 'label', 'bind', 'by', 'format', 'limit']\nconst ACTION_COMMANDS = ['open_source', 'activate_editor', 'open_definition']\nconst INSPECTOR_KINDS = ['text', 'number', 'select', 'boolean', 'color']\n\n/** What another control declares (the `events` names of its component.json), `undefined` when it is not at hand:\n * whether a composite's slot children raise an event can be judged only then (otherwise the build judges it). */\nexport type AiwsCellEvents = (ident: string) => string[] | undefined\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === 'object' && !Array.isArray(v)\n}\n\n/** A file name of a source folder: a relative path whose parts are non-empty and do not start with `.` (Q23). */\nexport function isSourcePath(name: string): boolean {\n return name.length > 0 && encoder.encode(name).length <= 255 && !name.includes('\\0') && name.split('/').every((seg) => seg.length > 0 && !seg.startsWith('.'))\n}\n\nfunction configProps(configSchema: unknown): Record<string, unknown> {\n const props = isRecord(configSchema) ? configSchema.properties : undefined\n return isRecord(props) ? props : {}\n}\n\n/** `{{config.<key>}}` placeholders of a string: each names a property of `config_schema`. */\nfunction configPlaceholders(text: string, at: string, props: Record<string, unknown>, error: (message: string) => void): void {\n for (const m of text.matchAll(/\\{\\{([^}]*)\\}\\}/g)) {\n const inner = m[1].trim()\n if (!inner.startsWith('config.')) error(`${at}: only {{config.<key>}} may be used here`)\n else if (!(inner.slice(7) in props)) error(`${at}: {{${inner}}} names no property of config_schema`)\n }\n}\n\n/** A render control's `events` (Q26): ≤ 16 names `[a-z][a-z0-9_]{0,31}`, each `{ title?, description?, params? }` with\n * ≤ 16 params `{ type: string | number | boolean | object | entity, required?, description? }`. */\nfunction eventProblems(v: unknown, out: string[]): void {\n if (!isRecord(v)) { out.push('events must be an object { <name>: { title?, description?, params? } }'); return }\n if (Object.keys(v).length > 16) out.push('events: at most 16')\n for (const [name, raw] of Object.entries(v)) {\n const at = `events.${name}`\n if (!BINDING.test(name)) out.push(`${at}: an event name is [a-z][a-z0-9_]{0,31}`)\n if (!isRecord(raw)) { out.push(`${at} must be an object { title?, description?, params? }`); continue }\n for (const [k, x] of Object.entries(raw)) {\n if (k === 'title') { if (typeof x !== 'string' || x.length > 256) out.push(`${at}.title: at most 256 characters`) }\n else if (k === 'description') { if (typeof x !== 'string' || x.length > 4000) out.push(`${at}.description: at most 4000 characters`) }\n else if (k !== 'params') out.push(`${at}: unknown key ${k} (title, description, params)`)\n }\n if (raw.params === undefined) continue\n if (!isRecord(raw.params)) { out.push(`${at}.params must be an object { <param>: { type, required?, description? } }`); continue }\n if (Object.keys(raw.params).length > 16) out.push(`${at}.params: at most 16`)\n for (const [p, spec] of Object.entries(raw.params)) {\n const pat = `${at}.params.${p}`\n if (!BINDING.test(p)) out.push(`${pat}: a param name is [a-z][a-z0-9_]{0,31}`)\n if (!isRecord(spec)) { out.push(`${pat} must be an object { type, required?, description? }`); continue }\n for (const [k, x] of Object.entries(spec)) {\n if (k === 'type') { if (typeof x !== 'string' || !EVENT_PARAM_TYPES.includes(x)) out.push(`${pat}.type: ${EVENT_PARAM_TYPES.join(', ')}`) }\n else if (k === 'required') { if (typeof x !== 'boolean') out.push(`${pat}.required must be a boolean`) }\n else if (k === 'description') { if (typeof x !== 'string' || x.length > 1000) out.push(`${pat}.description: at most 1000 characters`) }\n else out.push(`${pat}: unknown key ${k} (type, required, description)`)\n }\n if (spec.type === undefined) out.push(`${pat}.type required`)\n }\n }\n}\n\nfunction schemaProblems(v: unknown, path: string, out: string[]): void {\n if (!v || typeof v !== 'object' || Array.isArray(v)) { out.push(`${path}: a schema is an object`); return }\n for (const [k, x] of Object.entries(v as Record<string, unknown>)) {\n if (!SCHEMA_KEYWORDS.includes(k)) { out.push(`${path}/${k}: keyword ${k} is outside the supported subset`); continue }\n if (k === 'properties' && x && typeof x === 'object') for (const [n, s] of Object.entries(x as Record<string, unknown>)) schemaProblems(s, `${path}/properties/${n}`, out)\n if (k === 'items') schemaProblems(x, `${path}/items`, out)\n }\n}\n\n/**\n * Check a declarative control's entry file the way `ext.build` does (store/src/ext.rs `check_declarative`): what the\n * interpreter draws (`layout`, `items` / `view.items`, `accent`, `actions`, `inspector`) and, with manifest_version 3,\n * the item `{ kind: \"button\", label, emit, params? }` raising an event of `events` (`EVENT_UNDECLARED` otherwise;\n * strings in `params` may hold `{{config.<key>}}`). Without `events` the emitted names are not judged.\n */\nexport function checkDeclarative(text: string, context: { bindings?: unknown; events?: string[]; configSchema?: unknown; manifestVersion?: number } = {}, file = 'declarative.json'): AiwsDiagnostic[] {\n const out: AiwsDiagnostic[] = []\n const error = (message: string, code?: string) => out.push({ file, severity: 'error', message, ...(code ? { code } : {}) })\n const warn = (message: string) => out.push({ file, severity: 'warning', message })\n let o: Record<string, unknown>\n try {\n const parsed = JSON.parse(text) as unknown\n if (!isRecord(parsed)) { error('a declarative definition is a JSON object'); return out }\n o = parsed\n } catch (e) {\n error(e instanceof Error ? e.message : String(e))\n return out\n }\n const bindings = isRecord(context.bindings) ? context.bindings : {}\n const props = configProps(context.configSchema)\n const strings = (v: unknown, at: string): void => {\n if (typeof v === 'string') configPlaceholders(v, at, props, error)\n else if (Array.isArray(v)) v.forEach((x, i) => strings(x, `${at}[${i}]`))\n else if (isRecord(v)) for (const [k, x] of Object.entries(v)) strings(x, `${at}.${k}`)\n }\n const button = (it: Record<string, unknown>, at: string) => {\n if (context.manifestVersion !== undefined && context.manifestVersion < 3) error(`${at}: a button ${V3_HINT}`)\n for (const k of Object.keys(it)) if (!['kind', 'label', 'emit', 'params'].includes(k)) warn(`${at}: key ${k} is ignored by the interpreter`)\n if (typeof it.label !== 'string' || !it.label) error(`${at}.label: the button's text (required)`)\n if (typeof it.emit !== 'string' || !it.emit) error(`${at}.emit: the event the button raises (required)`)\n else if (context.events && !context.events.includes(it.emit)) error(`${at}.emit ${it.emit}: not an event of component.json`, 'EVENT_UNDECLARED')\n if (it.params !== undefined) { if (isRecord(it.params)) strings(it.params, `${at}.params`); else error(`${at}.params must be an object`) }\n }\n const items = (list: unknown, at: string) => {\n if (list === undefined) return\n if (!Array.isArray(list)) { error(`${at} must be an array`); return }\n list.forEach((it, i) => {\n const iat = `${at}[${i}]`\n if (!isRecord(it)) { error(`${iat} must be an object`); return }\n if (it.kind === 'button') { button(it, iat); return }\n if (typeof it.kind !== 'string' || !ITEM_KINDS.includes(it.kind)) error(`${iat}.kind ${JSON.stringify(it.kind)}: one of ${[...ITEM_KINDS, 'button'].join(', ')}`)\n for (const k of Object.keys(it)) if (!ITEM_KEYS.includes(k)) warn(`${iat}: key ${k} is ignored by the interpreter`)\n if (it.format !== undefined && !['text', 'number', 'percent', 'currency'].includes(it.format as string)) error(`${iat}.format ${JSON.stringify(it.format)}: text, number, percent or currency`)\n if (typeof it.bind === 'string' && it.bind.includes('.')) {\n const prefix = it.bind.slice(0, it.bind.indexOf('.'))\n if (prefix !== 'props' && !(prefix in bindings)) warn(`${iat}.bind ${JSON.stringify(it.bind)}: ${prefix} is not a declared binding, so it reads the field ${JSON.stringify(it.bind)} of the main source`)\n }\n })\n }\n for (const [k, v] of Object.entries(o)) {\n if (k === 'layout') { if (v !== 'stack' && v !== 'row') error('layout: stack or row') }\n else if (k === 'items') items(v, 'items')\n else if (k === 'view') items(isRecord(v) ? v.items : undefined, 'view.items')\n else if (k === 'accent') { if (typeof v !== 'string') error('accent must be a colour string') }\n else if (k === 'actions') {\n (Array.isArray(v) ? v : []).forEach((a: unknown, i) => {\n const r = isRecord(a) ? a : {}\n if (typeof r.command !== 'string' || !ACTION_COMMANDS.includes(r.command)) error(`actions[${i}].command: one of ${ACTION_COMMANDS.join(', ')}`)\n if (typeof r.id !== 'string' || typeof r.label !== 'string') error(`actions[${i}] needs id and label`)\n })\n } else if (k === 'inspector') {\n (Array.isArray(v) ? v : []).forEach((f: unknown, i) => {\n const r = isRecord(f) ? f : {}\n if (typeof r.kind !== 'string' || !INSPECTOR_KINDS.includes(r.kind)) error(`inspector[${i}].kind: one of ${INSPECTOR_KINDS.join(', ')}`)\n if (typeof r.key !== 'string' || typeof r.label !== 'string') error(`inspector[${i}] needs key and label`)\n })\n } else warn(`key ${k} is not part of the declarative vocabulary`)\n }\n if (o.items === undefined && o.view === undefined) warn('no items: the control draws nothing')\n return out\n}\n\n/** A composite's `composition.json` (K3): what the slots accept and their counts, the layout, the Chrome and the\n * events it re-raises from its children (P2). */\nexport interface AiwsComposition {\n layout: { algorithm: 'stack' | 'fixed' | 'grid'; direction?: 'column' | 'row'; spacing?: number | string; padding?: number | string | { t?: number; r?: number; b?: number; l?: number }; columns?: number; gap?: number | string }\n slots: Record<string, { accepts?: string[]; min?: number; max?: number; placement?: 'stack' | 'top' | 'bottom' | 'free'; title?: string }>\n chrome?: { background?: string; radius?: number | string; border?: string; title?: { text: string; slot?: string }; empty?: string }\n events?: Record<string, { from: { slot: string; event: string }; title?: string; description?: string }>\n}\n\n/**\n * Check a `composition.json` the way `ext.build` does (store/src/ext.rs `check_composition`): `layout` is `stack`,\n * `fixed` or `grid` (`columns` 1…12, `gap`; a grid fills its cells with the slots' children in slot order, so its slots\n * take placement `stack` only), at most 16 slots named `[a-z][a-z0-9_]{0,31}` accepting `cell:<ident>`, a view type or\n * `container`, the Chrome's strings, `{{config.<key>}}` naming properties of `config_schema`, and `events`\n * (manifest_version 3) re-raising an event of a slot's children: `EVENT_UNDECLARED` when no `cell:<ident>` of that slot\n * declares it, judged as far as `cellEvents` knows those controls.\n */\nexport function checkComposition(text: string, configSchema?: unknown, file = AIWS_COMPOSITION_FILE, context: { manifestVersion?: number; cellEvents?: AiwsCellEvents } = {}): AiwsDiagnostic[] {\n const out: AiwsDiagnostic[] = []\n const error = (message: string, code?: string) => out.push({ file, severity: 'error', message, ...(code ? { code } : {}) })\n let o: Record<string, unknown>\n try {\n const parsed = JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { error('a composition is a JSON object { layout, slots, chrome?, events? }'); return out }\n o = parsed as Record<string, unknown>\n } catch (e) {\n error(e instanceof Error ? e.message : String(e))\n return out\n }\n const props = configProps(configSchema)\n const placeholders = (t: string, at: string) => configPlaceholders(t, at, props, error)\n const dimension = (v: unknown, at: string, max: number) => {\n if (typeof v === 'number' && v >= 0 && v <= max) return\n if (typeof v === 'string' && /^\\s*\\{\\{.*\\}\\}\\s*$/.test(v)) { placeholders(v, at); return }\n error(`${at}: a number in [0, ${max}] or {{config.<key>}}`)\n }\n for (const k of Object.keys(o)) {\n if (!['layout', 'slots', 'chrome', 'events'].includes(k)) error(`unknown key ${k} (a composition says layout, slots, chrome and events)`)\n }\n const layout = o.layout as Record<string, unknown> | undefined\n let algorithm = 'stack'\n if (!layout || typeof layout !== 'object') error('layout { algorithm: stack | fixed | grid } required')\n else {\n if (layout.algorithm === 'stack' || layout.algorithm === 'fixed' || layout.algorithm === 'grid') algorithm = layout.algorithm\n else error(`layout.algorithm ${JSON.stringify(layout.algorithm)}: stack, fixed or grid (the algorithms the host ships)`)\n for (const [k, v] of Object.entries(layout)) {\n if (k === 'algorithm') continue\n if ((k === 'direction' || k === 'spacing') && algorithm !== 'stack') { error(`layout.${k} belongs to the stack layout`); continue }\n if ((k === 'columns' || k === 'gap') && algorithm !== 'grid') { error(`layout.${k} belongs to the grid layout`); continue }\n if (k === 'direction') { if (v !== 'column' && v !== 'row') error('layout.direction: column or row') }\n else if (k === 'spacing') dimension(v, 'layout.spacing', 2000)\n else if (k === 'columns') { if (!Number.isInteger(v) || (v as number) < 1 || (v as number) > 12) error('layout.columns: an integer in [1, 12]') }\n else if (k === 'gap') dimension(v, 'layout.gap', 2000)\n else if (k === 'padding') {\n if (v && typeof v === 'object' && !Array.isArray(v)) for (const [side, n] of Object.entries(v)) { if (!['t', 'r', 'b', 'l'].includes(side)) error(`layout.padding.${side}: t, r, b or l`); dimension(n, `layout.padding.${side}`, 2000) }\n else dimension(v, 'layout.padding', 2000)\n } else error(`layout: unknown key ${k}`)\n }\n if (algorithm === 'grid' && layout.columns === undefined) error('layout.columns (1…12) required: the cells of a grid row')\n }\n const slots = (o.slots && typeof o.slots === 'object' && !Array.isArray(o.slots) ? o.slots : null) as Record<string, unknown> | null\n if (!slots) error('slots { <name>: { accepts?, min?, max?, placement? } } required')\n else {\n if (Object.keys(slots).length > 16) error('at most 16 slots')\n for (const [name, raw] of Object.entries(slots)) {\n const at = `slots.${name}`\n if (!BINDING.test(name)) error(`${at}: a slot name is [a-z][a-z0-9_]{0,31}`)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { error(`${at} must be an object`); continue }\n const slot = raw as Record<string, unknown>\n for (const [k, v] of Object.entries(slot)) {\n if (k === 'accepts') {\n if (!Array.isArray(v) || v.length === 0 || v.length > 32) { error(`${at}.accepts: 1…32 entries (cell:<ident>, a view type, container)`); continue }\n for (const a of v) {\n if (typeof a === 'string' && a.startsWith('cell:')) { if (!IDENT.test(a.slice(5)) || encoder.encode(a.slice(5)).length > 128) error(`${at}.accepts ${JSON.stringify(a)}: cell:<author_did>#<name>`) }\n else if (a !== 'container' && !(typeof a === 'string' && NAME.test(a))) error(`${at}.accepts ${JSON.stringify(a)}: cell:<ident>, a view type or container`)\n }\n } else if (k === 'min') { if (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 64) error(`${at}.min: an integer in [0, 64]`) }\n else if (k === 'max') { if (!Number.isInteger(v) || (v as number) < 1 || (v as number) > 1000) error(`${at}.max: an integer in [1, 1000]`) }\n else if (k === 'placement') {\n if (v !== 'stack' && v !== 'top' && v !== 'bottom' && v !== 'free') error(`${at}.placement: stack, top, bottom or free`)\n else if (algorithm === 'fixed' && v !== 'free') error(`${at}.placement: a fixed layout keeps every child where it is (free)`)\n else if (algorithm === 'grid' && v !== 'stack') error(`${at}.placement: a grid fills its cells with the slots' children in slot order (stack)`)\n } else if (k === 'title') { if (typeof v !== 'string' || v.length > 256) error(`${at}.title: at most 256 characters`) }\n else error(`${at}: unknown key ${k}`)\n }\n if (Number.isInteger(slot.min) && Number.isInteger(slot.max) && (slot.min as number) > (slot.max as number)) error(`${at}: min exceeds max`)\n }\n }\n const chrome = o.chrome\n if (chrome !== undefined) {\n if (!chrome || typeof chrome !== 'object' || Array.isArray(chrome)) error('chrome must be an object')\n else for (const [k, v] of Object.entries(chrome as Record<string, unknown>)) {\n const at = `chrome.${k}`\n if (k === 'background' || k === 'border') { if (typeof v === 'string' && v.length <= 64) placeholders(v, at); else error(`${at}: a colour (≤ 64 characters) or {{config.<key>}}`) }\n else if (k === 'radius') dimension(v, at, 200)\n else if (k === 'empty') { if (typeof v === 'string' && v.length <= 1000) placeholders(v, at); else error(`${at}: a text of at most 1000 characters`) }\n else if (k === 'title') {\n const t = v as Record<string, unknown> | null\n if (!t || typeof t !== 'object' || Array.isArray(t)) { error(`${at}: { text, slot? }`); continue }\n for (const [tk, tv] of Object.entries(t)) {\n if (tk === 'text') { if (typeof tv === 'string' && tv.length <= 256) placeholders(tv, 'chrome.title.text'); else error('chrome.title.text: at most 256 characters') }\n else if (tk === 'slot') { if (typeof tv !== 'string' || !slots || !(tv in slots)) error(`chrome.title.slot ${JSON.stringify(tv)}: a slot of this composition`) }\n else error(`chrome.title: unknown key ${tk}`)\n }\n if (typeof t.text !== 'string') error('chrome.title.text required')\n } else error(`chrome: unknown key ${k} (background, radius, border, title, empty)`)\n }\n }\n if (o.events !== undefined) {\n if (context.manifestVersion !== undefined && context.manifestVersion < 3) error(`events ${V3_HINT}`)\n if (!isRecord(o.events)) error('events must be an object { <name>: { from: { slot, event }, title?, description? } }')\n else {\n if (Object.keys(o.events).length > 16) error('events: at most 16')\n for (const [name, raw] of Object.entries(o.events)) {\n const at = `events.${name}`\n if (!BINDING.test(name)) error(`${at}: an event name is [a-z][a-z0-9_]{0,31}`)\n if (!isRecord(raw)) { error(`${at} must be an object { from: { slot, event }, title?, description? }`); continue }\n for (const [k, v] of Object.entries(raw)) {\n if (k === 'title') { if (typeof v !== 'string' || v.length > 256) error(`${at}.title: at most 256 characters`) }\n else if (k === 'description') { if (typeof v !== 'string' || v.length > 4000) error(`${at}.description: at most 4000 characters`) }\n else if (k !== 'from') error(`${at}: unknown key ${k} (from, title, description)`)\n }\n const from = raw.from\n if (!isRecord(from)) { error(`${at}.from { slot, event } required: the child event it re-raises`); continue }\n for (const k of Object.keys(from)) if (k !== 'slot' && k !== 'event') error(`${at}.from: unknown key ${k} (slot, event)`)\n const event = typeof from.event === 'string' && BINDING.test(from.event) ? from.event : undefined\n if (!event) error(`${at}.from.event: an event name [a-z][a-z0-9_]{0,31}`)\n const slot = typeof from.slot === 'string' && slots ? slots[from.slot] : undefined\n if (!isRecord(slot)) { error(`${at}.from.slot ${JSON.stringify(from.slot)}: a slot of this composition`); continue }\n if (!event) continue\n const cells = (Array.isArray(slot.accepts) ? slot.accepts : []).filter((a): a is string => typeof a === 'string' && a.startsWith('cell:')).map((a) => a.slice(5))\n if (cells.length === 0) { error(`${at}: slot ${from.slot} accepts no cell:<ident>, so no control there declares ${event}`, 'EVENT_UNDECLARED'); continue }\n const declared = cells.map((ident) => context.cellEvents?.(ident))\n if (declared.every((names) => names !== undefined && !names.includes(event))) error(`${at}: no control slot ${from.slot} accepts (${cells.join(', ')}) declares the event ${event}`, 'EVENT_UNDECLARED')\n }\n }\n }\n return out\n}\n\n/**\n * Check a `component.json` text against the files of its directory (and its declarative file or composition when\n * `readText` gives the entry's text; `cellEvents` says what other controls declare, for a composite's re-raised\n * events). Errors make a build fail; warnings do not.\n */\nexport function checkComponent(text: string, fileNames: string[], readText?: (name: string) => string | undefined, cellEvents?: AiwsCellEvents): AiwsDiagnostic[] {\n const out: AiwsDiagnostic[] = []\n const f = AIWS_COMPONENT_FILE\n const error = (message: string) => out.push({ file: f, severity: 'error', message })\n let c: Record<string, unknown>\n try {\n const parsed = JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { error('must be a JSON object'); return out }\n c = parsed as Record<string, unknown>\n } catch (e) {\n error(e instanceof Error ? e.message : String(e))\n return out\n }\n for (const k of Object.keys(c)) if (!COMPONENT_KEYS.includes(k)) error(`unknown key ${k}`)\n const mv = c.manifest_version\n const version = typeof mv === 'number' && Number.isInteger(mv) && mv >= 1 ? mv : 0\n if (!version) error(`manifest_version (1…${AIWS_MANIFEST_VERSION}) required`)\n else if (version > AIWS_MANIFEST_VERSION) error(`manifest_version ${mv} is newer than this client reads (${AIWS_MANIFEST_VERSION})`)\n const before3 = version > 0 && version < 3\n const ident = c.ident as Record<string, unknown> | undefined\n let self = ''\n if (!ident || typeof ident !== 'object') error('ident { author_did, name } required')\n else {\n if (typeof ident.author_did !== 'string' || !DID.test(ident.author_did)) error('ident.author_did must be a DID (did:<method>:<id>)')\n if (typeof ident.name !== 'string' || !NAME.test(ident.name)) error('ident.name must be [a-z0-9][a-z0-9._-]{0,63}')\n if (typeof ident.author_did === 'string' && typeof ident.name === 'string') {\n self = `${ident.author_did}#${ident.name}`\n if (encoder.encode(self).length > 128) error('an identity is at most 128 bytes')\n }\n }\n const composite = c.kind === 'composite'\n if (c.kind !== 'declarative' && c.kind !== 'html' && !composite) error('kind must be declarative, html or composite')\n if (composite && version === 1) error(`kind composite ${V2_HINT}`)\n if (composite) for (const k of ['accepts', 'allow_no_source']) if (c[k] !== undefined) error(`${k}: a composite is a container of Blocks, not a Cell showing data`)\n if (typeof c.title !== 'string' || !c.title || c.title.length > 256) error('title: 1…256 characters')\n if (c.config_schema !== undefined) { const p: string[] = []; schemaProblems(c.config_schema, 'config_schema', p); p.forEach(error) }\n if (c.bindings !== undefined) {\n if (!c.bindings || typeof c.bindings !== 'object') error('bindings must be an object')\n else for (const n of Object.keys(c.bindings as object)) if (!BINDING.test(n) || n === 'props') error(`binding name ${n}: [a-z][a-z0-9_]{0,31}, not props`)\n }\n if (c.deps !== undefined) {\n if (!Array.isArray(c.deps) || c.deps.length > 32) error('deps: at most 32 identities <author_did>#<name>')\n else if (c.deps.length > 0 && version === 1) error(`deps ${V2_HINT}`)\n else {\n const seen = new Set<string>()\n for (const d of c.deps) {\n if (typeof d !== 'string' || !IDENT.test(d)) error(`deps: ${JSON.stringify(d)} is not an identity <author_did>#<name>`)\n else if (d === self) error('deps: a control cannot depend on itself')\n else if (seen.has(d)) error(`deps lists ${d} twice`)\n seen.add(String(d))\n }\n }\n }\n let events: string[] = []\n if (c.events !== undefined) {\n if (composite) error('events: a composite declares its events in composition.json (events.<name>.from re-raises an event of a child)')\n else if (before3) error(`events ${V3_HINT}`)\n else { const p: string[] = []; eventProblems(c.events, p); p.forEach(error) }\n if (!composite && isRecord(c.events)) events = Object.keys(c.events)\n }\n const has = (n: unknown) => typeof n === 'string' && fileNames.includes(n)\n const named = new Set([f])\n if (c.kind === 'html') {\n const e = c.entry as Record<string, unknown> | undefined\n if (!e || typeof e !== 'object' || typeof e.html !== 'string') error('entry must be { html, css?, js? }')\n else for (const [k, n] of Object.entries(e)) { if (!has(n)) error(`entry.${k} ${JSON.stringify(n)} is not in the directory`); else named.add(String(n)) }\n if (c.host_api !== undefined && c.host_api !== 2 && c.host_api !== 3) error('host_api: the HTML Block host speaks API 2 and 3')\n else if (c.host_api === 3 && before3) error(`host_api 3 ${V3_HINT}`)\n if (events.length > 0 && c.host_api !== 3) out.push({ file: f, severity: 'warning', message: 'events: an HTML control raises them with aiws.emit, which is host API 3 (set host_api to 3)' })\n } else if (c.kind === 'declarative' || composite) {\n if (!has(c.entry)) error(`entry ${JSON.stringify(c.entry)} is not in the directory`)\n else {\n named.add(String(c.entry))\n const entryText = readText?.(String(c.entry))\n const manifestVersion = version || undefined\n if (entryText !== undefined && composite) out.push(...checkComposition(entryText, c.config_schema, String(c.entry), { manifestVersion, cellEvents }))\n else if (entryText !== undefined) out.push(...checkDeclarative(entryText, { bindings: c.bindings, events, configSchema: c.config_schema, manifestVersion }, String(c.entry)))\n }\n if (composite && c.host_api !== undefined) error('host_api: a composite runs no code of its own (its layout and chrome are the host\\'s)')\n if (!composite && c.host_api !== undefined && c.host_api !== AIWS_DECLARATIVE_API_VERSION) error(`host_api: the declarative interpreter is version ${AIWS_DECLARATIVE_API_VERSION}`)\n }\n for (const a of Array.isArray(c.assets) ? c.assets : []) { if (!has(a)) error(`asset ${JSON.stringify(a)} is not in the directory`); else named.add(String(a)) }\n if (c.agent !== undefined) { if (!has(c.agent)) error(`agent ${JSON.stringify(c.agent)} is not in the directory`); else named.add(String(c.agent)) }\n for (const n of fileNames) {\n if (!isSourcePath(n)) out.push({ file: n, severity: 'error', message: 'a file of a source directory: a relative path whose parts do not start with \\'.\\'' })\n else if (!named.has(n)) out.push({ file: n, severity: 'warning', message: 'not named by component.json: kept in the source snapshot only' })\n }\n return out\n}\n\n/** The identities a composition's slots accept as `cell:<ident>`. */\nexport function slotCells(composition: AiwsComposition): string[] {\n const out = new Set<string>()\n for (const slot of Object.values(composition.slots ?? {})) for (const a of slot.accepts ?? []) if (a.startsWith('cell:')) out.add(a.slice(5))\n return [...out].sort()\n}\n\n// ---- bundles (exports, the `aiws` sub-package of a PIKG)\n\n/** Read an AIWS manifest of any supported version as the current one (Q19); a newer one is refused. */\nexport function compatManifest(value: unknown): AiwsManifest {\n if (!value || typeof value !== 'object') throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'must be a JSON object' }])\n const m = value as Record<string, unknown>\n const version = m.manifest_version\n if (typeof version !== 'number' || version < 1) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'manifest_version required' }])\n if (version > AIWS_MANIFEST_VERSION) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: `manifest_version ${version} needs a newer client (this one reads ${AIWS_MANIFEST_VERSION})` }])\n if (m.purpose !== 'aiws') throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'purpose must be aiws' }])\n if (!Array.isArray(m.controls)) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'controls must be an array' }])\n return { manifest_version: version, purpose: 'aiws', host_api: (m.host_api as Record<string, number>) ?? {}, controls: m.controls as AiwsManifestControl[], workspace_templates: Array.isArray(m.workspace_templates) ? m.workspace_templates : [] }\n}\n\nconst TEMPLATE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/\n\n/** Where a Workspace template's files sit in a bundle: `templates/<id>/` (`snapshot.json`, `objects/`, `chunks/`). */\nexport function templateDir(id: string): string {\n return `templates/${id}/`\n}\n\n/** The content digest of a Workspace template (its manifest `digest`): the files under `templates/<id>/`, named\n * relative to that folder, digested as a control's. */\nexport async function aiwsTemplateDigest(files: Iterable<[string, Uint8Array]>, id: string): Promise<string> {\n const dir = templateDir(id)\n const own: [string, Uint8Array][] = []\n for (const [path, bytes] of files) if (path.startsWith(dir)) own.push([path.slice(dir.length), bytes])\n return aiwsContentDigest(own)\n}\n\n/** The shape of a `workspace_templates` item (schemas/template.schema.json); `controls` are the manifest's identities. */\nfunction templateProblems(t: unknown, controls: Set<string>): string[] {\n if (!isRecord(t)) return ['a template is an object { id, title, snapshot, digest, requires, description?, params?, reset? }']\n const out: string[] = []\n for (const k of Object.keys(t)) if (!['id', 'title', 'description', 'snapshot', 'digest', 'requires', 'params', 'reset'].includes(k)) out.push(`unknown key ${k}`)\n if (typeof t.id !== 'string' || !TEMPLATE_ID.test(t.id)) out.push('id: [a-z0-9][a-z0-9-]{0,63}')\n else if (t.snapshot !== `${templateDir(t.id)}snapshot.json`) out.push(`snapshot must be ${templateDir(t.id)}snapshot.json`)\n if (typeof t.title !== 'string' || !t.title || t.title.length > 256) out.push('title: 1…256 characters')\n if (t.description !== undefined && (typeof t.description !== 'string' || t.description.length > 4000)) out.push('description: at most 4000 characters')\n if (typeof t.digest !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(t.digest)) out.push('digest: sha256:<64 hex digits>')\n const requires = t.requires\n if (!isRecord(requires)) out.push('requires { host_api?, controls } required')\n else {\n for (const k of Object.keys(requires)) if (k !== 'host_api' && k !== 'controls') out.push(`requires: unknown key ${k}`)\n if (requires.host_api !== undefined) {\n if (!isRecord(requires.host_api)) out.push('requires.host_api must be an object { html?, declarative? }')\n else for (const [k, v] of Object.entries(requires.host_api)) if ((k !== 'html' && k !== 'declarative') || !Number.isInteger(v) || (v as number) < 1) out.push(`requires.host_api.${k}: html or declarative, a positive integer`)\n }\n if (!Array.isArray(requires.controls) || requires.controls.length > 256) out.push('requires.controls: at most 256 identities')\n else {\n const seen = new Set<unknown>()\n for (const ident of requires.controls) {\n if (typeof ident !== 'string' || !controls.has(ident)) out.push(`requires.controls: ${JSON.stringify(ident)} is not a control of this manifest`)\n else if (seen.has(ident)) out.push(`requires.controls lists ${ident} twice`)\n seen.add(ident)\n }\n }\n }\n if (t.params !== undefined) {\n if (!isRecord(t.params) || Object.keys(t.params).length > 32) out.push('params: an object of at most 32 { type, title?, default? }')\n else for (const [name, p] of Object.entries(t.params)) {\n const at = `params.${name}`\n if (!BINDING.test(name)) out.push(`${at}: a param name is [a-z][a-z0-9_]{0,31}`)\n if (!isRecord(p)) { out.push(`${at} must be an object { type, title?, default? }`); continue }\n for (const [k, v] of Object.entries(p)) {\n if (k === 'type') { if (v !== 'string' && v !== 'number' && v !== 'boolean') out.push(`${at}.type: string, number or boolean`) }\n else if (k === 'title') { if (typeof v !== 'string' || v.length > 256) out.push(`${at}.title: at most 256 characters`) }\n else if (k === 'default') { if (!['string', 'number', 'boolean'].includes(typeof v)) out.push(`${at}.default: a string, number or boolean`) }\n else out.push(`${at}: unknown key ${k} (type, title, default)`)\n }\n if (p.type === undefined) out.push(`${at}.type required`)\n }\n }\n if (t.reset !== undefined) {\n const tables = isRecord(t.reset) ? t.reset.tables : undefined\n if (!isRecord(t.reset) || Object.keys(t.reset).some((k) => k !== 'tables')) out.push('reset: { tables }')\n else if (tables !== undefined && (!Array.isArray(tables) || tables.length > 64 || new Set(tables).size !== tables.length || tables.some((x) => typeof x !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(x)))) out.push('reset.tables: at most 64 distinct table ids')\n }\n return out\n}\n\n/** Verify a bundle the way an installer does: manifest, each control's digest and component.json, each Workspace\n * template's shape, snapshot and digest, no stray files. */\nexport async function verifyBundle(files: Map<string, Uint8Array>): Promise<{ manifest: AiwsManifest; diagnostics: AiwsDiagnostic[] }> {\n const raw = files.get(AIWS_MANIFEST_FILE)\n if (!raw) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'missing' }])\n let parsed: unknown\n try { parsed = JSON.parse(decoder.decode(raw)) } catch (e) { throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: String(e) }]) }\n const manifest = compatManifest(parsed)\n const diagnostics: AiwsDiagnostic[] = []\n const templates = manifest.workspace_templates\n if (templates.length > 0 && manifest.manifest_version < 3) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `Workspace templates need manifest_version 3 (raise it in ${AIWS_MANIFEST_FILE})` })\n if (templates.length > 32) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'at most 32 Workspace templates' })\n if (manifest.controls.length === 0 && templates.length === 0) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'lists no control' })\n // what the bundle's controls declare: a composite's re-raised events are judged against them\n const declared = new Map<string, string[]>()\n for (const c of manifest.controls) {\n const component = typeof c.dir === 'string' ? files.get(`${c.dir}${AIWS_COMPONENT_FILE}`) : undefined\n try {\n const comp = component ? JSON.parse(decoder.decode(component)) as unknown : undefined\n if (isRecord(comp)) declared.set(c.ident, isRecord(comp.events) ? Object.keys(comp.events) : [])\n } catch { /* reported below */ }\n }\n const dirs = new Set<string>()\n for (const c of manifest.controls) {\n if (typeof c.dir !== 'string' || !/^controls\\/[a-z0-9][a-z0-9._-]{0,70}\\/$/.test(c.dir) || dirs.has(c.dir)) { diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `control ${c.ident}: bad or repeated dir` }); continue }\n dirs.add(c.dir)\n const own: [string, Uint8Array][] = [...files].filter(([p]) => p.startsWith(c.dir)).map(([p, b]) => [p.slice(c.dir.length), b])\n if (await aiwsContentDigest(own) !== c.digest) diagnostics.push({ file: c.dir, severity: 'error', message: 'the files do not match the manifest digest' })\n const component = own.find(([n]) => n === AIWS_COMPONENT_FILE)\n if (!component) { diagnostics.push({ file: `${c.dir}${AIWS_COMPONENT_FILE}`, severity: 'error', message: 'missing' }); continue }\n const text = (name: string) => { const hit = own.find(([n]) => n === name); return hit ? decoder.decode(hit[1]) : undefined }\n for (const d of checkComponent(decoder.decode(component[1]), own.map(([n]) => n), text, (ident) => declared.get(ident))) diagnostics.push({ ...d, file: `${c.dir}${d.file}` })\n try {\n const comp = JSON.parse(decoder.decode(component[1])) as { ident?: { author_did?: string; name?: string }; kind?: string; deps?: string[] }\n if (`${comp.ident?.author_did}#${comp.ident?.name}` !== c.ident || comp.kind !== c.kind) diagnostics.push({ file: c.dir, severity: 'error', message: 'ident and kind must match its component.json' })\n if (JSON.stringify([...(comp.deps ?? [])].sort()) !== JSON.stringify([...(c.deps ?? [])].sort())) diagnostics.push({ file: c.dir, severity: 'error', message: 'deps must match its component.json' })\n } catch { /* reported above */ }\n }\n // what a control builds on travels with it (P1): every dependency is another control of the bundle\n const idents = new Set(manifest.controls.map((c) => c.ident))\n for (const c of manifest.controls) for (const d of c.deps ?? []) if (!idents.has(d)) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `${c.ident} depends on ${d}, which the bundle does not carry` })\n // a template is a snapshot under templates/<id>/ needing controls of the same manifest (Q32)\n for (const [i, t] of templates.entries()) {\n const label = isRecord(t) && typeof t.id === 'string' ? `template ${t.id}` : `workspace_templates[${i}]`\n for (const p of templateProblems(t, idents)) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `${label}: ${p}` })\n if (!isRecord(t) || typeof t.id !== 'string' || !TEMPLATE_ID.test(t.id)) continue\n const dir = templateDir(t.id)\n if (dirs.has(dir)) { diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `${label} is listed twice` }); continue }\n dirs.add(dir)\n const snapshot = files.get(`${dir}snapshot.json`)\n let format: unknown\n try { format = snapshot ? (JSON.parse(decoder.decode(snapshot)) as { format?: unknown }).format : undefined } catch { format = undefined }\n if (!snapshot) diagnostics.push({ file: `${dir}snapshot.json`, severity: 'error', message: 'missing' })\n else if (format !== AIWS_TEMPLATE_FORMAT) diagnostics.push({ file: `${dir}snapshot.json`, severity: 'error', message: `not a template snapshot (format ${AIWS_TEMPLATE_FORMAT})` })\n if (await aiwsTemplateDigest(files, t.id) !== t.digest) diagnostics.push({ file: dir, severity: 'error', message: 'the files do not match the template digest' })\n }\n for (const p of files.keys()) if (p !== AIWS_MANIFEST_FILE && ![...dirs].some((d) => p.startsWith(d))) diagnostics.push({ file: p, severity: 'error', message: 'belongs to no control or template of the manifest' })\n return { manifest, diagnostics }\n}\n\n/** The bundle of Workspace definitions (`ext.export`): the manifest plus every file's bytes. */\nexport async function exportBundle(client: AiwsExtRpc, workspaceId: string, entityIds: string[], fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<AiwsBundle & { controls: Record<string, unknown>[] }> {\n const r = await client.extExport(workspaceId, entityIds, 'package')\n const files = new Map<string, Uint8Array>()\n files.set(AIWS_MANIFEST_FILE, encoder.encode(`${JSON.stringify(r.manifest, null, 2)}\\n`))\n for (const f of r.files) files.set(f.path, f.text !== undefined ? encoder.encode(f.text) : await fetchAsset(workspaceId, String(f.obj_id)))\n return { manifest: compatManifest(r.manifest), files, controls: r.controls }\n}\n\n// ---- the home folder over NFSP\n\n/** The entry `name` of a folder, found with a filtered listing (no request fails for a missing name). */\nasync function child(nfsp: NfspClient, folder: WireRef | string, name: string) {\n const glob = /[*?[\\]\\\\]/.test(name) ? undefined : name\n const page = await nfsp.list(typeof folder === 'string' ? folder : { ref: folder }, { limit: glob ? 10 : 1000, ...(glob ? { filter: { name_glob: glob } } : {}) }, ['base', 'ident'])\n return page.entries.find((e) => e.name === name)\n}\n\n/** Make sure a folder exists, creating each missing level below the realm root (`/home`); answers its ref. Levels\n * are looked up by listing their parent, so a missing one is not a failed request. */\nexport async function ensureFolder(nfsp: NfspClient, path: string): Promise<WireRef> {\n const parts = path.split('/').filter(Boolean)\n if (parts.length === 0) throw new Error(`not a folder path: ${path}`)\n let ref = (await nfsp.stat(`/${parts[0]}`)).ref\n for (const name of parts.slice(1)) {\n const hit = await child(nfsp, ref, name)\n if (hit && hit.target.kind !== 'dir') throw new AiwsSourceError([{ file: name, severity: 'error', message: `${name} in ${path} is not a folder` }])\n ref = hit ? hit.target.ref : (await nfsp.mkdir({ ref }, name)).ref\n }\n return ref\n}\n\n/** A folder's ref, or null when it (or a level above it) does not exist — found without failed requests. */\nexport async function findFolder(nfsp: NfspClient, path: string): Promise<WireRef | null> {\n const parts = path.split('/').filter(Boolean)\n if (parts.length === 0) return null\n let ref = (await nfsp.stat(`/${parts[0]}`)).ref\n for (const name of parts.slice(1)) {\n const hit = await child(nfsp, ref, name)\n if (!hit || hit.target.kind !== 'dir') return null\n ref = hit.target.ref\n }\n return ref\n}\n\n/** Whether a folder holds a control source (its component.json). */\nexport async function hasControlSource(nfsp: NfspClient, dir: string): Promise<boolean> {\n const ref = await findFolder(nfsp, dir)\n return ref !== null && (await child(nfsp, ref, AIWS_COMPONENT_FILE)) !== undefined\n}\n\n/** Write one file into a folder (replacing it). */\nexport async function writeHomeFile(nfsp: NfspClient, dir: string | WireRef, name: string, bytes: Uint8Array): Promise<void> {\n const ref = typeof dir === 'string' ? await ensureFolder(nfsp, dir) : dir\n await nfsp.uploadFile(ref, name, bytes, { overwrite: true })\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\n/** The files of a control's source folder, sub-folders included (names are relative paths, Q23); dot files and dot\n * folders are the client's own and skipped. */\nexport async function collectSources(nfsp: NfspClient, dir: string): Promise<AiwsSourceFile[]> {\n const out: AiwsSourceFile[] = []\n const problems: AiwsDiagnostic[] = []\n const walk = async (folder: string | WireRef, prefix: string, depth: number): Promise<void> => {\n let cursor: string | undefined\n do {\n const page = await nfsp.list(typeof folder === 'string' ? folder : { ref: folder }, { limit: 500, ...(cursor ? { cursor } : {}) }, ['base', 'ident'])\n for (const e of page.entries) {\n if (e.name.startsWith('.')) continue\n const name = `${prefix}${e.name}`\n if (e.target.kind === 'dir') {\n if (depth >= 8) problems.push({ file: name, severity: 'error', message: 'sub-folders nest at most 8 levels' })\n else await walk(e.target.ref, `${name}/`, depth + 1)\n continue\n }\n if (e.target.kind !== 'file') { problems.push({ file: name, severity: 'error', message: 'only files and folders belong to a control source' }); continue }\n const ref = e.target.ref\n const objId = ref.type === 'object' ? ref.obj_id : typeof e.target.attrs?.obj_id === 'string' ? e.target.attrs.obj_id : undefined\n out.push({\n name,\n ...(objId ? { obj_id: objId } : {}),\n ...(ref.type === 'live' ? { node_id: ref.node_id } : {}),\n ...(typeof e.target.attrs?.etag === 'string' ? { etag: e.target.attrs.etag } : {}),\n ...(typeof e.target.attrs?.size === 'number' ? { size: e.target.attrs.size } : {}),\n })\n }\n cursor = page.truncated ? page.next_cursor : undefined\n } while (cursor)\n }\n await walk(dir, '', 0)\n if (out.length === 0) problems.push({ file: '', severity: 'error', message: `${dir} holds no files` })\n if (out.length > AIWS_MAX_SOURCE_FILES) problems.push({ file: '', severity: 'error', message: `a control holds at most ${AIWS_MAX_SOURCE_FILES} files` })\n if (problems.some((p) => p.severity === 'error')) throw new AiwsSourceError(problems)\n return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n}\n\n/** Write a source file whose name may be a relative path (its sub-folders are created). */\nexport async function writeSourceFile(nfsp: NfspClient, dir: string, name: string, bytes: Uint8Array): Promise<void> {\n const cut = name.lastIndexOf('/')\n await writeHomeFile(nfsp, cut < 0 ? dir : joinPath(dir, name.slice(0, cut)), cut < 0 ? name : name.slice(cut + 1), bytes)\n}\n\n/** The content digest of a home folder's sources (what `ext.export` answers as a control's `digest`). */\nexport async function sourcesDigest(nfsp: NfspClient, files: AiwsSourceFile[]): Promise<string> {\n const pairs: [string, Uint8Array][] = []\n for (const f of files) {\n if (!f.node_id) throw new AiwsSourceError([{ file: f.name, severity: 'error', message: 'the file service did not name this file' }])\n pairs.push([f.name, new Uint8Array(await (await nfsp.readFile(f.node_id)).arrayBuffer())])\n }\n return aiwsContentDigest(pairs)\n}\n\n/**\n * Does the home folder of a definition hold changes that were not built (P0 遗留 L3)? Compares its sources with the\n * Workspace snapshot (`ext.export { purpose: pull }`). `null` when the folder holds no control.\n */\nexport async function unbuiltChanges(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, defEntityId: string, dir: string): Promise<{ changed: boolean; home: string; built: string } | null> {\n if (!(await hasControlSource(nfsp, dir))) return null\n const home = await sourcesDigest(nfsp, await collectSources(nfsp, dir))\n const r = await client.extExport(workspaceId, [defEntityId], 'pull')\n const built = String((r.controls[0] as { digest?: string } | undefined)?.digest ?? '')\n return { changed: home !== built, home, built }\n}\n\nexport async function readBuildState(nfsp: NfspClient, dir: string): Promise<AiwsBuildState | null> {\n try {\n const entry = await child(nfsp, dir, AIWS_BUILD_STATE_FILE)\n const nodeId = entry?.target.ref.type === 'live' ? entry.target.ref.node_id : undefined\n if (!nodeId) return null\n const response = await nfsp.readFile(nodeId)\n return (await response.json()) as AiwsBuildState\n } catch {\n return null\n }\n}\n\nexport async function writeBuildState(nfsp: NfspClient, dir: string, state: AiwsBuildState): Promise<void> {\n await writeHomeFile(nfsp, dir, AIWS_BUILD_STATE_FILE, encoder.encode(`${JSON.stringify(state, null, 2)}\\n`))\n}\n\nexport interface AiwsBuildOptions { folderId?: string; force?: boolean; dryRun?: boolean; upload?: AiwsUploader; migration?: Record<string, AiwsMigration> }\n\n/**\n * Build the control in `dir` into a Workspace: collect the files, call `ext.build` with the base recorded in\n * `.aiws-build.json` (when it is this Workspace's), and record the new base. Service refusals throw `AiwsFailure`\n * (`BUILD_FAILED` carries `data.diagnostics`); source problems throw `AiwsSourceError`.\n */\nexport async function buildControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, dir: string, opts: AiwsBuildOptions = {}): Promise<Record<string, unknown> & { files: AiwsSourceFile[] }> {\n const files = await collectSources(nfsp, dir)\n const state = await readBuildState(nfsp, dir)\n const base = state && state.workspace_id === workspaceId ? { def_rev: state.def_rev, dir_rev: state.dir_rev } : undefined\n const result = await client.extBuild(workspaceId, {\n files: await buildFiles(nfsp, files, opts.upload),\n ...(opts.folderId ? { folder_id: opts.folderId } : {}),\n ...(base ? { expect: base } : {}),\n ...(opts.force ? { force: true } : {}),\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.migration ? { migration: opts.migration } : {}),\n })\n if (!opts.dryRun && typeof result.def_entity_id === 'string' && typeof result.def_rev === 'number') {\n await writeBuildState(nfsp, dir, { workspace_id: workspaceId, def_entity_id: result.def_entity_id, def_rev: result.def_rev, dir_rev: Number(result.dir_rev ?? 0), ident: String(result.ident ?? ''), at: new Date().toISOString() })\n }\n return { ...result, files }\n}\n\n/**\n * Write a definition's Workspace snapshot into `outDir` (a definition never built from source gets synthesized\n * files) and record it as the base of the next build.\n */\nexport async function pullControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, defEntityId: string, outDir: string, fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<{ files: string[]; state: AiwsBuildState }> {\n const r = await client.extExport(workspaceId, [defEntityId], 'pull')\n const control = r.controls[0] as { entity_id: string; ident: string; def_rev: number; dir_rev: number; files: { name: string; obj_id?: string; text?: string }[] }\n await ensureFolder(nfsp, outDir)\n for (const f of control.files) await writeSourceFile(nfsp, outDir, f.name, f.text !== undefined ? encoder.encode(f.text) : await fetchAsset(workspaceId, String(f.obj_id)))\n const state: AiwsBuildState = { workspace_id: workspaceId, def_entity_id: control.entity_id, def_rev: control.def_rev, dir_rev: control.dir_rev, ident: control.ident, at: new Date().toISOString() }\n await writeBuildState(nfsp, outDir, state)\n return { files: control.files.map((f) => f.name), state }\n}\n\n/**\n * Rebuild whenever the folder changes: NFSP watch events (lossy: a `resync` lists again), debounced, and only when\n * the files' objects differ from the last build. Returns when `signal` aborts.\n */\nexport async function watchControl(nfsp: NfspClient, dir: string, onChange: (files: AiwsSourceFile[]) => Promise<void>, opts: { debounceMs?: number; signal?: AbortSignal } = {}): Promise<void> {\n let last = ''\n let timer: ReturnType<typeof setTimeout> | undefined\n let running = Promise.resolve()\n const check = () => {\n running = running.then(async () => {\n let files: AiwsSourceFile[]\n try { files = await collectSources(nfsp, dir) } catch { return }\n const key = sourcesKey(files)\n if (key === last) return\n last = key\n await onChange(files)\n }).catch(() => undefined)\n }\n check()\n while (!opts.signal?.aborted) {\n const listing = await nfsp.list(dir, { limit: 1 }, ['base'])\n const stream = nfsp.watch({ tokens: listing.watch_token ? [listing.watch_token] : [], signal: opts.signal })\n try {\n for await (const _ of stream) {\n if (timer) clearTimeout(timer)\n timer = setTimeout(check, opts.debounceMs ?? 500)\n }\n } catch {\n if (opts.signal?.aborted) break\n await sleep(2_000)\n } finally {\n stream.close()\n }\n }\n if (timer) clearTimeout(timer)\n await running\n}\n\n// ---- skeletons\n\nexport interface AiwsSkeletonOptions {\n authorDid: string\n name: string\n title?: string\n kind?: 'declarative' | 'html' | 'composite'\n /** A composite's slots (default: one `items` slot taking any Block) and what it builds on. */\n slots?: AiwsComposition['slots']\n deps?: string[]\n algorithm?: 'stack' | 'fixed'\n}\n\n/** The files of a new control: a minimal working declarative or HTML control (with one public event, raised by a\n * button) with one optional binding, or a composite that stacks (or keeps in place) the Blocks of its slots under a\n * titled frame. */\nexport function controlSkeleton(opts: AiwsSkeletonOptions): Record<string, string> {\n const title = opts.title ?? opts.name\n if (opts.kind === 'composite') {\n const fixed = opts.algorithm === 'fixed'\n const slots = opts.slots ?? { items: { placement: fixed ? 'free' : 'stack', title: 'Items' } }\n const composition: AiwsComposition = {\n layout: fixed ? { algorithm: 'fixed', padding: 12 } : { algorithm: 'stack', direction: 'column', spacing: '{{config.gap}}', padding: 12 },\n slots,\n chrome: { background: '{{config.background}}', radius: 12, title: { text: '{{config.title}}' }, empty: 'Drop Blocks here' },\n }\n const component = {\n manifest_version: AIWS_MANIFEST_VERSION,\n ident: { author_did: opts.authorDid, name: opts.name },\n kind: 'composite',\n title,\n description: `${title}: a panel of Blocks`,\n default_size: { w: 320, h: 360 },\n config_schema: { type: 'object', properties: {\n title: { type: 'string', title: 'Title', default: title },\n background: { type: 'string', title: 'Background', default: '#f6f7fb' },\n gap: { type: 'integer', title: 'Gap (px)', default: 8, minimum: 0, maximum: 64 },\n } },\n entry: AIWS_COMPOSITION_FILE,\n deps: opts.deps ?? [],\n catalog: { group: 'custom', description: `${title}` },\n agent: 'AGENT.md',\n }\n const names = Object.keys(slots).map((n) => `\\`${n}\\``).join(', ')\n return {\n [AIWS_COMPONENT_FILE]: `${JSON.stringify(component, null, 2)}\\n`,\n [AIWS_COMPOSITION_FILE]: `${JSON.stringify(composition, null, 2)}\\n`,\n 'AGENT.md': `# ${title}\\n\\nA composite: an instance is a \\`buckyos.container { kind: \"composite\", def_ref }\\`; put Blocks under it with \\`slot\\` set to one of ${names}. Config: \\`title\\`, \\`background\\`, \\`gap\\`.\\n`,\n }\n }\n const base = {\n manifest_version: AIWS_MANIFEST_VERSION,\n ident: { author_did: opts.authorDid, name: opts.name },\n kind: opts.kind ?? 'declarative',\n title,\n description: `${title}: a control of this Workspace`,\n accepts: ['buckyos.table-source', 'buckyos.record'],\n allow_no_source: true,\n default_size: { w: 260, h: 140 },\n config_schema: { type: 'object', properties: { label: { type: 'string', title: 'Label', default: title } } },\n bindings: { data: { accepts: ['buckyos.table-source'], title: 'Data', description: 'The table this control summarizes' } },\n catalog: { group: 'custom', description: `${title}` },\n agent: 'AGENT.md',\n }\n const agent = `# ${title}\\n\\nBind \\`data\\` to a table. Config: \\`label\\` (text).\\n`\n if (opts.kind === 'html') {\n const events = { clicked: { title: 'Clicked', description: 'Raised when someone clicks the button (in run mode)', params: { count: { type: 'number', description: 'Rows of the bound table' } } } }\n return {\n [AIWS_COMPONENT_FILE]: `${JSON.stringify({ ...base, host_api: AIWS_HTML_API_VERSION, events, entry: { html: 'view.html', css: 'style.css', js: 'behavior.js' } }, null, 2)}\\n`,\n 'view.html': '<div class=\"card\"><div class=\"label\" id=\"label\"></div><div class=\"value\" id=\"value\">—</div><button id=\"go\" type=\"button\">Go</button></div>\\n',\n 'style.css': '.card{font:14px system-ui;padding:12px}.label{opacity:.7}.value{font-size:28px;font-weight:600}\\n',\n 'behavior.js': [\n \"document.getElementById('label').textContent = (aiws.context.config || {}).label || ''\",\n 'var count = 0',\n \"if (aiws.bindings.data) aiws.input('data').rows().then(function (rows) { count = rows.length; document.getElementById('value').textContent = String(count) })\",\n '// the public event of component.json: an instance binds handlers to it in its `on` (host API 3)',\n \"document.getElementById('go').addEventListener('click', function () { aiws.emit('clicked', { count: count }) })\",\n '',\n ].join('\\n'),\n 'AGENT.md': `${agent}Event: \\`clicked\\` (\\`count\\`), raised by its button; bind handlers to it in the instance's \\`on\\`.\\n`,\n }\n }\n return {\n [AIWS_COMPONENT_FILE]: `${JSON.stringify({ ...base, entry: 'declarative.json' }, null, 2)}\\n`,\n 'declarative.json': `${JSON.stringify({ layout: 'stack', items: [{ kind: 'metric', label: title, bind: 'data.count', format: 'number' }, { kind: 'text', text: 'Rows of the bound table' }] }, null, 2)}\\n`,\n 'AGENT.md': agent,\n }\n}\n\n/** Create a control's source folder from a skeleton (refuses to overwrite a folder that has a component.json). */\nexport async function createControlSource(nfsp: NfspClient, dir: string, files: Record<string, string>): Promise<WireRef> {\n const ref = await ensureFolder(nfsp, dir)\n const existing = await nfsp.list({ ref }, { limit: 500 }, ['base']).catch(() => null)\n if (existing?.entries.some((e) => e.name === AIWS_COMPONENT_FILE)) throw new AiwsSourceError([{ file: AIWS_COMPONENT_FILE, severity: 'error', message: `${dir} already holds a control` }])\n for (const [name, text] of Object.entries(files)) await writeHomeFile(nfsp, ref, name, encoder.encode(text))\n return ref\n}\n"],"names":["AIWS_COMPONENT_FILE","AIWS_COMPOSITION_FILE","AIWS_MANIFEST_FILE","AIWS_BUILD_STATE_FILE","AIWS_TEMPLATE_FORMAT","AiwsSourceError","Error","constructor","diagnostics","super","filter","d","severity","map","file","message","join","this","name","encoder","TextEncoder","decoder","TextDecoder","joinPath","dir","replace","folderName","title","trim","slice","async","sha256Hex","bytes","digest","crypto","subtle","Array","from","Uint8Array","b","toString","padStart","aiwsContentDigest","files","pairs","push","sort","a","encode","JSON","stringify","sourcesKey","localeCompare","f","obj_id","etag","AIWS_MAX_INLINE_BYTES","base64","binary","i","length","String","fromCharCode","subarray","btoa","packBuildFiles","upload","byRef","total","reduce","n","uploaded","Map","set","out","obj","get","buildFiles","nfsp","inline","_a","startsWith","node_id","readFile","arrayBuffer","COMPONENT_KEYS","SCHEMA_KEYWORDS","NAME","DID","BINDING","IDENT","V2_HINT","V3_HINT","EVENT_PARAM_TYPES","ITEM_KINDS","ITEM_KEYS","ACTION_COMMANDS","INSPECTOR_KINDS","isRecord","v","isArray","isSourcePath","includes","split","every","seg","configProps","configSchema","props","properties","configPlaceholders","text","at","error","m","matchAll","inner","schemaProblems","path","k","x","Object","entries","s","checkDeclarative","context","code","warn","o","parsed","parse","e","bindings","strings","forEach","items","list","it","iat","kind","keys","format","bind","prefix","indexOf","manifestVersion","label","emit","events","params","button","r","command","id","key","view","checkComposition","placeholders","t","dimension","max","test","layout","algorithm","Number","isInteger","side","columns","slots","raw","slot","min","chrome","tk","tv","event","cells","accepts","ident","cellEvents","call","names","checkComponent","fileNames","readText","c","mv","manifest_version","version","before3","self","author_did","composite","config_schema","p","deps","seen","Set","has","add","spec","pat","type","eventProblems","named","entry","html","host_api","entryText","assets","agent","compatManifest","value","purpose","controls","workspace_templates","TEMPLATE_ID","templateDir","aiwsTemplateDigest","own","templateProblems","snapshot","description","requires","reset","tables","some","size","child","folder","glob","ref","limit","name_glob","find","ensureFolder","parts","Boolean","stat","hit","target","mkdir","findFolder","hasControlSource","writeHomeFile","uploadFile","overwrite","sleep","ms","Promise","setTimeout","collectSources","problems","walk","depth","cursor","page","objId","attrs","_b","_c","truncated","next_cursor","writeSourceFile","cut","lastIndexOf","sourcesDigest","readBuildState","nodeId","response","json","writeBuildState","state","client","workspaceId","opts","base","workspace_id","def_rev","dir_rev","result","extBuild","folderId","folder_id","expect","force","dryRun","dry_run","migration","def_entity_id","Date","toISOString","fixed","placement","composition","padding","direction","spacing","background","radius","empty","component","authorDid","default_size","w","h","default","gap","minimum","maximum","catalog","group","allow_no_source","data","clicked","count","css","js","existing","catch","entityIds","fetchAsset","extExport","manifest","owner","workspaceTitle","pkg","defEntityId","outDir","control","entity_id","values","home","built","changed","decode","templates","declared","comp","dirs","idents","onChange","timer","last","running","resolve","check","then","signal","aborted","listing","stream","watch","tokens","watch_token","_","clearTimeout","debounceMs","close"],"mappings":"gFAoBO,MAAMA,EAAsB,iBAEtBC,EAAwB,mBACxBC,EAAqB,qBAErBC,EAAwB,mBAUxBC,EAAuB,kBA6B7B,MAAMC,UAAwBC,MAEnC,WAAAC,CAAYC,GACJC,MAAAD,EAAYE,QAAQC,GAAqB,UAAfA,EAAEC,WAAsBC,KAAKF,GAAM,GAAGA,EAAEG,KAAO,GAAGH,EAAEG,SAAW,KAAKH,EAAEI,YAAWC,KAAK,OAAS,0BAC/HC,KAAKC,KAAO,kBACZD,KAAKT,YAAcA,CACrB,EAGF,MAAMW,EAAU,IAAIC,YACdC,EAAU,IAAIC,YAEJ,SAAAC,EAASC,EAAaN,GACpC,MAAO,GAAGM,EAAIC,QAAQ,OAAQ,OAAOP,GACvC,CAGO,SAASQ,EAAWC,GAEzB,OADgBA,EAAMF,QAAQ,sBAAuB,KAAKA,QAAQ,OAAQ,IAAIG,OAC/DC,MAAM,EAAG,KAAO,WACjC,CAmBAC,eAAeC,EAAUC,GACvB,MAAMC,QAAeC,OAAOC,OAAOF,OAAO,UAAWD,GACrD,OAAOI,MAAMC,KAAK,IAAIC,WAAWL,IAAUM,GAAMA,EAAEC,SAAS,IAAIC,SAAS,EAAG,OAAMzB,KAAK,GACzF,CAGAc,eAAsBY,EAAkBC,GACtC,MAAMC,EAA4B,GACvB,IAAA,MAAC1B,EAAMc,KAAUW,EAAOC,EAAMC,KAAK,CAAC3B,QAAYa,EAAUC,KAE9D,OADPY,EAAME,MAAK,CAACC,EAAGR,IAAOQ,EAAE,GAAKR,EAAE,IAAK,EAAKQ,EAAE,GAAKR,EAAE,GAAK,EAAI,IACpD,gBAAgBR,EAAUZ,EAAQ6B,OAAOC,KAAKC,UAAUN,MACjE,CAGO,SAASO,EAAWR,GACzB,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