@reqvire-org/ads 0.4.4 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -8
- package/dist/capture.mjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/input-scope.mjs +57 -0
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/build-status.mjs +12 -3
- package/dist/mcp/drafts.mjs +7 -0
- package/dist/mcp/mutations.mjs +1 -1
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- package/dist/mcp/preview-watch.mjs +14 -3
- package/dist/mcp/preview-widget.bundle.js +20 -20
- package/dist/mcp/resource-loader.js +1 -1
- package/dist/mcp/sandbox-host.mjs +6 -1
- package/dist/mcp/server.mjs +49 -9
- package/dist/mcp/showcase-host.mjs +56 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- package/dist/preview-inputs.mjs +7 -2
- package/dist/scenario-registry.mjs +2 -2
- package/dist/scenarios-compiler.mjs +19 -1
- package/dist/showcase/client.bundle.js +54 -54
- package/dist/showcase/comparison.js +15 -12
- package/dist/showcase/connection.js +10 -0
- package/dist/showcase/http-client.bundle.js +9 -0
- package/dist/showcase/http-connection.js +86 -0
- package/dist/showcase/http-preview.js +81 -0
- package/dist/showcase-http-routes.mjs +31 -0
- package/dist/skills/README.md +2 -2
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/runtimes.md +18 -2
- package/dist/skills/ads-designer/references/workflows.md +16 -0
- package/dist/skills/ads-import/references/captures.md +1 -1
- package/dist/skills/ads-import/references/runtimes.md +18 -2
- package/dist/skills/ads-import/references/workflows.md +16 -0
- package/dist/skills/ads-migrate/SKILL.md +1 -0
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +9 -0
- package/dist/skills/ads-migrate/references/0.4.4-to-0.4.5.md +72 -0
- package/dist/skills/ads-port/references/captures.md +1 -1
- package/dist/skills/ads-port/references/runtimes.md +18 -2
- package/dist/skills/ads-port/references/workflows.md +16 -0
- package/dist/stage-timing.cjs +3 -2
- package/dist/validation-inputs.mjs +21 -3
- package/dist/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +56 -42
- package/docs/CHANGELOG.md +45 -25
- package/docs/GUIDE.md +15 -8
- package/docs/HTTP-SHOWCASE-POC.md +397 -0
- package/docs/MCP.md +63 -9
- package/docs/benchmarks/http-showcase-optimized.json +1879 -0
- package/docs/benchmarks/http-showcase-profile.json +308 -0
- package/docs/benchmarks/http-showcase.json +3069 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
function S(){let t=new Map,o=new Set,n=!1,e;function s(i){let c={data:t.get(i)?.data??{},callbacks:[],listeners:new Map};return t.set(i,c),{data:c.data,accept(d,f){if(!d||typeof d==="function")c.callbacks.push({deps:[i],callback:(h)=>d?.(h[0])});else c.callbacks.push({deps:typeof d==="string"?[d]:d,callback:(h)=>f?.(typeof d==="string"?h[0]:h)})},acceptExports(d,f){c.callbacks.push({deps:[i],callback:(h)=>f?.(h[0])})},dispose(d){c.dispose=d},prune(d){c.prune=d},invalidate(){n=!0},decline(){n=!0},on(d,f){let h=c.listeners.get(d)??new Set;h.add(f),c.listeners.set(d,h)},off(d,f){c.listeners.get(d)?.delete(f)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function r(i){for(let u of t.values())for(let c of u.listeners.get(i)??[])await c()}return{context:s,observe(i,u,c){let d=t.get(i);if(!d)return;let f=import(u).then((h)=>{d.exports=h,d.isComponent=c});o.add(f),f.then(()=>o.delete(f),(h)=>{o.delete(f),e=h})},async update(i,u,c,d){if(await Promise.all(o),e)throw e;let f=new Map([...i].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),h=new Map([...u].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),v=new Map,m=new Map;for(let[a,{record:l}]of f)for(let y of[...l.imports,...l.dynamicImports]){let g=i.get(y)?.hot?.id;if(!g)continue;let w=v.get(g)??new Set;w.add(a),v.set(g,w)}function b(a,l=new Set){if(l.has(a))return!1;let y=t.get(a);if(y?.callbacks.some((E)=>E.deps.includes(a))&&h.has(a))return m.set(a,y),!0;let g=v.get(a);if(!g?.size)return!1;let w=new Set([...l,a]);for(let E of g)if(!b(E,w))return!1;return!0}for(let[a,{record:l}]of f){let y=h.get(a)?.record;if(!y||l.hot.source!==y.hot.source){if(!b(a))return!1}}if(!m.size)return!0;n=!1,await r("vite:beforeUpdate");let p=[];for(let[a,l]of m){if(!d())return!1;await l.dispose?.(l.data),p.push([a,l,await c(h.get(a).uri)])}if(!d())return!1;for(let[,a,l]of p)if(a.isComponent){let y=a.exports,g=Object.keys(l).filter((w)=>w!=="__esModule");if(!y||g.length!==Object.keys(y).filter((w)=>w!=="__esModule").length||g.some((w)=>!Object.hasOwn(y,w)||!a.isComponent(l[w])&&y[w]!==l[w]))return!1}for(let[a,l,y]of p)for(let g of l.callbacks)if(g.deps.includes(a))await g.callback(g.deps.map((w)=>w===a?y:void 0));return await r("vite:afterUpdate"),await new Promise((a)=>setTimeout(a,20)),d()&&!n},async dispose(){for(let i of t.values())await i.dispose?.(i.data),await i.prune?.(i.data);t.clear(),o.clear(),e=void 0}}}function R(t,o){let n=[],e=new Set;function s(r){if(e.has(r))return;e.add(r);let i=t.get(r);if(!i)throw Error(`Missing preview dependency metadata: ${r}`);for(let u of[...i.imports,...i.styles,...i.references])s(u);n.push(r)}return s(o),n}function O(t,o){if(!t||t.revision===o.revision)return[];let n=(e,s)=>{let r=new Map(Object.entries(e.assets));return JSON.stringify(R(r,s.module).map((i)=>[i,r.get(i)]))};return o.scenarios.filter((e)=>{let s=t.scenarios.find((r)=>r.id===e.id);return!s||n(t,s)!==n(o,e)}).map((e)=>e.id)}class x{constructor(t){this.read=t,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.executed=new Map,this.moduleHistory=new Set,this.importing=Promise.resolve(),this.mounting=Promise.resolve(),this.refreshDirty=!1,this.generation=0,this.prefetchGeneration=0,this.closed=!1,this.hot=S(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(o)=>this.importModule(o)}register(t){if(t.schemaVersion!==1||!Array.isArray(t.scenarios)||!t.assets||typeof t.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(t.refresh&&(t.refresh.version!==1||typeof t.refresh.epoch!=="string"||!t.refresh.epoch||t.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let o=new Set;for(let[n,e]of Object.entries(t.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(n)||!/^sha256:[a-f0-9]{64}$/.test(e.digest)||e.hot&&(!t.refresh||e.kind!=="module"||typeof e.hot.id!=="string"||!e.hot.id||e.hot.id.length>4096||o.has(e.hot.id)||!/^[a-f0-9]{64}$/.test(e.hot.source))||!["imports","dynamicImports","styles","references"].every((s)=>Array.isArray(e[s])&&e[s].every((r)=>Object.hasOwn(t.assets,r))))throw Error("Invalid preview dependency graph.");if(e.hot)o.add(e.hot.id);if(this.records.has(n)&&this.records.get(n).digest!==e.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:n})}for(let[n,e]of Object.entries(t.assets))this.records.set(n,e)}async resource(t){if(!this.bytes.has(t)){let o=(async()=>{let n=this.records.get(t);if(!n)throw Error(`Unknown preview dependency: ${t}`);let e;try{e=await this.read(t)}catch(c){throw Object.assign(Error(`Preview resource read failed for ${t}: ${c.message}`,{cause:c}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:t})}if(this.closed)throw Error("The preview App was closed.");let s=e.contents.find((c)=>c.uri===t);if(!s)throw Object.assign(Error(`Missing preview dependency: ${t}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:t});let r=typeof s.text==="string"?new TextEncoder().encode(s.text):Uint8Array.from(atob(s.blob),(c)=>c.charCodeAt(0)),i=await crypto.subtle.digest("SHA-256",r),u="sha256:"+[...new Uint8Array(i)].map((c)=>c.toString(16).padStart(2,"0")).join("");if(r.length!==n.size||u!==n.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:t});return r})();this.bytes.set(t,o),o.catch(()=>this.bytes.delete(t))}return this.bytes.get(t)}closure(t){return R(this.records,t)}async prefetch(t,o){if(this.closed)return;this.register(t);let n=++this.prefetchGeneration,e=new Set,s=[],r=0;for(let d of o){let f=t.scenarios.find((m)=>m.id===d);if(!f)continue;let h=this.closure(f.module).filter((m)=>!this.bytes.has(m)&&!e.has(m)),v=h.reduce((m,b)=>m+this.records.get(b).size,0);if(r+v>16777216||e.size+h.length>256)continue;r+=v,s.push(d);for(let m of h)e.add(m)}let i=[...e],u=0,c=async()=>{while(!this.closed&&n===this.prefetchGeneration&&u<i.length)await this.resource(i[u++])};return await Promise.all(Array.from({length:Math.min(3,i.length)},c)),{scenarios:s,resources:i.length}}async materialize(t){let o=this.closure(t);await Promise.all(o.map((e)=>this.resource(e)));let n={};for(let e of o){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(e))continue;let s=this.records.get(e),r=await this.resource(e);if(s.kind==="module"||s.mimeType==="text/css"||s.mimeType==="text/javascript"){let u=new TextDecoder().decode(r);for(let c of s.references){let d=this.urls.get(c);if(!d)throw Error("Unsupported cyclic asset reference.");u=u.replaceAll(c,d)}r=u}let i=URL.createObjectURL(new Blob([r],{type:s.mimeType}));if(this.urls.set(e,i),s.kind==="module")n[e]=i}if(Object.keys(n).length){let e=document.createElement("script");e.type="importmap",e.textContent=JSON.stringify({imports:n}),document.head.append(e)}return o}async importModule(t){let o=this.importing.then(()=>this.materialize(t));this.importing=o.catch(()=>{});let n=await o;await this.attachStyles(n);try{let e=await import(t);this.loadedModules.add(t);for(let s of n){let r=this.records.get(s);if(r.hot)this.executed.set(r.hot.id,{uri:s,record:r}),this.moduleHistory.add(s)}return e}catch(e){throw Error(`Preview module import failed for ${t}: ${e.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:e})}}async attachStyles(t){for(let o of t){if(this.records.get(o).mimeType!=="text/css")continue;if(this.styles.has(o)){await this.styleReady.get(o);continue}let e=document.createElement("link");e.rel="stylesheet",e.href=this.urls.get(o),this.styles.set(o,e);let s=new Promise((r,i)=>{e.onload=r,e.onerror=()=>i(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(o,s),document.head.append(e);try{await s}catch(r){throw e.remove(),this.styles.delete(o),this.styleReady.delete(o),r}}}async refreshStyles(t,o){let n=[t],e=new Set,s=new Set;for(let r=0;r<n.length;r++){let i=n[r];if(e.has(i))continue;e.add(i);for(let u of await this.materialize(i)){s.add(u);for(let c of this.records.get(u).dynamicImports)if(this.loadedModules.has(c)||this.executed.has(this.records.get(c)?.hot?.id))n.push(c)}}if(await this.attachStyles([...s]),o!==this.generation||this.closed)return!1;for(let[r,i]of this.styles)if(!s.has(r))i.remove(),this.styles.delete(r),this.styleReady.delete(r);for(let r of s)if(this.styles.has(r))document.head.append(this.styles.get(r));return!0}async mount(t,o,n){let e=++this.generation,s=this.mounting.then(()=>e!==this.generation||this.closed?!1:this.mountRevision(t,o,n,e));return this.mounting=s.catch(()=>{}),s}async mountRevision(t,o,n,e){this.register(t);let s=t.scenarios.find((h)=>h.id===o);if(!s)throw Error("The selected scenario is no longer registered.");let r=JSON.stringify(this.closure(s.module).map((h)=>[h,this.records.get(h)])),i=new Map(this.closure(s.module).map((h)=>[h,this.records.get(h)])),u=(h)=>{throw Object.assign(Error(h),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)u("An interrupted module update requires a clean preview frame.");let c=[...this.urls.keys()].reduce((h,v)=>h+this.records.get(v).size,0);if(this.records.size>4096||c>67108864)u("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==t.refresh?.epoch)u("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(t.refresh&&this.mounted){let h=new Map(Object.entries(t.assets)),v=new Map([...h].filter(([,p])=>p.hot).map(([p,a])=>[a.hot.id,{uri:p,record:a}]));for(let[p,{record:a}]of this.executed){let l=v.get(p);if(l&&l.record.hot.source!==a.hot.source&&this.moduleHistory.has(l.uri))u("Restoring a previous module revision requires a clean preview frame.")}let m=new Map([...this.executed.values()].map(({uri:p,record:a})=>[p,a]));this.refreshDirty=!0;let b=await this.hot.update(m,h,(p)=>this.importModule(p),()=>e===this.generation&&!this.closed);if(e!==this.generation||this.closed)return!1;if(!b)u("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let p of this.executed.keys())if(v.has(p))this.executed.set(p,v.get(p));if(this.mounted.id===o){if(!await this.refreshStyles(s.module,e))return!1;return this.revisions.add(s.module),this.mounted={...this.mounted,signature:r,records:i,module:s.module},!0}}if(this.mounted?.id===o&&this.mounted.container===n&&this.mounted.signature===r)return this.refreshStyles(s.module,e);if(this.revisions.add(s.module),!t.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let d=await this.importModule(s.module);if(e!==this.generation)return!1;let f=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await f?.(),e!==this.generation||this.closed)return!1;if(n.replaceChildren(),!await this.refreshStyles(s.module,e))return!1;if(typeof d.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=d.mount(n),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:o,container:n,signature:r,records:i,module:s.module,refresh:t.refresh},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.mounting,await this.unmount?.(),await this.hot.dispose(),this.mounted=void 0;for(let t of this.styles.values())t.remove();for(let t of this.urls.values())URL.revokeObjectURL(t);if(this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),this.executed.clear(),this.moduleHistory.clear(),delete globalThis.__dsPreviewImport,globalThis.__adsPreviewHot===this.hot)delete globalThis.__adsPreviewHot}}export{x as PreviewResourceLoader,O as changedPreviewScenarios};
|
|
1
|
+
function S(){let t=new Map,o=new Set,n=!1,e;function s(r){let d={data:t.get(r)?.data??{},callbacks:[],listeners:new Map};return t.set(r,d),{data:d.data,accept(h,f){if(!h||typeof h==="function")d.callbacks.push({deps:[r],callback:(c)=>h?.(c[0])});else d.callbacks.push({deps:typeof h==="string"?[h]:h,callback:(c)=>f?.(typeof h==="string"?c[0]:c)})},acceptExports(h,f){d.callbacks.push({deps:[r],callback:(c)=>f?.(c[0])})},dispose(h){d.dispose=h},prune(h){d.prune=h},invalidate(){n=!0},decline(){n=!0},on(h,f){let c=d.listeners.get(h)??new Set;c.add(f),d.listeners.set(h,c)},off(h,f){d.listeners.get(h)?.delete(f)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function i(r){for(let u of t.values())for(let d of u.listeners.get(r)??[])await d()}return{context:s,observe(r,u,d){let h=t.get(r);if(!h)return;let f=import(u).then((c)=>{h.exports=c,h.isComponent=d});o.add(f),f.then(()=>o.delete(f),(c)=>{o.delete(f),e=c})},async update(r,u,d,h){if(await Promise.all(o),e)throw e;let f=new Map([...r].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),c=new Map([...u].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),v=new Map,m=new Map;for(let[a,{record:l}]of f)for(let y of[...l.imports,...l.dynamicImports]){let g=r.get(y)?.hot?.id;if(!g)continue;let w=v.get(g)??new Set;w.add(a),v.set(g,w)}function b(a,l=new Set){if(l.has(a))return!1;let y=t.get(a);if(y?.callbacks.some((E)=>E.deps.includes(a))&&c.has(a))return m.set(a,y),!0;let g=v.get(a);if(!g?.size)return!1;let w=new Set([...l,a]);for(let E of g)if(!b(E,w))return!1;return!0}for(let[a,{record:l}]of f){let y=c.get(a)?.record;if(!y||l.hot.source!==y.hot.source){if(!b(a))return!1}}if(!m.size)return!0;n=!1,await i("vite:beforeUpdate");let p=[];for(let[a,l]of m){if(!h())return!1;await l.dispose?.(l.data),p.push([a,l,await d(c.get(a).uri)])}if(!h())return!1;for(let[,a,l]of p)if(a.isComponent){let y=a.exports,g=Object.keys(l).filter((w)=>w!=="__esModule");if(!y||g.length!==Object.keys(y).filter((w)=>w!=="__esModule").length||g.some((w)=>!Object.hasOwn(y,w)||!a.isComponent(l[w])&&y[w]!==l[w]))return!1}for(let[a,l,y]of p)for(let g of l.callbacks)if(g.deps.includes(a))await g.callback(g.deps.map((w)=>w===a?y:void 0));return await i("vite:afterUpdate"),await new Promise((a)=>setTimeout(a,20)),h()&&!n},async dispose(){for(let r of t.values())await r.dispose?.(r.data),await r.prune?.(r.data);t.clear(),o.clear(),e=void 0}}}async function x(t,o){let n=await crypto.subtle.digest("SHA-256",o),e="sha256:"+[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,"0")).join("");if(o.length!==t.size||e!==t.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build"});return o}function R(t,o){let n=[],e=new Set;function s(i){if(e.has(i))return;e.add(i);let r=t.get(i);if(!r)throw Error(`Missing preview dependency metadata: ${i}`);for(let u of[...r.imports,...r.styles,...r.references])s(u);n.push(i)}return s(o),n}function P(t,o){if(!t||t.revision===o.revision)return[];let n=(e,s)=>{let i=new Map(Object.entries(e.assets));return JSON.stringify(R(i,s.module).map((r)=>[r,i.get(r)]))};return o.scenarios.filter((e)=>{let s=t.scenarios.find((i)=>i.id===e.id);return!s||n(t,s)!==n(o,e)}).map((e)=>e.id)}class M{constructor(t){this.read=t,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.executed=new Map,this.moduleHistory=new Set,this.importing=Promise.resolve(),this.mounting=Promise.resolve(),this.refreshDirty=!1,this.generation=0,this.prefetchGeneration=0,this.closed=!1,this.hot=S(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(o)=>this.importModule(o)}register(t){if(t.schemaVersion!==1||!Array.isArray(t.scenarios)||!t.assets||typeof t.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(t.refresh&&(t.refresh.version!==1||typeof t.refresh.epoch!=="string"||!t.refresh.epoch||t.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let o=new Set;for(let[n,e]of Object.entries(t.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(n)||!/^sha256:[a-f0-9]{64}$/.test(e.digest)||e.hot&&(!t.refresh||e.kind!=="module"||typeof e.hot.id!=="string"||!e.hot.id||e.hot.id.length>4096||o.has(e.hot.id)||!/^[a-f0-9]{64}$/.test(e.hot.source))||!["imports","dynamicImports","styles","references"].every((s)=>Array.isArray(e[s])&&e[s].every((i)=>Object.hasOwn(t.assets,i))))throw Error("Invalid preview dependency graph.");if(e.hot)o.add(e.hot.id);if(this.records.has(n)&&this.records.get(n).digest!==e.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:n})}for(let[n,e]of Object.entries(t.assets))this.records.set(n,e)}async resource(t){if(!this.bytes.has(t)){let o=(async()=>{let n=this.records.get(t);if(!n)throw Error(`Unknown preview dependency: ${t}`);let e;try{e=await this.read(t)}catch(r){throw Object.assign(Error(`Preview resource read failed for ${t}: ${r.message}`,{cause:r}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:t})}if(this.closed)throw Error("The preview App was closed.");let s=e.contents.find((r)=>r.uri===t);if(!s)throw Object.assign(Error(`Missing preview dependency: ${t}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:t});let i=typeof s.text==="string"?new TextEncoder().encode(s.text):Uint8Array.from(atob(s.blob),(r)=>r.charCodeAt(0));try{return await x(n,i)}catch(r){throw r.resourceUri=t,r}})();this.bytes.set(t,o),o.catch(()=>this.bytes.delete(t))}return this.bytes.get(t)}closure(t){return R(this.records,t)}async prefetch(t,o){if(this.closed)return;this.register(t);let n=++this.prefetchGeneration,e=new Set,s=[],i=0;for(let h of o){let f=t.scenarios.find((m)=>m.id===h);if(!f)continue;let c=this.closure(f.module).filter((m)=>!this.bytes.has(m)&&!e.has(m)),v=c.reduce((m,b)=>m+this.records.get(b).size,0);if(i+v>16777216||e.size+c.length>256)continue;i+=v,s.push(h);for(let m of c)e.add(m)}let r=[...e],u=0,d=async()=>{while(!this.closed&&n===this.prefetchGeneration&&u<r.length)await this.resource(r[u++])};return await Promise.all(Array.from({length:Math.min(3,r.length)},d)),{scenarios:s,resources:r.length}}async materialize(t){let o=this.closure(t);await Promise.all(o.map((e)=>this.resource(e)));let n={};for(let e of o){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(e))continue;let s=this.records.get(e),i=await this.resource(e);if(s.kind==="module"||s.mimeType==="text/css"||s.mimeType==="text/javascript"){let u=new TextDecoder().decode(i);for(let d of s.references){let h=this.urls.get(d);if(!h)throw Error("Unsupported cyclic asset reference.");u=u.replaceAll(d,h)}i=u}let r=URL.createObjectURL(new Blob([i],{type:s.mimeType}));if(this.urls.set(e,r),s.kind==="module")n[e]=r}if(Object.keys(n).length){let e=document.createElement("script");e.type="importmap",e.textContent=JSON.stringify({imports:n}),document.head.append(e)}return o}async importModule(t){let o=this.importing.then(()=>this.materialize(t));this.importing=o.catch(()=>{});let n=await o;await this.attachStyles(n);try{let e=await import(t);this.loadedModules.add(t);for(let s of n){let i=this.records.get(s);if(i.hot)this.executed.set(i.hot.id,{uri:s,record:i}),this.moduleHistory.add(s)}return e}catch(e){throw Error(`Preview module import failed for ${t}: ${e.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:e})}}async attachStyles(t){for(let o of t){if(this.records.get(o).mimeType!=="text/css")continue;if(this.styles.has(o)){await this.styleReady.get(o);continue}let e=document.createElement("link");e.rel="stylesheet",e.href=this.urls.get(o),this.styles.set(o,e);let s=new Promise((i,r)=>{e.onload=i,e.onerror=()=>r(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(o,s),document.head.append(e);try{await s}catch(i){throw e.remove(),this.styles.delete(o),this.styleReady.delete(o),i}}}async refreshStyles(t,o){let n=[t],e=new Set,s=new Set;for(let i=0;i<n.length;i++){let r=n[i];if(e.has(r))continue;e.add(r);for(let u of await this.materialize(r)){s.add(u);for(let d of this.records.get(u).dynamicImports)if(this.loadedModules.has(d)||this.executed.has(this.records.get(d)?.hot?.id))n.push(d)}}if(await this.attachStyles([...s]),o!==this.generation||this.closed)return!1;for(let[i,r]of this.styles)if(!s.has(i))r.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of s)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(t,o,n){let e=++this.generation,s=this.mounting.then(()=>e!==this.generation||this.closed?!1:this.mountRevision(t,o,n,e));return this.mounting=s.catch(()=>{}),s}async mountRevision(t,o,n,e){this.register(t);let s=t.scenarios.find((c)=>c.id===o);if(!s)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(s.module).map((c)=>[c,this.records.get(c)])),r=new Map(this.closure(s.module).map((c)=>[c,this.records.get(c)])),u=(c)=>{throw Object.assign(Error(c),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)u("An interrupted module update requires a clean preview frame.");let d=[...this.urls.keys()].reduce((c,v)=>c+this.records.get(v).size,0);if(this.records.size>4096||d>67108864)u("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==t.refresh?.epoch)u("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(t.refresh&&this.mounted){let c=new Map(Object.entries(t.assets)),v=new Map([...c].filter(([,p])=>p.hot).map(([p,a])=>[a.hot.id,{uri:p,record:a}]));for(let[p,{record:a}]of this.executed){let l=v.get(p);if(l&&l.record.hot.source!==a.hot.source&&this.moduleHistory.has(l.uri))u("Restoring a previous module revision requires a clean preview frame.")}let m=new Map([...this.executed.values()].map(({uri:p,record:a})=>[p,a]));this.refreshDirty=!0;let b=await this.hot.update(m,c,(p)=>this.importModule(p),()=>e===this.generation&&!this.closed);if(e!==this.generation||this.closed)return!1;if(!b)u("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let p of this.executed.keys())if(v.has(p))this.executed.set(p,v.get(p));if(this.mounted.id===o){if(!await this.refreshStyles(s.module,e))return!1;return this.revisions.add(s.module),this.mounted={...this.mounted,signature:i,records:r,module:s.module},!0}}if(this.mounted?.id===o&&this.mounted.container===n&&this.mounted.signature===i)return this.refreshStyles(s.module,e);if(this.revisions.add(s.module),!t.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let h=await this.importModule(s.module);if(e!==this.generation)return!1;let f=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await f?.(),e!==this.generation||this.closed)return!1;if(n.replaceChildren(),!await this.refreshStyles(s.module,e))return!1;if(typeof h.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=h.mount(n),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:o,container:n,signature:i,records:r,module:s.module,refresh:t.refresh},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.mounting,await this.unmount?.(),await this.hot.dispose(),this.mounted=void 0;for(let t of this.styles.values())t.remove();for(let t of this.urls.values())URL.revokeObjectURL(t);if(this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),this.executed.clear(),this.moduleHistory.clear(),delete globalThis.__dsPreviewImport,globalThis.__adsPreviewHot===this.hot)delete globalThis.__adsPreviewHot}}export{M as PreviewResourceLoader,P as changedPreviewScenarios,x as verifyPreviewAssetBytes};
|
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
import { createServer } from "node:http";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { createHttpPreviewDelivery } from "./preview-http.mjs";
|
|
3
4
|
|
|
4
5
|
/** A different loopback port provides the browser host's separate sandbox origin. */
|
|
5
6
|
export async function startSandboxHost(parentOrigin) {
|
|
6
7
|
const script = await readFile(new URL("../showcase/sandbox.bundle.js", import.meta.url));
|
|
8
|
+
const delivery = await createHttpPreviewDelivery(parentOrigin);
|
|
7
9
|
const web = createServer((req, res) => {
|
|
8
10
|
const origin = `http://127.0.0.1:${web.address().port}`;
|
|
9
11
|
const url = new URL(req.url, origin);
|
|
10
12
|
if (req.headers.host !== new URL(origin).host || req.method !== "GET") { res.writeHead(403); res.end(); return; }
|
|
13
|
+
if (delivery?.serve(req, res)) return;
|
|
11
14
|
const javascript = url.pathname === "/sandbox.js";
|
|
12
15
|
if (!javascript &&( url.pathname !== "/sandbox.html" || url.searchParams.get("parent") !== parentOrigin)) { res.writeHead(404); res.end(); return; }
|
|
13
16
|
res.writeHead(200, { "Content-Type": javascript ? "text/javascript" : "text/html", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": `frame-ancestors ${parentOrigin};object-src 'none'` });
|
|
14
17
|
res.end(javascript ? script : '<!doctype html><html><head><meta charset="utf-8"><style>html,body,iframe{height:100%;width:100%;margin:0;border:0;display:block;overflow:hidden}</style></head><body><script src="/sandbox.js"></script></body></html>');
|
|
15
18
|
});
|
|
16
19
|
await new Promise((resolve, reject) => { web.once("error", reject); web.listen(0, "127.0.0.1", resolve); });
|
|
17
|
-
|
|
20
|
+
delivery?.setOrigin(`http://127.0.0.1:${web.address().port}`);
|
|
21
|
+
return { delivery, url: `http://127.0.0.1:${web.address().port}/sandbox.html?parent=${encodeURIComponent(parentOrigin)}`, close() {
|
|
22
|
+
delivery?.close();
|
|
18
23
|
const stopped = new Promise(resolve => web.close(resolve));
|
|
19
24
|
web.closeAllConnections();
|
|
20
25
|
return stopped;
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -37,6 +37,7 @@ import { createPreviewWork } from "./preview-work.mjs";
|
|
|
37
37
|
import { createCaptureController } from "../capture.mjs";
|
|
38
38
|
import { CAPTURES_URI, captureSpec } from "../capture-store.mjs";
|
|
39
39
|
import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
40
|
+
import { outsideInputRequestScope, withInputRequestScope } from "../input-scope.mjs";
|
|
40
41
|
import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
|
|
41
42
|
import { behaviorSections } from "./behavior-pages.mjs";
|
|
42
43
|
import { compactProgress, resultBudgets } from "./result-pages.mjs";
|
|
@@ -270,10 +271,11 @@ export async function createAdsMcp(
|
|
|
270
271
|
return stored;
|
|
271
272
|
}
|
|
272
273
|
if (cache.registryTask?.revision !== revision) {
|
|
273
|
-
|
|
274
|
+
// Shared by later requests: start it outside this request's revision.
|
|
275
|
+
const inspector = (cache.registryInspector ??= outsideInputRequestScope(() => createScenarioInspector(root)));
|
|
274
276
|
const task = {
|
|
275
277
|
revision,
|
|
276
|
-
promise: inspector.inspect(),
|
|
278
|
+
promise: outsideInputRequestScope(() => inspector.inspect()),
|
|
277
279
|
};
|
|
278
280
|
cache.registryTask = task;
|
|
279
281
|
void task.promise
|
|
@@ -283,7 +285,7 @@ export async function createAdsMcp(
|
|
|
283
285
|
.catch(() => {});
|
|
284
286
|
}
|
|
285
287
|
const registry = await cache.registryTask.promise;
|
|
286
|
-
if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
|
|
288
|
+
if ((await previewSourceRevision(loadConfig(root), [], { fresh: true })) !== revision) continue;
|
|
287
289
|
cache.registry = cache.lastRegistry = registry;
|
|
288
290
|
cache.registryRevision = revision;
|
|
289
291
|
cache.catalog = undefined;
|
|
@@ -371,10 +373,10 @@ export async function createAdsMcp(
|
|
|
371
373
|
const revision = cache.registryRevision;
|
|
372
374
|
if (cache.catalog && cache.catalogRevision === revision) return cache.catalog;
|
|
373
375
|
if (cache.catalogTask?.revision !== revision) {
|
|
374
|
-
const inspector = (cache.registryInspector ??= createScenarioInspector(root));
|
|
376
|
+
const inspector = (cache.registryInspector ??= outsideInputRequestScope(() => createScenarioInspector(root)));
|
|
375
377
|
const task = {
|
|
376
378
|
revision,
|
|
377
|
-
promise: inspector.inspect(root, "catalog"),
|
|
379
|
+
promise: outsideInputRequestScope(() => inspector.inspect(root, "catalog")),
|
|
378
380
|
};
|
|
379
381
|
cache.catalogTask = task;
|
|
380
382
|
void task.promise
|
|
@@ -384,7 +386,7 @@ export async function createAdsMcp(
|
|
|
384
386
|
.catch(() => {});
|
|
385
387
|
}
|
|
386
388
|
const value = await cache.catalogTask.promise;
|
|
387
|
-
if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
|
|
389
|
+
if ((await previewSourceRevision(loadConfig(root), [], { fresh: true })) !== revision) continue;
|
|
388
390
|
cache.catalog = value.catalog;
|
|
389
391
|
cache.catalogRevision = revision;
|
|
390
392
|
cache.behaviorLibraries = {
|
|
@@ -813,7 +815,27 @@ export async function createAdsMcp(
|
|
|
813
815
|
}
|
|
814
816
|
const tokenInventory = () => analyze(root, "tokens");
|
|
815
817
|
const behaviorInventory = (args) => analyze(root, "behavior-page", [args]);
|
|
816
|
-
|
|
818
|
+
// Internal HTTP publication captures one authorized graph and keeps its asset
|
|
819
|
+
// lookup bound to that scope/revision. No client-supplied graph is trusted.
|
|
820
|
+
async function capturePreview(uri, signal) {
|
|
821
|
+
signal?.throwIfAborted();
|
|
822
|
+
if (uri.startsWith("ads://drafts/")) {
|
|
823
|
+
const url = new URL(uri), match = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
|
|
824
|
+
if (!match || [...url.searchParams.keys()].some(key => key !== "uri") || !url.searchParams.get("uri")) throw new Error("Invalid draft resource address.");
|
|
825
|
+
return drafts.capturePreview(match[1], url.searchParams.get("uri"), signal);
|
|
826
|
+
}
|
|
827
|
+
if (![PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI].includes(uri)) throw new Error("Invalid preview manifest resource.");
|
|
828
|
+
const options = uri === LIVE_PREVIEW_MANIFEST_URI ? livePreviewOptions(previewOptions()) : previewOptions();
|
|
829
|
+
const graph = JSON.parse((await read(uri, signal)).contents[0].text);
|
|
830
|
+
signal?.throwIfAborted();
|
|
831
|
+
return { graph, readAsset: id => { signal?.throwIfAborted(); return readPreviewAsset(options, id, graph); } };
|
|
832
|
+
}
|
|
833
|
+
// Accepted-project reads share one input revision per request. Draft reads
|
|
834
|
+
// keep their own lifecycle (they may refresh the draft workspace first).
|
|
835
|
+
function read(uri, signal) {
|
|
836
|
+
return uri.startsWith("ads://drafts/") ? readResource(uri, signal) : withInputRequestScope(() => readResource(uri, signal), { label: `resource:${uri}` });
|
|
837
|
+
}
|
|
838
|
+
async function readResource(uri, signal) {
|
|
817
839
|
if (uri === `${PROJECT_URI}/explorer`)
|
|
818
840
|
return {
|
|
819
841
|
contents: [
|
|
@@ -1222,7 +1244,15 @@ export async function createAdsMcp(
|
|
|
1222
1244
|
} else await refresh();
|
|
1223
1245
|
return result;
|
|
1224
1246
|
}
|
|
1247
|
+
// Read-only accepted-project tools; mutations, validation, captures and
|
|
1248
|
+
// drafts keep fresh reads at every fence.
|
|
1249
|
+
const requestScopedTools = new Set(["ads_status", "ads_catalog", "ads_scenarios", "ads_show_scenario"]);
|
|
1225
1250
|
function tools() {
|
|
1251
|
+
return toolDefinitions().map((tool) =>
|
|
1252
|
+
requestScopedTools.has(tool.name) ? { ...tool, call: (...args) => withInputRequestScope(() => tool.call(...args), { label: `tool:${tool.name}` }) } : tool,
|
|
1253
|
+
);
|
|
1254
|
+
}
|
|
1255
|
+
function toolDefinitions() {
|
|
1226
1256
|
return [
|
|
1227
1257
|
{
|
|
1228
1258
|
name: "ads_drafts",
|
|
@@ -2198,7 +2228,8 @@ export async function createAdsMcp(
|
|
|
2198
2228
|
refreshAgain = false;
|
|
2199
2229
|
const forced = refreshForced;
|
|
2200
2230
|
refreshForced = false;
|
|
2201
|
-
|
|
2231
|
+
// One input revision per observation pass (each status read used to walk again).
|
|
2232
|
+
changed = (await withInputRequestScope(() => refreshOnce(forced), { own: true, label: "observe" })) || changed;
|
|
2202
2233
|
}
|
|
2203
2234
|
return changed;
|
|
2204
2235
|
})
|
|
@@ -2395,6 +2426,7 @@ export async function createAdsMcp(
|
|
|
2395
2426
|
return previewWatch.buildAll(signal, options);
|
|
2396
2427
|
},
|
|
2397
2428
|
readResource: read,
|
|
2429
|
+
capturePreview,
|
|
2398
2430
|
async callTool(name, args, signal) {
|
|
2399
2431
|
const tool = tools().find((tool) => tool.name === name);
|
|
2400
2432
|
if (!tool) throw new Error("Unknown preview tool.");
|
|
@@ -2487,6 +2519,12 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2487
2519
|
}),
|
|
2488
2520
|
})
|
|
2489
2521
|
).server,
|
|
2522
|
+
{
|
|
2523
|
+
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2524
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2525
|
+
onBuildChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
2526
|
+
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2527
|
+
},
|
|
2490
2528
|
);
|
|
2491
2529
|
return {
|
|
2492
2530
|
url,
|
|
@@ -2509,6 +2547,7 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2509
2547
|
},
|
|
2510
2548
|
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2511
2549
|
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2550
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2512
2551
|
// The draft's verified preview revision, as the project host reports its own: captures and
|
|
2513
2552
|
// behavior evidence record which build they observed.
|
|
2514
2553
|
previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
|
|
@@ -2564,10 +2603,11 @@ export async function startAdsMcp(
|
|
|
2564
2603
|
let buildWatcher, buildChangeTimer;
|
|
2565
2604
|
const buildListeners = new Set();
|
|
2566
2605
|
const onBuildChange = (report) => {
|
|
2606
|
+
host?.buildChanged(report);
|
|
2567
2607
|
for (const listener of buildListeners) listener(report);
|
|
2568
2608
|
};
|
|
2569
2609
|
const showcaseUrl = () => host?.url;
|
|
2570
|
-
const mountPreview = (prefix, factory) => host?.mount(prefix, factory);
|
|
2610
|
+
const mountPreview = (prefix, factory, service) => host?.mount(prefix, factory, service);
|
|
2571
2611
|
if (showcase) {
|
|
2572
2612
|
// A 2025-era HTTP session observes the project like a stdio connection; per-request modern instances do not.
|
|
2573
2613
|
host = await startShowcaseHost(
|
|
@@ -4,7 +4,9 @@ import { createServer } from "node:http";
|
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
5
|
import { Readable } from "node:stream";
|
|
6
6
|
import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
|
|
7
|
+
import { serveShowcaseHttp, showcaseHttpEvents } from "./showcase-http.mjs";
|
|
7
8
|
import { startSandboxHost } from "./sandbox-host.mjs";
|
|
9
|
+
import timing from "../stage-timing.cjs";
|
|
8
10
|
|
|
9
11
|
const maxRequestBodySize = 2 * 1024 * 1024,
|
|
10
12
|
maxLegacySessions = 64;
|
|
@@ -73,6 +75,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
73
75
|
[
|
|
74
76
|
["/", "index.html", "text/html"],
|
|
75
77
|
["/client.js", "client.bundle.js", "text/javascript"],
|
|
78
|
+
["/http-client.js", "http-client.bundle.js", "text/javascript"],
|
|
76
79
|
["/style.css", "style.css", "text/css"],
|
|
77
80
|
["/ui.css", "ui/ui.css", "text/css"],
|
|
78
81
|
["/favicon.svg", "favicon.svg", "image/svg+xml"],
|
|
@@ -86,7 +89,22 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
86
89
|
// Draft previews are served from this same host under /draft/<id>/: the same client, with that
|
|
87
90
|
// draft's own MCP endpoint. No other port or process.
|
|
88
91
|
const mounts = new Map();
|
|
89
|
-
const
|
|
92
|
+
const services = new Map();
|
|
93
|
+
const events = showcaseHttpEvents();
|
|
94
|
+
const buildReports = new Map();
|
|
95
|
+
const buildSubscriptions = new Map();
|
|
96
|
+
function publishBuild(uri, report) {
|
|
97
|
+
const signature = JSON.stringify(report);
|
|
98
|
+
if (buildReports.get(uri) === signature) return;
|
|
99
|
+
buildReports.set(uri, signature);
|
|
100
|
+
events.emit({ type: "build", uri, report });
|
|
101
|
+
}
|
|
102
|
+
const observer = await observe?.({
|
|
103
|
+
...handler.notify,
|
|
104
|
+
resourceUpdated(uri) { events.emit({ type: "resource", uri }); return handler.notify.resourceUpdated(uri); },
|
|
105
|
+
resourcesChanged() { events.emit({ type: "resources" }); return handler.notify.resourcesChanged(); },
|
|
106
|
+
toolsChanged() { events.emit({ type: "tools" }); return handler.notify.toolsChanged(); },
|
|
107
|
+
});
|
|
90
108
|
const requests = new Set();
|
|
91
109
|
let sandbox;
|
|
92
110
|
const web = createServer(async (req, res) => {
|
|
@@ -107,7 +125,30 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
107
125
|
}
|
|
108
126
|
if (route === "/host.json" && req.method === "GET") {
|
|
109
127
|
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
110
|
-
res.end(JSON.stringify({ sandboxUrl: sandbox?.url }));
|
|
128
|
+
res.end(JSON.stringify({ sandboxUrl: sandbox?.url, ...(sandbox?.delivery ? { httpPreview: true } : {}) }));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (route === "/preview-http" && req.method === "POST" && sandbox?.delivery) {
|
|
132
|
+
const abort = new AbortController(); requests.add(abort);
|
|
133
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
134
|
+
try {
|
|
135
|
+
let body = "";
|
|
136
|
+
for await (const chunk of req) { body += chunk; if (body.length > 4096) throw new Error("HTTP preview request too large."); }
|
|
137
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
138
|
+
if (!service?.capturePreview) throw new Error("The scoped preview reader is unavailable.");
|
|
139
|
+
const result = await sandbox.delivery.control(mount?.[0] ?? "/", service, JSON.parse(body), abort.signal);
|
|
140
|
+
abort.signal.throwIfAborted();
|
|
141
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(result));
|
|
142
|
+
} catch (error) { if (!abort.signal.aborted && !res.destroyed) { res.writeHead(400, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify({ error: error.message, code: error.code })); } }
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (route.startsWith("/api/") && sandbox?.delivery) {
|
|
146
|
+
if (route === "/api/events" && req.method === "GET") { events.connect(res, mount?.[0] ?? "/"); return; }
|
|
147
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
148
|
+
if (!service) { res.writeHead(503); res.end("Showcase service unavailable."); return; }
|
|
149
|
+
const abort = new AbortController(); requests.add(abort);
|
|
150
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
151
|
+
await timing.timeStage(`showcase-api:${req.method} ${route.slice(5).replace(/^drafts\/[^/]+\//, "drafts/*/")}`, () => serveShowcaseHttp(req, res, route.slice(5) + url.search, service, abort.signal));
|
|
111
152
|
return;
|
|
112
153
|
}
|
|
113
154
|
const asset = assets.get(route);
|
|
@@ -118,7 +159,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
118
159
|
"X-Content-Type-Options": "nosniff",
|
|
119
160
|
"Content-Security-Policy": `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; frame-src ${sandbox ? new URL(sandbox.url).origin : "'none'"};connect-src 'self';object-src 'none'`,
|
|
120
161
|
});
|
|
121
|
-
res.end(asset
|
|
162
|
+
res.end(route === "/" && sandbox?.delivery && !["blob", "mcp"].includes(url.searchParams.get("delivery")) ? asset.bytes.toString().replace('src="client.js"', 'src="http-client.js"') : asset.bytes);
|
|
122
163
|
return;
|
|
123
164
|
}
|
|
124
165
|
if (route !== "/mcp") {
|
|
@@ -182,12 +223,19 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
182
223
|
let closing;
|
|
183
224
|
return {
|
|
184
225
|
url: `http://127.0.0.1:${web.address().port}/`,
|
|
226
|
+
buildChanged(report) { if (sandbox?.delivery) publishBuild("ads://project/build", report); },
|
|
185
227
|
/** Serve another MCP server's showcase under a path prefix such as /draft/<id>/. */
|
|
186
|
-
mount(prefix, mountFactory) {
|
|
228
|
+
mount(prefix, mountFactory, service) {
|
|
187
229
|
const mounted = createEndpoint(mountFactory);
|
|
188
230
|
mounts.set(prefix, mounted);
|
|
231
|
+
services.set(prefix, service);
|
|
232
|
+
const draft = /^\/draft\/([a-zA-Z0-9_-]+)\/$/.exec(prefix);
|
|
233
|
+
const buildUri = draft && `ads://drafts/${draft[1]}/resource?uri=${encodeURIComponent("ads://project/build")}`;
|
|
234
|
+
const unsubscribe = sandbox?.delivery && buildUri ? service?.onBuildChange?.(report => publishBuild(buildUri, report)) : undefined;
|
|
235
|
+
if (unsubscribe) buildSubscriptions.set(mounted, unsubscribe);
|
|
189
236
|
return async () => {
|
|
190
|
-
|
|
237
|
+
unsubscribe?.(); buildSubscriptions.delete(mounted); buildReports.delete(buildUri);
|
|
238
|
+
if (mounts.get(prefix) === mounted) { mounts.delete(prefix); services.delete(prefix); sandbox?.delivery?.retireOwner(prefix); }
|
|
191
239
|
await mounted.close();
|
|
192
240
|
};
|
|
193
241
|
},
|
|
@@ -196,6 +244,9 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
196
244
|
// Close sockets first: live subscriptions and preview requests must not
|
|
197
245
|
// hold shutdown open while protocol instances wait for cancellation.
|
|
198
246
|
const stopped = new Promise((resolve) => web.close(resolve));
|
|
247
|
+
events.close();
|
|
248
|
+
for (const unsubscribe of buildSubscriptions.values()) unsubscribe();
|
|
249
|
+
buildSubscriptions.clear(); buildReports.clear();
|
|
199
250
|
for (const request of requests) request.abort();
|
|
200
251
|
web.closeAllConnections();
|
|
201
252
|
const results = await Promise.allSettled([
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { httpPreviewAction, httpResourceUri } from "../showcase-http-routes.mjs";
|
|
2
|
+
|
|
3
|
+
/** HTTP presentation adapter over the same scoped services used by CLI/MCP. */
|
|
4
|
+
export async function serveShowcaseHttp(req, res, path, service, signal) {
|
|
5
|
+
try {
|
|
6
|
+
if (req.method === "GET") {
|
|
7
|
+
const uri = httpResourceUri(path);
|
|
8
|
+
const result = await service.readResource(uri, signal);
|
|
9
|
+
signal.throwIfAborted();
|
|
10
|
+
const content = result.contents?.find(item => typeof item.text === "string");
|
|
11
|
+
if (!content) throw new Error("The showcase resource contains no JSON data.");
|
|
12
|
+
JSON.parse(content.text);
|
|
13
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
14
|
+
res.end(content.text);
|
|
15
|
+
} else if (req.method === "POST") {
|
|
16
|
+
const chunks = []; let size = 0;
|
|
17
|
+
for await (const chunk of req) {
|
|
18
|
+
size += chunk.length;
|
|
19
|
+
if (size > 4096) throw new Error("Showcase action request too large.");
|
|
20
|
+
chunks.push(chunk);
|
|
21
|
+
}
|
|
22
|
+
const action = httpPreviewAction(path, JSON.parse(Buffer.concat(chunks).toString()));
|
|
23
|
+
// Tool schema parsing, read-only policy and exact revision gates stay in the service.
|
|
24
|
+
const result = await service.callTool(action.name, action.arguments, signal);
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
if (result.isError) throw Object.assign(new Error(result.content?.find(item => item.type === "text")?.text ?? "Preview failed."), result.structuredContent?.failure);
|
|
27
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
28
|
+
res.end(JSON.stringify(result.structuredContent));
|
|
29
|
+
} else {
|
|
30
|
+
res.writeHead(405, { Allow: "GET, POST" }); res.end();
|
|
31
|
+
}
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (signal.aborted || res.destroyed) return;
|
|
34
|
+
res.writeHead(400, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
35
|
+
res.end(JSON.stringify({ error: { message: error.message, code: error.code, category: error.category, resourceUri: error.resourceUri } }));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function showcaseHttpEvents() {
|
|
40
|
+
const clients = new Set();
|
|
41
|
+
return {
|
|
42
|
+
emit(event) {
|
|
43
|
+
for (const client of clients) {
|
|
44
|
+
let value = event;
|
|
45
|
+
if (client.scope && ["resource", "build"].includes(event.type)) {
|
|
46
|
+
if (!event.uri.startsWith(client.scope)) continue;
|
|
47
|
+
value = { ...event, uri: decodeURIComponent(event.uri.slice(client.scope.length)) };
|
|
48
|
+
}
|
|
49
|
+
// Bound slow readers instead of accumulating event buffers indefinitely.
|
|
50
|
+
if (!client.res.write(`data: ${JSON.stringify(value)}\n\n`)) client.res.destroy();
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
connect(res, prefix) {
|
|
54
|
+
if (clients.size >= 64) { res.writeHead(503); res.end("Too many showcase event streams."); return; }
|
|
55
|
+
const draft = /^\/draft\/([a-zA-Z0-9_-]+)\/$/.exec(prefix);
|
|
56
|
+
const client = { res, scope: draft && `ads://drafts/${draft[1]}/resource?uri=` };
|
|
57
|
+
clients.add(client);
|
|
58
|
+
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
|
|
59
|
+
res.write('data: {"type":"ready"}\n\n');
|
|
60
|
+
const timer = setInterval(() => { if (!res.write(": heartbeat\n\n")) res.destroy(); }, 15000);
|
|
61
|
+
timer.unref();
|
|
62
|
+
res.once("close", () => { clearInterval(timer); clients.delete(client); });
|
|
63
|
+
},
|
|
64
|
+
close() { for (const client of clients) client.res.destroy(); clients.clear(); },
|
|
65
|
+
};
|
|
66
|
+
}
|
package/dist/preview-inputs.mjs
CHANGED
|
@@ -3,14 +3,19 @@ import path from "node:path";
|
|
|
3
3
|
import { isScenarioFile } from "./config.mjs";
|
|
4
4
|
import { scenarioGroupFingerprint } from "./scenario-groups.mjs";
|
|
5
5
|
import { validationInputFiles } from "./validation-inputs.mjs";
|
|
6
|
+
import timing from "./stage-timing.cjs";
|
|
6
7
|
|
|
7
8
|
/** Shared source evidence for compilation, watch recovery and status reads. */
|
|
8
|
-
|
|
9
|
+
/** `fence`: { fresh } re-walks after long work; { observed } pairs the walk with external evidence. */
|
|
10
|
+
export function previewSourceRevision(options,apps=[],fence={}){
|
|
11
|
+
return timing.timeStage("preview-source-revision", () => sourceRevision(options,apps,fence));
|
|
12
|
+
}
|
|
13
|
+
async function sourceRevision(options,apps,fence){
|
|
9
14
|
const {root} = options;
|
|
10
15
|
const rows = [];
|
|
11
16
|
const scenarios = [];
|
|
12
17
|
const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
|
|
13
|
-
for (const [relative,digest] of Object.entries(await validationInputFiles(options))){
|
|
18
|
+
for (const [relative,digest] of Object.entries(await validationInputFiles(options,[],fence))){
|
|
14
19
|
const file=path.resolve(root,relative);
|
|
15
20
|
if (outputs.has(file)) continue;
|
|
16
21
|
rows.push([relative,digest]);
|
|
@@ -121,7 +121,7 @@ export async function prepareScenarioRegistryTransfer(candidate, target) {
|
|
|
121
121
|
registry = read(candidate, revision);
|
|
122
122
|
if (!registry) return null;
|
|
123
123
|
return async () => {
|
|
124
|
-
if ((await previewSourceRevision(target)) !== revision || !validRegistry(registry, target)) return false;
|
|
124
|
+
if ((await previewSourceRevision(target, [], { fresh: true })) !== revision || !validRegistry(registry, target)) return false;
|
|
125
125
|
write(target, revision, registry);
|
|
126
126
|
return true;
|
|
127
127
|
};
|
|
@@ -140,7 +140,7 @@ export async function discoverScenarioRegistry(options) {
|
|
|
140
140
|
const cached = read(current, revision);
|
|
141
141
|
if (cached) return cached;
|
|
142
142
|
const registry = await inspectScenarios(current, await programFor(current.root).build(current));
|
|
143
|
-
if (revision !== (await previewSourceRevision(loadConfig(current.root)))) continue;
|
|
143
|
+
if (revision !== (await previewSourceRevision(loadConfig(current.root), [], { fresh: true }))) continue;
|
|
144
144
|
write(current, revision, registry);
|
|
145
145
|
return registry;
|
|
146
146
|
}
|
|
@@ -476,6 +476,12 @@ export async function runScenarioCompiler(directory, setup) {
|
|
|
476
476
|
const root = path.resolve(directory);
|
|
477
477
|
const { watched = false, validate, buildGraph, compilerFiles = [], context = {} } = typeof setup === "function" ? setup(root) : setup;
|
|
478
478
|
if (typeof buildGraph !== "function") throw new Error("runScenarioCompiler needs buildGraph: previews compile into one shared resource graph.");
|
|
479
|
+
const draftWorkspace = watched && isDraftPreviewWorkspace(root);
|
|
480
|
+
const retired = () => draftWorkspace && !existsSync(root);
|
|
481
|
+
async function retiredStartup() {
|
|
482
|
+
await buildGraph.close?.();
|
|
483
|
+
return { async stop() {} };
|
|
484
|
+
}
|
|
479
485
|
const control = process.env.ADS_MCP_DRAFT_CONTROL,
|
|
480
486
|
hosting = watched && !context.session && control && existsSync(path.dirname(control));
|
|
481
487
|
const scheduler = hosting ? createScheduler() : null;
|
|
@@ -492,6 +498,9 @@ export async function runScenarioCompiler(directory, setup) {
|
|
|
492
498
|
async function registry() {
|
|
493
499
|
options = withPreviewSession(loadConfig(root), buildSession);
|
|
494
500
|
const result = await analyze(root, "registry");
|
|
501
|
+
// Acceptance/drop may retire a draft while asynchronous discovery is running.
|
|
502
|
+
// Never recreate its workspace by publishing a late registry result.
|
|
503
|
+
if (retired()) return [];
|
|
495
504
|
if (result.diagnostics.length)
|
|
496
505
|
throw Object.assign(new Error(result.diagnostics.map((item) => `${item.file}: ${item.message}`).join("\n")), { scenarios: result.scenarios });
|
|
497
506
|
writeRegistryManifest(root, result.scenarios);
|
|
@@ -508,6 +517,7 @@ export async function runScenarioCompiler(directory, setup) {
|
|
|
508
517
|
} finally {
|
|
509
518
|
if (watched) releaseScenarioRegistry(root);
|
|
510
519
|
}
|
|
520
|
+
if (retired()) return retiredStartup();
|
|
511
521
|
const buildApps = () => entries.map((entry) => ({ id: entry.id, file: previewArtifactPath(options, entry.artifact) }));
|
|
512
522
|
const reporter = createBuildReporter(root, {
|
|
513
523
|
apps: buildApps(),
|
|
@@ -553,7 +563,15 @@ export async function runScenarioCompiler(directory, setup) {
|
|
|
553
563
|
let publishedStamp;
|
|
554
564
|
let publishedEntries = new Set();
|
|
555
565
|
let validation;
|
|
556
|
-
let observedSourceRevision
|
|
566
|
+
let observedSourceRevision;
|
|
567
|
+
try {
|
|
568
|
+
observedSourceRevision = await previewSourceRevision(options);
|
|
569
|
+
} catch (error) {
|
|
570
|
+
if (retired()) return retiredStartup();
|
|
571
|
+
await buildGraph.close?.();
|
|
572
|
+
throw error;
|
|
573
|
+
}
|
|
574
|
+
if (retired()) return retiredStartup();
|
|
557
575
|
let invalidation;
|
|
558
576
|
let fullRequest, completedFull;
|
|
559
577
|
// Keep the registry inspector warm while previews are in use: a cold TypeScript program costs ~1.7 s per edit.
|