@reqvire-org/ads 0.4.4 → 0.4.5
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/cli.mjs +1 -1
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/drafts.mjs +7 -0
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- 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 +25 -1
- package/dist/mcp/showcase-host.mjs +55 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- 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/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +48 -42
- package/docs/CHANGELOG.md +65 -0
- 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
|
@@ -813,6 +813,21 @@ export async function createAdsMcp(
|
|
|
813
813
|
}
|
|
814
814
|
const tokenInventory = () => analyze(root, "tokens");
|
|
815
815
|
const behaviorInventory = (args) => analyze(root, "behavior-page", [args]);
|
|
816
|
+
// Internal HTTP publication captures one authorized graph and keeps its asset
|
|
817
|
+
// lookup bound to that scope/revision. No client-supplied graph is trusted.
|
|
818
|
+
async function capturePreview(uri, signal) {
|
|
819
|
+
signal?.throwIfAborted();
|
|
820
|
+
if (uri.startsWith("ads://drafts/")) {
|
|
821
|
+
const url = new URL(uri), match = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
|
|
822
|
+
if (!match || [...url.searchParams.keys()].some(key => key !== "uri") || !url.searchParams.get("uri")) throw new Error("Invalid draft resource address.");
|
|
823
|
+
return drafts.capturePreview(match[1], url.searchParams.get("uri"), signal);
|
|
824
|
+
}
|
|
825
|
+
if (![PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI].includes(uri)) throw new Error("Invalid preview manifest resource.");
|
|
826
|
+
const options = uri === LIVE_PREVIEW_MANIFEST_URI ? livePreviewOptions(previewOptions()) : previewOptions();
|
|
827
|
+
const graph = JSON.parse((await read(uri, signal)).contents[0].text);
|
|
828
|
+
signal?.throwIfAborted();
|
|
829
|
+
return { graph, readAsset: id => { signal?.throwIfAborted(); return readPreviewAsset(options, id, graph); } };
|
|
830
|
+
}
|
|
816
831
|
async function read(uri, signal) {
|
|
817
832
|
if (uri === `${PROJECT_URI}/explorer`)
|
|
818
833
|
return {
|
|
@@ -2395,6 +2410,7 @@ export async function createAdsMcp(
|
|
|
2395
2410
|
return previewWatch.buildAll(signal, options);
|
|
2396
2411
|
},
|
|
2397
2412
|
readResource: read,
|
|
2413
|
+
capturePreview,
|
|
2398
2414
|
async callTool(name, args, signal) {
|
|
2399
2415
|
const tool = tools().find((tool) => tool.name === name);
|
|
2400
2416
|
if (!tool) throw new Error("Unknown preview tool.");
|
|
@@ -2487,6 +2503,12 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2487
2503
|
}),
|
|
2488
2504
|
})
|
|
2489
2505
|
).server,
|
|
2506
|
+
{
|
|
2507
|
+
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2508
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2509
|
+
onBuildChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
2510
|
+
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2511
|
+
},
|
|
2490
2512
|
);
|
|
2491
2513
|
return {
|
|
2492
2514
|
url,
|
|
@@ -2509,6 +2531,7 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2509
2531
|
},
|
|
2510
2532
|
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2511
2533
|
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2534
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2512
2535
|
// The draft's verified preview revision, as the project host reports its own: captures and
|
|
2513
2536
|
// behavior evidence record which build they observed.
|
|
2514
2537
|
previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
|
|
@@ -2564,10 +2587,11 @@ export async function startAdsMcp(
|
|
|
2564
2587
|
let buildWatcher, buildChangeTimer;
|
|
2565
2588
|
const buildListeners = new Set();
|
|
2566
2589
|
const onBuildChange = (report) => {
|
|
2590
|
+
host?.buildChanged(report);
|
|
2567
2591
|
for (const listener of buildListeners) listener(report);
|
|
2568
2592
|
};
|
|
2569
2593
|
const showcaseUrl = () => host?.url;
|
|
2570
|
-
const mountPreview = (prefix, factory) => host?.mount(prefix, factory);
|
|
2594
|
+
const mountPreview = (prefix, factory, service) => host?.mount(prefix, factory, service);
|
|
2571
2595
|
if (showcase) {
|
|
2572
2596
|
// A 2025-era HTTP session observes the project like a stdio connection; per-request modern instances do not.
|
|
2573
2597
|
host = await startShowcaseHost(
|
|
@@ -4,6 +4,7 @@ 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";
|
|
8
9
|
|
|
9
10
|
const maxRequestBodySize = 2 * 1024 * 1024,
|
|
@@ -73,6 +74,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
73
74
|
[
|
|
74
75
|
["/", "index.html", "text/html"],
|
|
75
76
|
["/client.js", "client.bundle.js", "text/javascript"],
|
|
77
|
+
["/http-client.js", "http-client.bundle.js", "text/javascript"],
|
|
76
78
|
["/style.css", "style.css", "text/css"],
|
|
77
79
|
["/ui.css", "ui/ui.css", "text/css"],
|
|
78
80
|
["/favicon.svg", "favicon.svg", "image/svg+xml"],
|
|
@@ -86,7 +88,22 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
86
88
|
// Draft previews are served from this same host under /draft/<id>/: the same client, with that
|
|
87
89
|
// draft's own MCP endpoint. No other port or process.
|
|
88
90
|
const mounts = new Map();
|
|
89
|
-
const
|
|
91
|
+
const services = new Map();
|
|
92
|
+
const events = showcaseHttpEvents();
|
|
93
|
+
const buildReports = new Map();
|
|
94
|
+
const buildSubscriptions = new Map();
|
|
95
|
+
function publishBuild(uri, report) {
|
|
96
|
+
const signature = JSON.stringify(report);
|
|
97
|
+
if (buildReports.get(uri) === signature) return;
|
|
98
|
+
buildReports.set(uri, signature);
|
|
99
|
+
events.emit({ type: "build", uri, report });
|
|
100
|
+
}
|
|
101
|
+
const observer = await observe?.({
|
|
102
|
+
...handler.notify,
|
|
103
|
+
resourceUpdated(uri) { events.emit({ type: "resource", uri }); return handler.notify.resourceUpdated(uri); },
|
|
104
|
+
resourcesChanged() { events.emit({ type: "resources" }); return handler.notify.resourcesChanged(); },
|
|
105
|
+
toolsChanged() { events.emit({ type: "tools" }); return handler.notify.toolsChanged(); },
|
|
106
|
+
});
|
|
90
107
|
const requests = new Set();
|
|
91
108
|
let sandbox;
|
|
92
109
|
const web = createServer(async (req, res) => {
|
|
@@ -107,7 +124,30 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
107
124
|
}
|
|
108
125
|
if (route === "/host.json" && req.method === "GET") {
|
|
109
126
|
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
110
|
-
res.end(JSON.stringify({ sandboxUrl: sandbox?.url }));
|
|
127
|
+
res.end(JSON.stringify({ sandboxUrl: sandbox?.url, ...(sandbox?.delivery ? { httpPreview: true } : {}) }));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (route === "/preview-http" && req.method === "POST" && sandbox?.delivery) {
|
|
131
|
+
const abort = new AbortController(); requests.add(abort);
|
|
132
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
133
|
+
try {
|
|
134
|
+
let body = "";
|
|
135
|
+
for await (const chunk of req) { body += chunk; if (body.length > 4096) throw new Error("HTTP preview request too large."); }
|
|
136
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
137
|
+
if (!service?.capturePreview) throw new Error("The scoped preview reader is unavailable.");
|
|
138
|
+
const result = await sandbox.delivery.control(mount?.[0] ?? "/", service, JSON.parse(body), abort.signal);
|
|
139
|
+
abort.signal.throwIfAborted();
|
|
140
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(result));
|
|
141
|
+
} 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 })); } }
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (route.startsWith("/api/") && sandbox?.delivery) {
|
|
145
|
+
if (route === "/api/events" && req.method === "GET") { events.connect(res, mount?.[0] ?? "/"); return; }
|
|
146
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
147
|
+
if (!service) { res.writeHead(503); res.end("Showcase service unavailable."); return; }
|
|
148
|
+
const abort = new AbortController(); requests.add(abort);
|
|
149
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
150
|
+
await serveShowcaseHttp(req, res, route.slice(5) + url.search, service, abort.signal);
|
|
111
151
|
return;
|
|
112
152
|
}
|
|
113
153
|
const asset = assets.get(route);
|
|
@@ -118,7 +158,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
118
158
|
"X-Content-Type-Options": "nosniff",
|
|
119
159
|
"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
160
|
});
|
|
121
|
-
res.end(asset
|
|
161
|
+
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
162
|
return;
|
|
123
163
|
}
|
|
124
164
|
if (route !== "/mcp") {
|
|
@@ -182,12 +222,19 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
182
222
|
let closing;
|
|
183
223
|
return {
|
|
184
224
|
url: `http://127.0.0.1:${web.address().port}/`,
|
|
225
|
+
buildChanged(report) { if (sandbox?.delivery) publishBuild("ads://project/build", report); },
|
|
185
226
|
/** Serve another MCP server's showcase under a path prefix such as /draft/<id>/. */
|
|
186
|
-
mount(prefix, mountFactory) {
|
|
227
|
+
mount(prefix, mountFactory, service) {
|
|
187
228
|
const mounted = createEndpoint(mountFactory);
|
|
188
229
|
mounts.set(prefix, mounted);
|
|
230
|
+
services.set(prefix, service);
|
|
231
|
+
const draft = /^\/draft\/([a-zA-Z0-9_-]+)\/$/.exec(prefix);
|
|
232
|
+
const buildUri = draft && `ads://drafts/${draft[1]}/resource?uri=${encodeURIComponent("ads://project/build")}`;
|
|
233
|
+
const unsubscribe = sandbox?.delivery && buildUri ? service?.onBuildChange?.(report => publishBuild(buildUri, report)) : undefined;
|
|
234
|
+
if (unsubscribe) buildSubscriptions.set(mounted, unsubscribe);
|
|
189
235
|
return async () => {
|
|
190
|
-
|
|
236
|
+
unsubscribe?.(); buildSubscriptions.delete(mounted); buildReports.delete(buildUri);
|
|
237
|
+
if (mounts.get(prefix) === mounted) { mounts.delete(prefix); services.delete(prefix); sandbox?.delivery?.retireOwner(prefix); }
|
|
191
238
|
await mounted.close();
|
|
192
239
|
};
|
|
193
240
|
},
|
|
@@ -196,6 +243,9 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
196
243
|
// Close sockets first: live subscriptions and preview requests must not
|
|
197
244
|
// hold shutdown open while protocol instances wait for cancellation.
|
|
198
245
|
const stopped = new Promise((resolve) => web.close(resolve));
|
|
246
|
+
events.close();
|
|
247
|
+
for (const unsubscribe of buildSubscriptions.values()) unsubscribe();
|
|
248
|
+
buildSubscriptions.clear(); buildReports.clear();
|
|
199
249
|
for (const request of requests) request.abort();
|
|
200
250
|
web.closeAllConnections();
|
|
201
251
|
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
|
+
}
|
|
@@ -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.
|