@stacksjs/docs 0.75.663 → 0.75.667

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.
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- import{createHash as ze}from"crypto";import{lstat as U,mkdir as z,mkdtemp as fe,readFile as M,rename as K,rm as q,rmdir as Ke,stat as Ge}from"fs/promises";import{tmpdir as Qe}from"os";import{dirname as pe,isAbsolute as ue,join as g,relative as B,resolve as S}from"path";import{pathToFileURL as Xe}from"url";function X(e){let o=`:is(${['input[type="password"]',...e].join(",")})`,a=`${o}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
- ${o}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
- ${a}, ${a}::selection {
2
+ import{createHash as Ke}from"crypto";import{lstat as U,mkdir as z,mkdtemp as fe,readFile as M,rename as K,rm as q,rmdir as Ge,stat as Qe}from"fs/promises";import{tmpdir as Xe}from"os";import{dirname as pe,isAbsolute as ue,join as g,relative as B,resolve as v}from"path";import{pathToFileURL as Ye}from"url";function X(e){let i=`:is(${['input[type="password"]',...e].join(",")})`,n=`${i}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
+ ${i}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
+ ${n}, ${n}::selection {
5
5
  color: transparent !important;
6
6
  -webkit-text-fill-color: transparent !important;
7
7
  -webkit-text-stroke: 0 transparent !important;
@@ -9,10 +9,10 @@ ${a}, ${a}::selection {
9
9
  caret-color: transparent !important;
10
10
  forced-color-adjust: none !important;
11
11
  }
12
- ${a}::selection { background: transparent !important; }
13
- ${a}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
- ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
15
- `}import{join as we}from"path";import{launch as ge}from"@stacksjs/testing/browser";function Y(e,o){let a=we(e,"stx-b-");return o!=="win32"&&Buffer.byteLength(a)+6>60?"/tmp/stx-b-":a}function D(e){let o,a;return{async view(t,c){if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");if(e==="webkit")return new Bun.WebView({width:t,height:c,backend:e});if(!a){let f=await ge({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let p=`127.0.0.1:${f.port}`,u=await fetch(`http://${p}/json/version`,{signal:AbortSignal.timeout(5000)});if(!u.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${u.status})`);let m=await u.json(),i=URL.parse(m.webSocketDebuggerUrl||"");if(i?.protocol!=="ws:"||i.host!==p||!i.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");a=i.href,o=f}catch(p){throw await f.close(),p}}return new Bun.WebView({width:t,height:c,backend:{type:"chrome",url:a}})},async close(){try{await o?.close()}finally{o=void 0,a=void 0}}}}import{createHash as ye}from"crypto";import{readFile as be}from"fs/promises";import{existsSync as Se}from"fs";import{isAbsolute as ve,join as ke,relative as xe,resolve as $e}from"path";import{loadModelRegistry as Ee,modelFiles as Z}from"@stacksjs/orm/model-registry";function V(e){let o=Object.entries(e).map(([r,n])=>{let d=Object.entries(n.attributes??{}),h=n.belongsTo??[],x=(Array.isArray(h)?h:Object.values(h)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),b=n.traits?.useApi,E=n.traits?.useSeeder??n.traits?.seedable,j=(w,v)=>Boolean(v.hidden||v.encrypted||v.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),O=d.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(n.name??r),table:n.table,primaryKey:String(n.primaryKey??"id"),...b?.uri?{api:String(b.uri)}:{},parents:[...new Set([...x,...Array.isArray(E?.after)?E.after.map(String):[]])].sort(),seederCount:typeof E?.count==="number"?E.count:null,factoryFields:d.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:d.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:O,sensitiveFields:d.filter(([w,v])=>j(w,v)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...b?.routes?.includes("show")?["detail"]:[],...b?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((r,n)=>r.name.localeCompare(n.name)),a=new Set(o.map((r)=>r.name)),t=new Map(o.map((r)=>[r.name,r])),c=[];for(;;){let r=[...t.values()].filter((n)=>n.parents.every((d)=>!a.has(d)||c.includes(d)));if(!r.length)break;for(let n of r)c.push(n.name),t.delete(n.name)}let f=new Set,p=new Map,u=new Map,m=[],i=new Set,s=0;function l(r){p.set(r,s),u.set(r,s++),m.push(r),i.add(r);for(let h of t.get(r)?.parents??[]){if(!t.has(h))continue;if(!p.has(h))l(h),u.set(r,Math.min(u.get(r),u.get(h)));else if(i.has(h))u.set(r,Math.min(u.get(r),p.get(h)))}if(u.get(r)!==p.get(r))return;let n=[],d;do d=m.pop(),i.delete(d),n.push(d);while(d!==r);if(n.length>1||t.get(r)?.parents.includes(r))for(let h of n)f.add(h)}for(let r of t.keys())if(!p.has(r))l(r);return{models:o,creationOrder:c,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(o.flatMap((r)=>r.parents).filter((r)=>!a.has(r)))].sort()}}async function H(e,o={}){if(o===!1)return V({});if(o.directory!==void 0&&!o.directory.trim())throw Error("Model directory must not be empty");let a=$e(e,o.directory??"app/Models");if(ve(o.directory??"")||xe(e,a).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=o.includeDefaults?ke(e,"storage/framework/defaults/app/Models"):void 0;if(!Se(a)&&!t)return V({});let c=[],f=await Ee({userRoot:a,defaultsRoot:t,onImportError:(m)=>c.push(m)});if(c.length)throw Error(`Cannot inspect screenshot models: ${c.join(", ")}`);let p=V(f),u=[...Z(a),...t?Z(t):[]].sort();return p.sourceHash=ye("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>be(m))))).digest("hex"),p}function W(e,o,a,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let c=o?t.models.filter((u)=>u.name===o):t.models.filter((u)=>u.api&&e.replace(/^\//,"").startsWith(`${u.api.replace(/^\//,"")}/`)),f=c.length===1?c[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=a[f.name];if(!p)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,m,i)=>{let s=m||i,l=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(l)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=p[l];if(r===void 0||r===""||typeof r!=="string"&&typeof r!=="number"||typeof r==="number"&&!Number.isFinite(r))throw Error(`Screenshot fixture ${f.name} has no ${s}`);return encodeURIComponent(String(r))})}import{Mp4Muxer as Pe}from"@ts-videos/mp4";import{BufferTarget as Me}from"ts-videos";function ee(e={}){let o=Bun.serve({port:0,hostname:"127.0.0.1",fetch(a){let t=e[new URL(a.url).pathname];if(t)return new Response(Bun.file(t),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${o.port}/`,stop:()=>{o.stop(!0)}}}var Oe=["6400","4d00","42e0"],je=(e)=>`(() => {
12
+ ${n}::selection { background: transparent !important; }
13
+ ${n}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
+ ${n}::-webkit-search-cancel-button { visibility: hidden !important; }
15
+ `}import{join as ge}from"path";import{launch as ye}from"@stacksjs/testing/browser";function Y(e,i){let n=ge(e,"stx-b-");return i!=="win32"&&Buffer.byteLength(n)+6>60?"/tmp/stx-b-":n}function D(e){let i,n;return{async view(t,c){if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");if(e==="webkit")return new Bun.WebView({width:t,height:c,backend:e});if(!n){let f=await ye({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let p=`127.0.0.1:${f.port}`,u=await fetch(`http://${p}/json/version`,{signal:AbortSignal.timeout(5000)});if(!u.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${u.status})`);let m=await u.json(),o=URL.parse(m.webSocketDebuggerUrl||"");if(o?.protocol!=="ws:"||o.host!==p||!o.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");n=o.href,i=f}catch(p){throw await f.close(),p}}return new Bun.WebView({width:t,height:c,backend:{type:"chrome",url:n}})},async close(){try{await i?.close()}finally{i=void 0,n=void 0}}}}import{createHash as be}from"crypto";import{readFile as ve}from"fs/promises";import{existsSync as Se}from"fs";import{isAbsolute as ke,join as xe,relative as $e,resolve as Ee}from"path";import{loadModelRegistry as Pe,modelFiles as Z}from"@stacksjs/orm/model-registry";function V(e){let i=Object.entries(e).map(([r,a])=>{let d=Object.entries(a.attributes??{}),h=a.belongsTo??[],x=(Array.isArray(h)?h:Object.values(h)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),b=a.traits?.useApi,E=a.traits?.useSeeder??a.traits?.seedable,j=(w,S)=>Boolean(S.hidden||S.encrypted||S.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),O=d.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(a.name??r),table:a.table,primaryKey:String(a.primaryKey??"id"),...b?.uri?{api:String(b.uri)}:{},parents:[...new Set([...x,...Array.isArray(E?.after)?E.after.map(String):[]])].sort(),seederCount:typeof E?.count==="number"?E.count:null,factoryFields:d.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:d.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:O,sensitiveFields:d.filter(([w,S])=>j(w,S)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...b?.routes?.includes("show")?["detail"]:[],...b?.middleware?.length?["permission-denied"]:[],...a.traits?.useSoftDeletes||a.traits?.softDeletable?["archived"]:[]])]}}).sort((r,a)=>r.name.localeCompare(a.name)),n=new Set(i.map((r)=>r.name)),t=new Map(i.map((r)=>[r.name,r])),c=[];for(;;){let r=[...t.values()].filter((a)=>a.parents.every((d)=>!n.has(d)||c.includes(d)));if(!r.length)break;for(let a of r)c.push(a.name),t.delete(a.name)}let f=new Set,p=new Map,u=new Map,m=[],o=new Set,s=0;function l(r){p.set(r,s),u.set(r,s++),m.push(r),o.add(r);for(let h of t.get(r)?.parents??[]){if(!t.has(h))continue;if(!p.has(h))l(h),u.set(r,Math.min(u.get(r),u.get(h)));else if(o.has(h))u.set(r,Math.min(u.get(r),p.get(h)))}if(u.get(r)!==p.get(r))return;let a=[],d;do d=m.pop(),o.delete(d),a.push(d);while(d!==r);if(a.length>1||t.get(r)?.parents.includes(r))for(let h of a)f.add(h)}for(let r of t.keys())if(!p.has(r))l(r);return{models:i,creationOrder:c,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(i.flatMap((r)=>r.parents).filter((r)=>!n.has(r)))].sort()}}async function H(e,i={}){if(i===!1)return V({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let n=Ee(e,i.directory??"app/Models");if(ke(i.directory??"")||$e(e,n).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=i.includeDefaults?xe(e,"storage/framework/defaults/app/Models"):void 0;if(!Se(n)&&!t)return V({});let c=[],f=await Pe({userRoot:n,defaultsRoot:t,onImportError:(m)=>c.push(m)});if(c.length)throw Error(`Cannot inspect screenshot models: ${c.join(", ")}`);let p=V(f),u=[...Z(n),...t?Z(t):[]].sort();return p.sourceHash=be("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>ve(m))))).digest("hex"),p}function W(e,i,n,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let c=i?t.models.filter((u)=>u.name===i):t.models.filter((u)=>u.api&&e.replace(/^\//,"").startsWith(`${u.api.replace(/^\//,"")}/`)),f=c.length===1?c[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=n[f.name];if(!p)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,m,o)=>{let s=m||o,l=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(l)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=p[l];if(r===void 0||r===""||typeof r!=="string"&&typeof r!=="number"||typeof r==="number"&&!Number.isFinite(r))throw Error(`Screenshot fixture ${f.name} has no ${s}`);return encodeURIComponent(String(r))})}import{Mp4Muxer as Me}from"@ts-videos/mp4";import{BufferTarget as Oe}from"ts-videos";function ee(e={}){let i=Bun.serve({port:0,hostname:"127.0.0.1",fetch(n){let t=e[new URL(n.url).pathname];if(t)return new Response(Bun.file(t),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${i.port}/`,stop:()=>{i.stop(!0)}}}var je=["6400","4d00","42e0"],Fe=(e)=>`(() => {
16
16
  if (window.__stacksFilm) return true
17
17
  const b64 = bytes => { let text = ''; for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(text) }
18
18
  const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
@@ -20,7 +20,7 @@ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
20
20
  if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
21
21
  film.width = width; film.height = height
22
22
  const level = width * height > 2097152 ? '33' : '28'
23
- for (const profile of ${JSON.stringify(Oe)}) {
23
+ for (const profile of ${JSON.stringify(je)}) {
24
24
  const config = { codec: 'avc1.' + profile + level, width, height, bitrate: ${e.bitrate??0} || Math.max(1500000, Math.round(width * height * 3)), framerate: ${e.fps}, avc: { format: 'avc' } }
25
25
  const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
26
26
  if (!support || !support.supported) continue
@@ -107,14 +107,14 @@ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
107
107
  return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
108
108
  }
109
109
  return true
110
- })()`,Fe=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function te(e,o){if(!Number.isInteger(o.fps)||o.fps<1||o.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(je(o));let a=[],t,c={width:0,height:0},f=0,p=async(u)=>{let m=JSON.parse(String(await e(`window.__stacksFilm.drain(${u})`)));if(c={width:m.width,height:m.height},m.description)t=new Uint8Array(Buffer.from(m.description,"base64"));for(let[i,s,l]of m.chunks)a.push([i,s,new Uint8Array(Buffer.from(l,"base64"))])};return{frames:()=>f,async add(u,m){if(!Number.isInteger(m)||m<1)return;let i=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(Fe(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${i}, ${m})`),f+=m,f%(o.fps*20)<m)await p(!1)},async addVideo(u,m=[]){for(let s of m)if(![s.x,s.y,s.size,s.start,s.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(s.color))throw Error("Invalid film mark");let i=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let s=0;s<i.frames;s+=o.fps){let l=Math.min(o.fps,i.frames-s);await e(`window.__stacksFilm.copy(${s}, ${l}, ${JSON.stringify(m)})`),f+=l,await p(!1)}return i.seconds},async finish(){if(await p(!0),!a.length||!t)throw Error("The browser encoded no video");let u=new Me,m=new Pe(u),i=m.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:o.fps,codecDescription:t});for(let[s,l,r]of a)await m.writePacket(i.id,{data:r,timestamp:l/1e6,duration:1/o.fps,isKeyframe:s===1});return await m.finalize(),u.buffer}}}import{createHash as Re}from"crypto";import{lstat as Te,mkdir as Be,readFile as re,rename as se}from"fs/promises";import{dirname as Ne,isAbsolute as Ce,join as L,relative as Ue,resolve as ie}from"path";var oe="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",ne=(e)=>Re("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),T=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function ae(e,o,a,t){if(e){let c=e.secondsPerScreen??2;if(!Number.isFinite(c)||c<0.2||c>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let f of e.viewports??[])if(!t.some((p)=>p.name===f))throw Error(`Unknown film viewport: ${f}`)}if(o){let c=ie(a,o.page);if(Ce(o.page)||Ue(a,c).startsWith("..")||!o.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(o.base)||o.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function J(e,o,a,t,c=process.platform==="darwin"?"webkit":"chrome"){let f=[],p=t.secondsPerScreen??2,u=t.fps??12,m=Math.max(1,Math.round(p*u)),i=D(c),s=ee();try{for(let l of a){if(t.viewports?.length&&!t.viewports.includes(l.name))continue;let r=o.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===l.name);if(!r.length)continue;let n,d;try{d=await i.view(320,240);let y=d;await y.navigate(s.url);let x=await te((b)=>y.evaluate(b),{fps:u,width:l.width,height:l.height});for(let b of r)await x.add(new Uint8Array(await re(L(e,b.file))),m);n=await x.finish()}catch(y){throw Error(`The ${l.name} screens could not be filmed: ${y instanceof Error?y.message.slice(0,400):"the browser failed"}`)}finally{d?.close()}let h=`film-${l.name}.mp4`;await Bun.write(L(e,`${h}.tmp`),n),await se(L(e,`${h}.tmp`),L(e,h)),f.push({viewport:l.name,file:h,sha256:ne(n),screens:r.length,seconds:r.length*m/u})}return f}finally{try{await i.close()}finally{s.stop()}}}function Ae(e,o){let a=o.base.replace(/\/+$/,""),t=o.title??"Screens",c=e.results.filter((i)=>i.status==="captured"&&i.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(o.description??"Every screen of the application, captured automatically from its views.")}`,"---","",oe,"",`# ${T(t)}`,"",`${new Set(c.map((i)=>i.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let i of e.films??[]){let s=c.find((l)=>l.viewport.name===i.viewport);f.push(`## Walkthrough video (${T(i.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${a}/${i.file}`)}"${s?` poster="${N(`${a}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${i.screens} screens in ${Math.round(i.seconds)} seconds. [Download the video](${a}/${i.file}).`,"")}let p=(i)=>i.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",u=new Map;for(let i of e.inventory)u.set(p(i.path),[...u.get(p(i.path))??[],i]);let m=[];for(let[i,s]of[...u].sort(([l],[r])=>l.localeCompare(r))){let l=[];for(let r of s){let n=c.filter((d)=>d.id===r.id);if(!n.length){let d=e.results.find((h)=>h.id===r.id);m.push(`- ${T(r.title)} (\`${r.path}\`): ${r.skip?T(r.skip):d?"the last capture failed.":"not captured yet."}`);continue}l.push(`### ${T(r.title)}`,"",T(n[0].description),"",...n[0].reason?[T(n[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let d of n)l.push("<figure>",` <img src="${N(`${a}/${d.file}`)}" alt="${N(`${d.title}, ${d.viewport.name}`)}" width="${d.viewport.width}" height="${d.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${d.viewport.width}px;height:auto">`,` <figcaption>${N(d.viewport.name)}, ${d.viewport.width} by ${d.viewport.height}${d.profile==="default"?"":`, signed in as ${N(d.profile)}`}</figcaption>`,"</figure>","")}if(l.length)f.push(`## ${T(i[0].toUpperCase()+i.slice(1).replace(/[-_]+/g," "))}`,"",...l)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
110
+ })()`,Re=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function te(e,i){if(!Number.isInteger(i.fps)||i.fps<1||i.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(Fe(i));let n=[],t,c={width:0,height:0},f=0,p=async(u)=>{let m=JSON.parse(String(await e(`window.__stacksFilm.drain(${u})`)));if(c={width:m.width,height:m.height},m.description)t=new Uint8Array(Buffer.from(m.description,"base64"));for(let[o,s,l]of m.chunks)n.push([o,s,new Uint8Array(Buffer.from(l,"base64"))])};return{frames:()=>f,async add(u,m){if(!Number.isInteger(m)||m<1)return;let o=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(Re(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${o}, ${m})`),f+=m,f%(i.fps*20)<m)await p(!1)},async addVideo(u,m=[]){for(let s of m)if(![s.x,s.y,s.size,s.start,s.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(s.color))throw Error("Invalid film mark");let o=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let s=0;s<o.frames;s+=i.fps){let l=Math.min(i.fps,o.frames-s);await e(`window.__stacksFilm.copy(${s}, ${l}, ${JSON.stringify(m)})`),f+=l,await p(!1)}return o.seconds},async finish(){if(await p(!0),!n.length||!t)throw Error("The browser encoded no video");let u=new Oe,m=new Me(u),o=m.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:i.fps,codecDescription:t});for(let[s,l,r]of n)await m.writePacket(o.id,{data:r,timestamp:l/1e6,duration:1/i.fps,isKeyframe:s===1});return await m.finalize(),u.buffer}}}import{createHash as Te}from"crypto";import{lstat as Be,mkdir as Ne,readFile as re,rename as se}from"fs/promises";import{dirname as Ce,isAbsolute as Ue,join as L,relative as Ae,resolve as ie}from"path";var oe="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",ne=(e)=>Te("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),T=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function ae(e,i,n,t){if(e){let c=e.secondsPerScreen??2;if(!Number.isFinite(c)||c<0.2||c>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let f of e.viewports??[])if(!t.some((p)=>p.name===f))throw Error(`Unknown film viewport: ${f}`)}if(i){let c=ie(n,i.page);if(Ue(i.page)||Ae(n,c).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function J(e,i,n,t,c=process.platform==="darwin"?"webkit":"chrome"){let f=[],p=t.secondsPerScreen??2,u=t.fps??12,m=Math.max(1,Math.round(p*u)),o=D(c),s=ee();try{for(let l of n){if(t.viewports?.length&&!t.viewports.includes(l.name))continue;let r=i.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===l.name);if(!r.length)continue;let a,d;try{d=await o.view(320,240);let y=d;await y.navigate(s.url);let x=await te((b)=>y.evaluate(b),{fps:u,width:l.width,height:l.height});for(let b of r)await x.add(new Uint8Array(await re(L(e,b.file))),m);a=await x.finish()}catch(y){throw Error(`The ${l.name} screens could not be filmed: ${y instanceof Error?y.message.slice(0,400):"the browser failed"}`)}finally{d?.close()}let h=`film-${l.name}.mp4`;await Bun.write(L(e,`${h}.tmp`),a),await se(L(e,`${h}.tmp`),L(e,h)),f.push({viewport:l.name,file:h,sha256:ne(a),screens:r.length,seconds:r.length*m/u})}return f}finally{try{await o.close()}finally{s.stop()}}}function De(e,i){let n=i.base.replace(/\/+$/,""),t=i.title??"Screens",c=e.results.filter((o)=>o.status==="captured"&&o.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",oe,"",`# ${T(t)}`,"",`${new Set(c.map((o)=>o.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let o of e.films??[]){let s=c.find((l)=>l.viewport.name===o.viewport);f.push(`## Walkthrough video (${T(o.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${n}/${o.file}`)}"${s?` poster="${N(`${n}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${o.screens} screens in ${Math.round(o.seconds)} seconds. [Download the video](${n}/${o.file}).`,"")}let p=(o)=>o.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",u=new Map;for(let o of e.inventory)u.set(p(o.path),[...u.get(p(o.path))??[],o]);let m=[];for(let[o,s]of[...u].sort(([l],[r])=>l.localeCompare(r))){let l=[];for(let r of s){let a=c.filter((d)=>d.id===r.id);if(!a.length){let d=e.results.find((h)=>h.id===r.id);m.push(`- ${T(r.title)} (\`${r.path}\`): ${r.skip?T(r.skip):d?"the last capture failed.":"not captured yet."}`);continue}l.push(`### ${T(r.title)}`,"",T(a[0].description),"",...a[0].reason?[T(a[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let d of a)l.push("<figure>",` <img src="${N(`${n}/${d.file}`)}" alt="${N(`${d.title}, ${d.viewport.name}`)}" width="${d.viewport.width}" height="${d.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${d.viewport.width}px;height:auto">`,` <figcaption>${N(d.viewport.name)}, ${d.viewport.width} by ${d.viewport.height}${d.profile==="default"?"":`, signed in as ${N(d.profile)}`}</figcaption>`,"</figure>","")}if(l.length)f.push(`## ${T(o[0].toUpperCase()+o.slice(1).replace(/[-_]+/g," "))}`,"",...l)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
111
111
  `).trimEnd()}
112
- `}async function _(e,o,a){let t=ie(e,a.page);try{if((await Te(t)).isSymbolicLink()||!(await re(t,"utf8")).includes(oe))throw Error(`Refusing to replace a hand-written page: ${a.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let c=Ae(o,a);return await Be(Ne(t),{recursive:!0}),await Bun.write(`${t}.tmp`,c),await se(`${t}.tmp`,t),{path:a.page,sha256:ne(c)}}import{createRouter as De}from"@stacksjs/stx";import{readFileSync as Ve}from"fs";import{relative as He,resolve as Le}from"path";var ce=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),We=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Je(e){try{return Ve(e,"utf8")}catch{return""}}function _e(e,o){let a=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(a)return a;let t=o.split("/").filter(Boolean).map((c)=>c.startsWith("[")?`by ${ce(c.slice(1,-1).replace(/^\.\.\./,""))}`:ce(c));return t.length?We(t.join(" / ")):"Home"}function le(e={}){let o=Le(e.root??process.cwd()),a=[],t=new Set;for(let c of e.directories??["resources/views"])for(let f of De(o,{pagesDir:c,emit:!1})){let p=f.pattern.replace(/\*(\w*)/g,(l,r)=>`[...${r||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=p.split("/").filter(Boolean).map((l)=>l.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=u;for(let l=2;t.has(m);l++)m=`${u}-${l}`;t.add(m);let i=Je(f.filePath),s=i.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];a.push({id:m,route:p,source:He(o,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:_e(i,p),...s?{layout:s}:{},text:i})}return a.sort((c,f)=>c.route<f.route?-1:c.route>f.route?1:0)}function qe(e={}){let o=[],a=new Set;for(let t of le(e)){a.add(t.route);let c=[e.each?.(t),e.routes?.[t.route]],f={id:t.id,title:t.title,path:t.route,description:`The ${t.title} screen, served at ${t.route}.`,waitFor:"body",...e.defaults,sources:[t.source]};for(let p of c){if(p===void 0)continue;if(p===!1||typeof p==="string"){f.skip=p||"Left out of the screen documentation on purpose.";continue}Object.assign(f,p)}if(t.dynamic&&typeof f.path==="string"&&f.path===t.route&&!f.model&&!f.skip){if(e.strict)throw Error(`Dynamic view needs a concrete path or model: ${t.route} (${t.source})`);f.skip=`Needs a seeded example: give ${t.route} a concrete path, fixture resolver or model.`}if(typeof f.path==="function"&&!f.route)f.route=t.route;o.push(f)}for(let t of Object.keys(e.routes??{}))if(!a.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...o,...e.extra??[]]}import{spawnOwnedProcess as Ye}from"@stacksjs/cli/owned-process";import{ChromeLaunchError as Ze}from"@stacksjs/testing/browser";var C="0.75.663";var Dt=(e)=>e,F=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],A=(e)=>ze("sha256").update(e).digest("hex"),I=(e)=>/^[a-z0-9][a-z0-9._-]*$/i.test(e)&&!e.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e),de=(e)=>{let o=new URL(e);return o.origin+o.pathname};async function he(e,o=process.cwd()){let a=new URL(e.baseUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!e.outDir||!e.pages.length)throw Error("outDir and at least one page are required");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(e.backend&&!["webkit","chrome"].includes(e.backend))throw Error("backend must be webkit or chrome");if(e.requireHttpStatus!==void 0&&typeof e.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let t=Object.keys(e.profiles??{default:{}});if(!t.length||t.some((i)=>!I(i)))throw Error("Profile names must be safe filenames");let c=new Set,f=new Set;for(let i of e.pages){if(!I(i.id)||c.has(i.id))throw Error(`Duplicate or invalid screen id: ${i.id}`);if(c.add(i.id),i.expectedStatus!==void 0&&(!Number.isInteger(i.expectedStatus)||i.expectedStatus<100||i.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${i.id}`);if(!i.title.trim()||!i.description.trim()||!i.waitFor.trim())throw Error(`Screen ${i.id} needs title, description and waitFor`);if(typeof i.path!=="string"&&(typeof i.path!=="function"||!i.route))throw Error(`Screen ${i.id} needs a route pattern for its path resolver`);let s=new URL(typeof i.path==="string"?i.path:i.route,a);if(s.origin!==a.origin||s.username||s.password)throw Error(`Screen ${i.id} must stay on baseUrl's origin`);if(i.profiles?.some((l)=>!t.includes(l))||i.profiles?.length===0)throw Error(`Unknown or empty profiles for ${i.id}`);for(let l of i.sources??[]){let r=S(o,l);if(B(o,r).startsWith("..")||ue(l))throw Error(`Source must be inside the project: ${l}`);await M(r),f.add(B(o,r).replaceAll("\\","/"))}}let p=new Set;for(let i of e.viewports??F){if(!I(i.name)||p.has(i.name)||![i.width,i.height].every((s)=>Number.isInteger(s)&&s>=200&&s<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");p.add(i.name)}if(!p.size)throw Error("At least one viewport is required");for(let i of e.pages)if(i.viewports!==void 0&&(!i.viewports.length||i.viewports.some((s)=>!p.has(s))))throw Error(`Unknown or empty viewports for ${i.id}`);for(let i of e.inputs??[])await M(S(o,i));ae(e.film===!0?{}:e.film,e.docs,o,e.viewports??F);let u=[],m=new Set;for(let i of e.coverage?.directories??[]){let s=S(o,i);if(B(o,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Ge(s)).isDirectory())throw Error(`Missing coverage directory: ${i}`);let l=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){l++;let n=B(o,g(s,r)).replaceAll("\\","/");if(m.add(n),!f.has(n)&&!e.coverage?.exclude?.[n]?.trim())u.push(n)}if(!l)throw Error(`No .stx screens found in ${i}`)}for(let[i,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(i))throw Error(`Stale or unexplained coverage exclusion: ${i}`);if(u.length)throw Error(`Undocumented screens:
112
+ `}async function _(e,i,n){let t=ie(e,n.page);try{if((await Be(t)).isSymbolicLink()||!(await re(t,"utf8")).includes(oe))throw Error(`Refusing to replace a hand-written page: ${n.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let c=De(i,n);return await Ne(Ce(t),{recursive:!0}),await Bun.write(`${t}.tmp`,c),await se(`${t}.tmp`,t),{path:n.page,sha256:ne(c)}}import{createRouter as Ve}from"@stacksjs/stx";import{readFileSync as He}from"fs";import{relative as Le,resolve as We}from"path";var ce=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Je=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function _e(e){try{return He(e,"utf8")}catch{return""}}function qe(e,i){let n=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(n)return n;let t=i.split("/").filter(Boolean).map((c)=>c.startsWith("[")?`by ${ce(c.slice(1,-1).replace(/^\.\.\./,""))}`:ce(c));return t.length?Je(t.join(" / ")):"Home"}function le(e={}){let i=We(e.root??process.cwd()),n=[],t=new Set;for(let c of e.directories??["resources/views"])for(let f of Ve(i,{pagesDir:c,emit:!1})){let p=f.pattern.replace(/\*(\w*)/g,(l,r)=>`[...${r||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=p.split("/").filter(Boolean).map((l)=>l.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=u;for(let l=2;t.has(m);l++)m=`${u}-${l}`;t.add(m);let o=_e(f.filePath),s=o.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];n.push({id:m,route:p,source:Le(i,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:qe(o,p),...s?{layout:s}:{},text:o})}return n.sort((c,f)=>c.route<f.route?-1:c.route>f.route?1:0)}function Ie(e={}){let i=[],n=new Set;for(let t of le(e)){n.add(t.route);let c=[e.each?.(t),e.routes?.[t.route]],f={id:t.id,title:t.title,path:t.route,description:`The ${t.title} screen, served at ${t.route}.`,waitFor:"body",...e.defaults,sources:[t.source]};for(let p of c){if(p===void 0)continue;if(p===!1||typeof p==="string"){f.skip=p||"Left out of the screen documentation on purpose.";continue}Object.assign(f,p)}if(t.dynamic&&typeof f.path==="string"&&f.path===t.route&&!f.model&&!f.skip){if(e.strict)throw Error(`Dynamic view needs a concrete path or model: ${t.route} (${t.source})`);f.skip=`Needs a seeded example: give ${t.route} a concrete path, fixture resolver or model.`}if(typeof f.path==="function"&&!f.route)f.route=t.route;i.push(f)}for(let t of Object.keys(e.routes??{}))if(!n.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...i,...e.extra??[]]}import{spawnOwnedProcess as Ze}from"@stacksjs/cli/owned-process";import{ChromeLaunchError as et}from"@stacksjs/testing/browser";var C="0.75.667";var Vt=(e)=>e,F=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],A=(e)=>Ke("sha256").update(e).digest("hex"),I=(e)=>/^[a-z0-9][a-z0-9._-]*$/i.test(e)&&!e.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e),de=(e)=>{let i=new URL(e);return i.origin+i.pathname};async function he(e,i=process.cwd()){let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!e.outDir||!e.pages.length)throw Error("outDir and at least one page are required");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(e.backend&&!["webkit","chrome"].includes(e.backend))throw Error("backend must be webkit or chrome");if(e.requireHttpStatus!==void 0&&typeof e.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let t=Object.keys(e.profiles??{default:{}});if(!t.length||t.some((o)=>!I(o)))throw Error("Profile names must be safe filenames");let c=new Set,f=new Set;for(let o of e.pages){if(!I(o.id)||c.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(c.add(o.id),o.expectedStatus!==void 0&&(!Number.isInteger(o.expectedStatus)||o.expectedStatus<100||o.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${o.id}`);if(!o.title.trim()||!o.description.trim()||!o.waitFor.trim())throw Error(`Screen ${o.id} needs title, description and waitFor`);if(typeof o.path!=="string"&&(typeof o.path!=="function"||!o.route))throw Error(`Screen ${o.id} needs a route pattern for its path resolver`);let s=new URL(typeof o.path==="string"?o.path:o.route,n);if(s.origin!==n.origin||s.username||s.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((l)=>!t.includes(l))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let l of o.sources??[]){let r=v(i,l);if(B(i,r).startsWith("..")||ue(l))throw Error(`Source must be inside the project: ${l}`);await M(r),f.add(B(i,r).replaceAll("\\","/"))}}let p=new Set;for(let o of e.viewports??F){if(!I(o.name)||p.has(o.name)||![o.width,o.height].every((s)=>Number.isInteger(s)&&s>=200&&s<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");p.add(o.name)}if(!p.size)throw Error("At least one viewport is required");for(let o of e.pages)if(o.viewports!==void 0&&(!o.viewports.length||o.viewports.some((s)=>!p.has(s))))throw Error(`Unknown or empty viewports for ${o.id}`);for(let o of e.inputs??[])await M(v(i,o));ae(e.film===!0?{}:e.film,e.docs,i,e.viewports??F);let u=[],m=new Set;for(let o of e.coverage?.directories??[]){let s=v(i,o);if(B(i,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Qe(s)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let l=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){l++;let a=B(i,g(s,r)).replaceAll("\\","/");if(m.add(a),!f.has(a)&&!e.coverage?.exclude?.[a]?.trim())u.push(a)}if(!l)throw Error(`No .stx screens found in ${o}`)}for(let[o,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(u.length)throw Error(`Undocumented screens:
113
113
  ${u.sort().join(`
114
- `)}`)}async function G(e){let o=(await import(Xe(e).href)).default;if(!o||typeof o!=="object")throw Error("Screenshot configuration must have a default export");return o}async function et(e,o){let a=Date.now()+o;while(!await e()){if(Date.now()>=a)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function me(e,o){let a=e instanceof Error?e.message:"Screenshot capture failed";if(e instanceof Ze&&e.diagnostics.stderrTail.trim()){let t=e.diagnostics.stderrTail.trim(),c=t.split(`
115
- `).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);a=`${a.split(`
114
+ `)}`)}async function G(e){let i=(await import(Ye(e).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function tt(e,i){let n=Date.now()+i;while(!await e()){if(Date.now()>=n)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function me(e,i){let n=e instanceof Error?e.message:"Screenshot capture failed";if(e instanceof et&&e.diagnostics.stderrTail.trim()){let t=e.diagnostics.stderrTail.trim(),c=t.split(`
115
+ `).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);n=`${n.split(`
116
116
  `,1)[0]}
117
- ${c}`}for(let t of o.redactEnv??[]){let c=process.env[t];if(c)a=a.replaceAll(c,"[redacted]")}return a.slice(0,1000)}async function tt(e,o,a){let t=await G(e),c=S(a.root),f=S(c,a.outDir??t.outDir),p=[],u=await H(c,t.models),m=D(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let i={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000;for(let l of t.viewports??F){if(a.viewports?.length&&!a.viewports.includes(l.name))continue;for(let r of t.pages){if(a.only?.length&&!a.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(o))continue;if(r.viewports&&!r.viewports.includes(l.name))continue;let n={id:r.id,profile:o,viewport:l,title:r.title,description:r.description,...r.reason?{reason:r.reason}:{},path:new URL(typeof r.path==="string"?r.path:r.route,t.baseUrl).pathname,status:"failed"};if(p.push(n),r.skip){n.status="skipped",n.error=r.skip,process.send?.({type:"screenshot-result",result:n});continue}let d="starting the browser",h,y;try{h=await m.view(l.width,l.height),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:i,models:u,profile:o}):W(r.path,r.model,i,u),b=new URL(x,t.baseUrl);if(b.origin!==new URL(t.baseUrl).origin||b.username||b.password)throw Error("Resolved screenshot path must stay on the configured origin");let E={...r,path:x},j={view:h,baseUrl:t.baseUrl,profile:o,viewport:l,page:E};n.path=b.pathname,d="preparing the review profile",await t.profiles?.[o]?.prepare?.(j),d="opening the screen",await h.navigate(new URL(E.path,t.baseUrl).href),d="checking the document HTTP status";let O=Number(await h.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(O)&&O>=100&&O<=599)j.httpStatus=n.httpStatus=O;if(!j.httpStatus&&(t.requireHttpStatus||r.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(r.expectedStatus!==void 0?j.httpStatus!==r.expectedStatus:O>=400)throw Error(`The screen returned HTTP ${O}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);d="preparing the screen state",await r.prepare?.(j),d="waiting for screen readiness",await et(async()=>Boolean(await h.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(j)),s);let w=String(await h.evaluate("location.href"));if(de(w)!==de(new URL(E.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(d="loading fonts and visible images",await h.evaluate(`(async () => {
117
+ ${c}`}for(let t of i.redactEnv??[]){let c=process.env[t];if(c)n=n.replaceAll(c,"[redacted]")}return n.slice(0,1000)}async function rt(e,i,n){let t=await G(e),c=v(n.root),f=v(c,n.outDir??t.outDir),p=[],u=await H(c,t.models),m=D(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let o={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000;for(let l of t.viewports??F){if(n.viewports?.length&&!n.viewports.includes(l.name))continue;for(let r of t.pages){if(n.only?.length&&!n.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(i))continue;if(r.viewports&&!r.viewports.includes(l.name))continue;let a={id:r.id,profile:i,viewport:l,title:r.title,description:r.description,...r.reason?{reason:r.reason}:{},path:new URL(typeof r.path==="string"?r.path:r.route,t.baseUrl).pathname,status:"failed"};if(p.push(a),r.skip){a.status="skipped",a.error=r.skip,process.send?.({type:"screenshot-result",result:a});continue}let d="starting the browser",h,y;try{h=await m.view(l.width,l.height),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:o,models:u,profile:i}):W(r.path,r.model,o,u),b=new URL(x,t.baseUrl);if(b.origin!==new URL(t.baseUrl).origin||b.username||b.password)throw Error("Resolved screenshot path must stay on the configured origin");let E={...r,path:x},j={view:h,baseUrl:t.baseUrl,profile:i,viewport:l,page:E};a.path=b.pathname,d="preparing the review profile",await t.profiles?.[i]?.prepare?.(j),d="opening the screen",await h.navigate(new URL(E.path,t.baseUrl).href),d="checking the document HTTP status";let O=Number(await h.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(O)&&O>=100&&O<=599)j.httpStatus=a.httpStatus=O;if(!j.httpStatus&&(t.requireHttpStatus||r.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(r.expectedStatus!==void 0?j.httpStatus!==r.expectedStatus:O>=400)throw Error(`The screen returned HTTP ${O}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);d="preparing the screen state",await r.prepare?.(j),d="waiting for screen readiness",await tt(async()=>Boolean(await h.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(j)),s);let w=String(await h.evaluate("location.href"));if(de(w)!==de(new URL(E.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(d="loading fonts and visible images",await h.evaluate(`(async () => {
118
118
  const style = document.createElement('style'); style.textContent = '*{animation:none!important;transition:none!important;scroll-behavior:auto!important;caret-color:transparent!important}'; document.head.append(style);
119
119
  for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
120
120
  const maskSheet = new CSSStyleSheet();
@@ -123,10 +123,10 @@ ${c}`}for(let t of o.redactEnv??[]){let c=process.env[t];if(c)a=a.replaceAll(c,"
123
123
  await document.fonts.ready;
124
124
  for (const image of document.images) { const box=image.getBoundingClientRect(); if(box.bottom>0 && box.top<innerHeight && !image.complete) await new Promise(resolve=>{image.addEventListener('load',resolve,{once:true});image.addEventListener('error',resolve,{once:true})}); }
125
125
  await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
126
- })()`),await h.evaluate("[...document.images].some(image=>{const r=image.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight&&image.complete&&image.naturalWidth===0})"))throw Error("A visible image failed to load");d="saving the screenshot";let k=new Uint8Array(await(await h.screenshot()).arrayBuffer()),P=`${r.id}/${o}-${l.name}.png`,R=g(f,P);await z(pe(R),{recursive:!0});let Q=g(a.staging,`${r.id}-${o}-${l.name}.png`);await Bun.write(Q,k),await K(Q,R),n.file=P,n.sha256=A(k),n.status="captured"})(),new Promise((x,b)=>{y=setTimeout(()=>{h?.close(),b(Error("Screenshot deadline exceeded"))},s)})])}catch(x){n.error=`${d}: ${me(x,t)}`}finally{if(y)clearTimeout(y);h?.close(),process.send?.({type:"screenshot-result",result:n})}}}return p}finally{try{await m.close()}finally{await t.data?.cleanup?.()}}}async function Vt(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let o=S(e.root??process.cwd()),a=S(o,e.config??"config/screenshots.ts"),t=await G(a);await he(t,o);for(let s of e.only??[])if(!t.pages.some((l)=>l.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??F).some((l)=>l.name===s))throw Error(`Unknown viewport: ${s}`);let c=S(o,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:C,models:await H(o,t.models),configHash:A(Buffer.concat([Buffer.from(C),await M(a),...await Promise.all(f.map((s)=>M(S(o,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return p;if(e.check){let s=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==C||s.configHash!==p.configHash||s.models?.sourceHash!==p.models.sourceHash||s.results.some((l)=>l.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let l of t.pages)for(let r of l.profiles??Object.keys(t.profiles??{default:{}}))for(let n of t.viewports??F){if(l.viewports&&!l.viewports.includes(n.name))continue;let d=s.results.find((h)=>h.id===l.id&&h.profile===r&&h.viewport.name===n.name);if(!d||!l.skip&&d.status!=="captured")throw Error(`Missing screenshot: ${l.id}/${r}-${n.name}`);if(d.file&&(B(c,S(c,d.file)).split(/[\\/]/)[0]===".."||ue(B(c,S(c,d.file)))||A(await M(g(c,d.file)))!==d.sha256))throw Error(`Screenshot bytes changed: ${l.id}`)}for(let l of s.films??[])if(B(c,S(c,l.file)).startsWith("..")||A(await M(g(c,l.file)))!==l.sha256)throw Error(`Screen film changed: ${l.file}`);if(t.film&&!s.films?.length)throw Error("The screen film is missing; capture again");if(t.docs&&(!s.docsPage||s.docsPage.path!==t.docs.page||A(await M(S(o,t.docs.page)))!==s.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return s}let u;try{let s=g(c,"manifest.json");if((await U(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(u=JSON.parse(await M(s,"utf8")),u.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((e.only?.length||e.viewports?.length)&&u.configHash!==p.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(s){if(s.code!=="ENOENT")throw s}let m=new Set(u?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let l=g(c,s.id);try{if((await U(l)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${s.id}`)}catch(r){if(r.code!=="ENOENT")throw r}for(let r of s.profiles??Object.keys(t.profiles??{default:{}}))for(let n of t.viewports??F){if(s.viewports&&!s.viewports.includes(n.name))continue;let d=`${s.id}/${r}-${n.name}.png`;try{if((await U(g(c,d))).isSymbolicLink()||!m.has(d))throw Error(`Refusing to overwrite an unowned screenshot: ${d}`)}catch(h){if(h.code!=="ENOENT")throw h}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await U(g(c,s))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(l){if(l.code!=="ENOENT")throw l}await z(c,{recursive:!0});let i=await fe(g(c,".stacks-screenshots-"));await Bun.write(g(i,"bunfig.toml"),`preload = []
127
- `);try{for(let n of Object.keys(t.profiles??{default:{}})){let d=g(i,`${n}.json`),h=t.pages.filter((v)=>(!e.only?.length||e.only.includes(v.id))&&(v.profiles??Object.keys(t.profiles??{default:{}})).includes(n)),y=h.reduce((v,k)=>v+(t.viewports??F).filter((P)=>(!e.viewports?.length||e.viewports.includes(P.name))&&(!k.viewports||k.viewports.includes(P.name))).length,0);if(!y)continue;let x=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!x)throw Error("An installed Bun is required for screenshot workers");let b=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",o):import.meta.path,E=await fe(Y(Qe(),process.platform)),j={...process.env,TMPDIR:E,TMP:E,TEMP:E},O,w;try{let v=O=Ye([x,"--no-env-file",`--config=${g(i,"bunfig.toml")}`,b,"--worker",a,n,JSON.stringify({...e,root:o,staging:i}),d],{ownerRuntime:x,cwd:o,env:j,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(P)=>{let R=P;if(R?.type==="screenshot-result"&&R.result)e.onProgress?.(R.result)}});if((await Promise.race([v.exited,new Promise((P,R)=>{w=setTimeout(()=>{v.stop(),R(Error(`Screenshot worker timed out for ${n}`))},y*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${n}`);p.results.push(...JSON.parse(await M(d,"utf8")))}catch(v){for(let k of h)for(let P of t.viewports??F){if(e.viewports?.length&&!e.viewports.includes(P.name)||k.viewports&&!k.viewports.includes(P.name))continue;p.results.push({id:k.id,profile:n,viewport:P,title:k.title,description:k.description,path:new URL(typeof k.path==="string"?k.path:k.route,t.baseUrl).pathname,status:"failed",error:me(v,t)})}}finally{if(w)clearTimeout(w);await O?.stop(),await q(E,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let n=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(n.configHash===p.configHash&&n.models?.sourceHash===p.models.sourceHash){let d=new Set(p.results.map((h)=>`${h.id}/${h.profile}/${h.viewport.name}`));p.results.unshift(...n.results.filter((h)=>!d.has(`${h.id}/${h.profile}/${h.viewport.name}`)))}}catch{}for(let n of p.results){if(n.status!=="failed"||n.file)continue;let d=u?.results.find((h)=>h.id===n.id&&h.profile===n.profile&&h.viewport.name===n.viewport.name);if(d?.file)n.file=d.file,n.sha256=d.sha256}if(!e.only?.length&&!e.viewports?.length){let n=new Set(p.results.map((d)=>d.file).filter(Boolean));for(let d of m){if(!d||n.has(d)||B(c,S(c,d)).startsWith(".."))continue;await q(g(c,d),{force:!0}),await Ke(pe(g(c,d))).catch(()=>{})}}await z(c,{recursive:!0});let s;try{if(e.publish!==!1){if(t.film)p.films=await J(c,p.results,t.viewports??F,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await _(o,p,t.docs)}}catch(n){s=n}await Bun.write(g(c,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
128
- `),await K(g(c,"manifest.json.tmp"),g(c,"manifest.json"));let l=(n)=>n.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
129
- `," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let n of p.results)r.push(`## ${l(n.title)} (${n.profile}, ${n.viewport.name})`,"",l(n.description),"",...n.reason?[l(n.reason),""]:[],n.status==="captured"?`![${l(n.title)}](${n.file})`:`**${n.status}:** ${l(n.error??"No image")}`,"");if(await Bun.write(g(c,"gallery.md"),`${r.join(`
126
+ })()`),await h.evaluate("[...document.images].some(image=>{const r=image.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight&&image.complete&&image.naturalWidth===0})"))throw Error("A visible image failed to load");d="saving the screenshot";let k=new Uint8Array(await(await h.screenshot()).arrayBuffer()),P=`${r.id}/${i}-${l.name}.png`,R=g(f,P);await z(pe(R),{recursive:!0});let Q=g(n.staging,`${r.id}-${i}-${l.name}.png`);await Bun.write(Q,k),await K(Q,R),a.file=P,a.sha256=A(k),a.status="captured"})(),new Promise((x,b)=>{y=setTimeout(()=>{h?.close(),b(Error("Screenshot deadline exceeded"))},s)})])}catch(x){a.error=`${d}: ${me(x,t)}`}finally{if(y)clearTimeout(y);h?.close(),process.send?.({type:"screenshot-result",result:a})}}}return p}finally{try{await m.close()}finally{await t.data?.cleanup?.()}}}async function Ht(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let i=v(e.root??process.cwd()),n=v(i,e.config??"config/screenshots.ts"),t=await G(n);await he(t,i);for(let s of e.only??[])if(!t.pages.some((l)=>l.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??F).some((l)=>l.name===s))throw Error(`Unknown viewport: ${s}`);let c=v(i,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:C,models:await H(i,t.models),configHash:A(Buffer.concat([Buffer.from(C),await M(n),...await Promise.all(f.map((s)=>M(v(i,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return p;if(e.check){let s=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==C||s.configHash!==p.configHash||s.models?.sourceHash!==p.models.sourceHash||s.results.some((l)=>l.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let l of t.pages)for(let r of l.profiles??Object.keys(t.profiles??{default:{}}))for(let a of t.viewports??F){if(l.viewports&&!l.viewports.includes(a.name))continue;let d=s.results.find((h)=>h.id===l.id&&h.profile===r&&h.viewport.name===a.name);if(!d||!l.skip&&d.status!=="captured")throw Error(`Missing screenshot: ${l.id}/${r}-${a.name}`);if(d.file&&(B(c,v(c,d.file)).split(/[\\/]/)[0]===".."||ue(B(c,v(c,d.file)))||A(await M(g(c,d.file)))!==d.sha256))throw Error(`Screenshot bytes changed: ${l.id}`)}for(let l of s.films??[])if(B(c,v(c,l.file)).startsWith("..")||A(await M(g(c,l.file)))!==l.sha256)throw Error(`Screen film changed: ${l.file}`);if(t.film&&!s.films?.length)throw Error("The screen film is missing; capture again");if(t.docs&&(!s.docsPage||s.docsPage.path!==t.docs.page||A(await M(v(i,t.docs.page)))!==s.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return s}let u;try{let s=g(c,"manifest.json");if((await U(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(u=JSON.parse(await M(s,"utf8")),u.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((e.only?.length||e.viewports?.length)&&u.configHash!==p.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(s){if(s.code!=="ENOENT")throw s}let m=new Set(u?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let l=g(c,s.id);try{if((await U(l)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${s.id}`)}catch(r){if(r.code!=="ENOENT")throw r}for(let r of s.profiles??Object.keys(t.profiles??{default:{}}))for(let a of t.viewports??F){if(s.viewports&&!s.viewports.includes(a.name))continue;let d=`${s.id}/${r}-${a.name}.png`;try{if((await U(g(c,d))).isSymbolicLink()||!m.has(d))throw Error(`Refusing to overwrite an unowned screenshot: ${d}`)}catch(h){if(h.code!=="ENOENT")throw h}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await U(g(c,s))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(l){if(l.code!=="ENOENT")throw l}await z(c,{recursive:!0});let o=await fe(g(c,".stacks-screenshots-"));await Bun.write(g(o,"bunfig.toml"),`preload = []
127
+ `);try{for(let a of Object.keys(t.profiles??{default:{}})){let d=g(o,`${a}.json`),h=t.pages.filter((S)=>(!e.only?.length||e.only.includes(S.id))&&(S.profiles??Object.keys(t.profiles??{default:{}})).includes(a)),y=h.reduce((S,k)=>S+(t.viewports??F).filter((P)=>(!e.viewports?.length||e.viewports.includes(P.name))&&(!k.viewports||k.viewports.includes(P.name))).length,0);if(!y)continue;let x=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!x)throw Error("An installed Bun is required for screenshot workers");let b=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,E=await fe(Y(Xe(),process.platform)),j={...process.env,TMPDIR:E,TMP:E,TEMP:E},O,w;try{let S=O=Ze([x,"--no-env-file",`--config=${g(o,"bunfig.toml")}`,b,"--worker",n,a,JSON.stringify({...e,root:i,staging:o}),d],{ownerRuntime:x,cwd:i,env:j,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(P)=>{let R=P;if(R?.type==="screenshot-result"&&R.result)e.onProgress?.(R.result)}});if((await Promise.race([S.exited,new Promise((P,R)=>{w=setTimeout(()=>{S.stop(),R(Error(`Screenshot worker timed out for ${a}`))},y*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${a}`);p.results.push(...JSON.parse(await M(d,"utf8")))}catch(S){for(let k of h)for(let P of t.viewports??F){if(e.viewports?.length&&!e.viewports.includes(P.name)||k.viewports&&!k.viewports.includes(P.name))continue;p.results.push({id:k.id,profile:a,viewport:P,title:k.title,description:k.description,path:new URL(typeof k.path==="string"?k.path:k.route,t.baseUrl).pathname,status:"failed",error:me(S,t)})}}finally{if(w)clearTimeout(w);await O?.stop(),await q(E,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let a=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(a.configHash===p.configHash&&a.models?.sourceHash===p.models.sourceHash){let d=new Set(p.results.map((h)=>`${h.id}/${h.profile}/${h.viewport.name}`));p.results.unshift(...a.results.filter((h)=>!d.has(`${h.id}/${h.profile}/${h.viewport.name}`)))}}catch{}for(let a of p.results){if(a.status!=="failed"||a.file)continue;let d=u?.results.find((h)=>h.id===a.id&&h.profile===a.profile&&h.viewport.name===a.viewport.name);if(d?.file)a.file=d.file,a.sha256=d.sha256}if(!e.only?.length&&!e.viewports?.length){let a=new Set(p.results.map((d)=>d.file).filter(Boolean));for(let d of m){if(!d||a.has(d)||B(c,v(c,d)).startsWith(".."))continue;await q(g(c,d),{force:!0}),await Ge(pe(g(c,d))).catch(()=>{})}}await z(c,{recursive:!0});let s;try{if(e.publish!==!1&&we(p)){if(t.film)p.films=await J(c,p.results,t.viewports??F,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await _(i,p,t.docs)}}catch(a){s=a}await Bun.write(g(c,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
128
+ `),await K(g(c,"manifest.json.tmp"),g(c,"manifest.json"));let l=(a)=>a.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
129
+ `," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let a of p.results)r.push(`## ${l(a.title)} (${a.profile}, ${a.viewport.name})`,"",l(a.description),"",...a.reason?[l(a.reason),""]:[],a.status==="captured"?`![${l(a.title)}](${a.file})`:`**${a.status}:** ${l(a.error??"No image")}`,"");if(await Bun.write(g(c,"gallery.md"),`${r.join(`
130
130
  `)}
131
- `),s)throw s;return p}finally{await q(i,{recursive:!0,force:!0})}}async function Ht(e={}){let o=S(e.root??process.cwd()),a=await G(S(o,e.config??"config/screenshots.ts"));await he(a,o);let t=S(o,e.outDir??a.outDir),c=g(t,"manifest.json");if((await U(c)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await M(c,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(delete f.films,delete f.docsPage,a.film)f.films=await J(t,f.results,a.viewports??F,a.film===!0?{}:a.film,a.backend);if(a.docs)f.docsPage=await _(o,f,a.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
132
- `),await K(g(t,"manifest.json.tmp"),c),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await tt(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{Vt as captureScreenshots,Dt as defineScreenshotConfig,H as discoverScreenshotModels,le as discoverViews,V as planScreenshotModels,Ht as publishScreenshots,qe as screensFromViews,W as screenshotFixturePath,he as validateScreenshotConfig};
131
+ `),s)throw s;return p}finally{await q(o,{recursive:!0,force:!0})}}function we(e){let i=new Set(e.results.map((n)=>n.id));return e.inventory.every((n)=>i.has(n.id))}async function Lt(e={}){let i=v(e.root??process.cwd()),n=await G(v(i,e.config??"config/screenshots.ts"));await he(n,i);let t=v(i,e.outDir??n.outDir),c=g(t,"manifest.json");if((await U(c)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await M(c,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(!we(f))throw Error("This manifest pictures only part of the inventory; capture every screen before publishing its films and page");if(delete f.films,delete f.docsPage,n.film)f.films=await J(t,f.results,n.viewports??F,n.film===!0?{}:n.film,n.backend);if(n.docs)f.docsPage=await _(i,f,n.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
132
+ `),await K(g(t,"manifest.json.tmp"),c),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await rt(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{Ht as captureScreenshots,Vt as defineScreenshotConfig,H as discoverScreenshotModels,le as discoverViews,V as planScreenshotModels,Lt as publishScreenshots,Ie as screensFromViews,W as screenshotFixturePath,he as validateScreenshotConfig};
package/dist/stories.d.ts CHANGED
@@ -2,6 +2,8 @@ import { open } from 'node:fs/promises';
2
2
  import { version } from '../package.json';
3
3
  export declare function defineStoryConfig(config: StoryConfig): StoryConfig;
4
4
  export declare function defineStory<Context>(story: Story<Context>): Story<Context>;
5
+ /** A folder inside the project, as the manifest records it: relative and with forward slashes. One outside stays absolute. */
6
+ export declare function portablePath(root: string, path: string): string;
5
7
  /** Record configured journeys, then atomically publish their docs and hashed evidence. */
6
8
  export declare function recordStories(options?: RecordStoryOptions): Promise<StoryReport>;
7
9
  export declare interface StorySession<Context = unknown> {
package/dist/stories.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{createHash as tt,randomUUID as ot}from"crypto";import{createReadStream as nt}from"fs";import{copyFile as at,lstat as _,mkdir as T,open as ct,readFile as S,realpath as dt,rename as Y,rm as ft,writeFile as R}from"fs/promises";import{basename as lt,dirname as W,isAbsolute as et,join as a,relative as P,resolve as b,sep as ut}from"path";import{pathToFileURL as pt}from"url";var X="0.75.663";function xt(t){return t}function Et(t){return t}var C=`stacks-story-recordings-v1
3
- `,z="<!-- Generated by buddy docs:stories. -->",I=(t)=>tt("sha256").update(t).digest("hex"),Z=(t)=>typeof t==="string"&&/^[a-z0-9][a-z0-9-]{0,79}$/.test(t);function v(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replace(/[\r\n]/g," ").replace(/([\\`*_[\]#|])/g,"\\$1")}async function J(t){try{return await _(t),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function g(t,i=t){let n=b(t);while(!0){if(await J(n)){if((await _(n)).isSymbolicLink())throw Error(`Story output cannot traverse a symbolic link: ${n}`)}if(n===b(i))return;let e=W(n);if(e===n)return;n=e}}async function L(t,i){await g(i,t);let n=await _(i);if(!n.isFile()||n.size===0)throw Error(`Missing or empty story artifact: ${i}`);let e=tt("sha256"),c=0;for await(let u of nt(i))e.update(u),c+=u.length;return{path:P(t,i).split(ut).join("/"),sha256:e.digest("hex"),bytes:c}}function B(t,i){let n=b(t,i.path);if(!i.path||et(i.path)||P(t,n).startsWith(".."))throw Error("Story artifact escaped its output directory");return n}async function ht(t){if(!t||!Array.isArray(t.stories)||!t.stories.length)throw Error("Story configuration needs at least one story");let i=new Set,n=(e,c,u,r)=>{if(!Number.isInteger(e)||e<c||e>u)throw Error(`Invalid story ${r}`)};n(t.fps??12,1,60,"fps (1 to 60)"),n(t.holdMs??700,0,30000,"holdMs (0 to 30000)"),n(t.timeoutMs??120000,100,1800000,"timeoutMs (100 to 1800000)");for(let e of t.stories){if(!Z(e.id)||i.has(e.id)||!e.title?.trim())throw Error(`Invalid or duplicate story id/title: ${e.id}`);if(i.add(e.id),!["browser","ios","android"].includes(e.driver?.platform)||typeof e.driver.open!=="function")throw Error(`Invalid driver for story ${e.id}`);if(!Array.isArray(e.scenes)||!e.scenes.length)throw Error(`Story ${e.id} has no scenes`);let c=new Set;for(let u of e.scenes){if(!Z(u.id)||c.has(u.id)||!u.title?.trim()||typeof u.run!=="function")throw Error(`Invalid or duplicate scene in ${e.id}: ${u.id}`);c.add(u.id),n(u.holdMs??t.holdMs??700,0,30000,"scene holdMs"),n(u.timeoutMs??t.timeoutMs??120000,100,1800000,"scene timeoutMs")}}}function wt(t,i){let n=[z,`# ${v(t.title)}`,"",t.description?v(t.description):"","",`Platform: ${t.platform}. Result: **${t.status}**.`,""];if(t.video)n.push(`<video controls playsinline preload="metadata" src="${i}${t.video.path}" poster="${t.scenes.find((e)=>e.screenshot)?.screenshot?i+t.scenes.find((e)=>e.screenshot).screenshot.path:""}"></video>`,"",`[Download video](${i}${t.video.path})`,"");for(let e of t.scenes)if(n.push(`## ${v(e.title)}`,"",`Result: **${e.status}**.${e.startedMs===void 0?"":` Starts at ${(e.startedMs/1000).toFixed(1)}s.`}`,"",e.description?v(e.description):"",""),e.screenshot)n.push(`![${v(e.title)}](${i}${e.screenshot.path})`,"");else n.push("No screenshot was captured for this scene.","");return`${n.join(`
2
+ import{createHash as it,randomUUID as dt}from"crypto";import{createReadStream as lt}from"fs";import{copyFile as ft,lstat as X,mkdir as U,open as ut,readFile as b,realpath as pt,rename as z,rm as et,writeFile as C}from"fs/promises";import{basename as ht,dirname as V,isAbsolute as q,join as n,relative as k,resolve as x,sep as ot}from"path";import{pathToFileURL as wt}from"url";var tt="0.75.667";function $t(t){return t}function jt(t){return t}var I=`stacks-story-recordings-v1
3
+ `,_="<!-- Generated by buddy docs:stories. -->",N=(t)=>it("sha256").update(t).digest("hex"),rt=(t)=>typeof t==="string"&&/^[a-z0-9][a-z0-9-]{0,79}$/.test(t);function E(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replace(/[\r\n]/g," ").replace(/([\\`*_[\]#|])/g,"\\$1")}async function O(t){try{return await X(t),!0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function y(t,s=t){let o=x(t);while(!0){if(await O(o)){if((await X(o)).isSymbolicLink())throw Error(`Story output cannot traverse a symbolic link: ${o}`)}if(o===x(s))return;let e=V(o);if(e===o)return;o=e}}async function F(t,s){await y(s,t);let o=await X(s);if(!o.isFile()||o.size===0)throw Error(`Missing or empty story artifact: ${s}`);let e=it("sha256"),l=0;for await(let u of lt(s))e.update(u),l+=u.length;return{path:k(t,s).split(ot).join("/"),sha256:e.digest("hex"),bytes:l}}function G(t,s){let o=x(t,s.path);if(!s.path||q(s.path)||k(t,o).startsWith(".."))throw Error("Story artifact escaped its output directory");return o}function st(t,s){let o=k(t,s);return o&&!o.startsWith("..")&&!q(o)?o.split(ot).join("/"):s}async function gt(t){if(!t||!Array.isArray(t.stories)||!t.stories.length)throw Error("Story configuration needs at least one story");let s=new Set,o=(e,l,u,r)=>{if(!Number.isInteger(e)||e<l||e>u)throw Error(`Invalid story ${r}`)};o(t.fps??12,1,60,"fps (1 to 60)"),o(t.holdMs??700,0,30000,"holdMs (0 to 30000)"),o(t.timeoutMs??120000,100,1800000,"timeoutMs (100 to 1800000)");for(let e of t.stories){if(!rt(e.id)||s.has(e.id)||!e.title?.trim())throw Error(`Invalid or duplicate story id/title: ${e.id}`);if(s.add(e.id),!["browser","ios","android"].includes(e.driver?.platform)||typeof e.driver.open!=="function")throw Error(`Invalid driver for story ${e.id}`);if(!Array.isArray(e.scenes)||!e.scenes.length)throw Error(`Story ${e.id} has no scenes`);let l=new Set;for(let u of e.scenes){if(!rt(u.id)||l.has(u.id)||!u.title?.trim()||typeof u.run!=="function")throw Error(`Invalid or duplicate scene in ${e.id}: ${u.id}`);l.add(u.id),o(u.holdMs??t.holdMs??700,0,30000,"scene holdMs"),o(u.timeoutMs??t.timeoutMs??120000,100,1800000,"scene timeoutMs")}}}function mt(t,s){let o=[_,`# ${E(t.title)}`,"",t.description?E(t.description):"","",`Platform: ${t.platform}. Result: **${t.status}**.`,""];if(t.video)o.push(`<video controls playsinline preload="metadata" src="${s}${t.video.path}" poster="${t.scenes.find((e)=>e.screenshot)?.screenshot?s+t.scenes.find((e)=>e.screenshot).screenshot.path:""}"></video>`,"",`[Download video](${s}${t.video.path})`,"");for(let e of t.scenes)if(o.push(`## ${E(e.title)}`,"",`Result: **${e.status}**.${e.startedMs===void 0?"":` Starts at ${(e.startedMs/1000).toFixed(1)}s.`}`,"",e.description?E(e.description):"",""),e.screenshot)o.push(`![${E(e.title)}](${s}${e.screenshot.path})`,"");else o.push("No screenshot was captured for this scene.","");return`${o.join(`
4
4
  `).trimEnd()}
5
- `}async function $t(t={}){if(t.list&&t.check)throw Error("Choose --list or --check");let i=await dt(b(t.root??process.cwd())),n=b(i,t.config??"config/stories.ts"),e=await S(n),c=(await import(`${pt(n).href}?story=${I(e)}`)).default;await ht(c);let u=[X,I(e),I(JSON.stringify(c,(s,o)=>typeof o==="function"?o.toString():o))];for(let s of[...c.inputs??[]].sort())u.push(`${s}:${I(await S(b(i,s)))}`);let r=b(i,t.outDir??c.outDir??"docs/stories"),l=c.publishDir===!1?void 0:b(i,c.publishDir??a(W(r),"public",lt(r)));if(l&&(l===r||!P(r,l).startsWith("..")||!P(l,r).startsWith("..")))throw Error("Published media must have a separate directory outside the story output");if(r===i||P(r,i)===""||!P(r,i).startsWith("..")&&!et(P(r,i)))throw Error("Story output must not contain the project root");let p={version:1,configHash:I(u.join(`
6
- `)),outDir:r,mediaDir:l,inventory:c.stories.map((s)=>({id:s.id,title:s.title,platform:s.driver.platform,scenes:s.scenes.map(({id:o,title:d})=>({id:o,title:d}))})),results:c.stories.map((s)=>({id:s.id,title:s.title,description:s.description,platform:s.driver.platform,status:"not-run",scenes:s.scenes.map((o)=>({id:o.id,title:o.title,description:o.description,status:"not-run"}))}))},G=new Set(t.only??c.stories.map((s)=>s.id));if(!G.size||[...G].some((s)=>!c.stories.some((o)=>o.id===s)))throw Error("Unknown or empty story selection");if(t.list)return p;if(await g(r),t.check){if(await g(a(r,".stacks-stories")),await S(a(r,".stacks-stories"),"utf8")!==C)throw Error("Unowned story output");let s=JSON.parse(await S(a(r,"manifest.json"),"utf8"));if(s.version!==1||s.configHash!==p.configHash||JSON.stringify(s.inventory)!==JSON.stringify(p.inventory))throw Error("Story recordings are stale");if(!s.index||s.results.length!==p.results.length||s.results.some((o,d)=>o.id!==p.results[d].id||o.status!=="passed"||!o.video||!o.page||o.scenes.length!==p.results[d].scenes.length||o.scenes.some((m,U)=>m.id!==p.results[d].scenes[U].id||m.status!=="passed"||!m.screenshot)))throw Error("Story recordings are incomplete or failed");for(let o of[s.index,...s.results.flatMap((d)=>[d.video,d.page,...d.scenes.map((m)=>m.screenshot)])]){let d=await L(r,B(r,o));if(d.sha256!==o.sha256||d.bytes!==o.bytes)throw Error(`Story artifact changed: ${o.path}`)}if(l){if(await g(l),await g(a(l,".stacks-stories")),await S(a(l,".stacks-stories"),"utf8")!==C||!s.published?.length)throw Error("Published story media is incomplete");let o=s.results.flatMap((d)=>[d.video,...d.scenes.map((m)=>m.screenshot)]);if(JSON.stringify(s.published)!==JSON.stringify(o))throw Error("Published story media inventory changed");for(let d of o)if((await L(l,B(l,d))).sha256!==d.sha256)throw Error(`Published story media changed: ${d.path}`)}return{...s,outDir:r}}if(await J(r)){if(await g(a(r,".stacks-stories")),!await J(a(r,".stacks-stories"))||await S(a(r,".stacks-stories"),"utf8")!==C)throw Error(`Refusing to overwrite an unowned story directory: ${r}`)}else await T(r,{recursive:!0}),await R(a(r,".stacks-stories"),C,{flag:"wx"});let V=await ct(a(r,".recording.lock"),"wx",384).catch(()=>{throw Error("Story output is locked by another recording; inspect .recording.lock before removing a stale lock")});await V.writeFile(`${process.pid}
7
- `);let q=`${new Date().toISOString().replaceAll(/[:.]/g,"-")}-${ot()}`;p.runId=q;let D=a(r,"runs",q),h=new AbortController,k=()=>h.abort(t.signal?.reason??Error("Story recording interrupted"));if(process.once("SIGINT",k),process.once("SIGTERM",k),t.signal?.addEventListener("abort",k,{once:!0}),t.signal?.aborted)k();try{await g(D,r),await T(D,{recursive:!0});for(let[f,w]of c.stories.entries()){if(!G.has(w.id))continue;let y=p.results[f],N=a(D,w.id);await T(N);let A,H=performance.now();try{h.signal.throwIfAborted(),A=await w.driver.open({videoPath:a(N,"video.mp4"),fps:c.fps??12,signal:h.signal}),H=performance.now(),y.status="passed";for(let[x,F]of w.scenes.entries()){h.signal.throwIfAborted();let O=y.scenes[x];O.startedMs=Math.round(performance.now()-H),O.status="failed";let Q=!1,rt=setTimeout(()=>h.abort(Error("Story scene timed out")),F.timeoutMs??c.timeoutMs??120000);try{await new Promise((E,M)=>{let j=()=>M(h.signal.reason);if(h.signal.addEventListener("abort",j,{once:!0}),Promise.resolve().then(()=>F.run(A.context,h.signal)).then(E,M).finally(()=>h.signal.removeEventListener("abort",j)),h.signal.aborted)j()}),await new Promise((E,M)=>{let j=()=>{clearTimeout(st),M(h.signal.reason)},st=setTimeout(()=>{h.signal.removeEventListener("abort",j),E()},F.holdMs??c.holdMs??700);if(h.signal.addEventListener("abort",j,{once:!0}),h.signal.aborted)j()}),Q=!0}finally{clearTimeout(rt);let E=await A.screenshot();if(E.length<8||Buffer.from(E.subarray(0,8)).toString("hex")!=="89504e470d0a1a0a")throw Error("Driver did not produce a PNG screenshot");let M=a(N,`${F.id}.png`);await R(M,E,{flag:"wx"}),O.screenshot=await L(r,M),O.status=Q?"passed":"failed",O.endedMs=Math.round(performance.now()-H)}}}catch(x){y.status="failed",t.onError?.(x,w.id)}finally{if(A){try{await A.finish(),y.video=await L(r,a(N,"video.mp4"))}catch(x){y.status="failed",t.onError?.(x,w.id)}try{await A.close()}catch(x){y.status="failed",t.onError?.(x,w.id)}}}let K=a(N,"index.md");if(await R(K,wt(y,"../../../"),{flag:"wx"}),y.page=await L(r,K),t.onProgress?.(y),h.signal.aborted)break}if(l){if(await g(l),await J(l)){if(await g(a(l,".stacks-stories")),await S(a(l,".stacks-stories"),"utf8")!==C)throw Error("Refusing to overwrite unowned published story media")}else await T(l,{recursive:!0}),await R(a(l,".stacks-stories"),C,{flag:"wx"});p.published=p.results.flatMap((f)=>[f.video,...f.scenes.map((w)=>w.screenshot)].filter((w)=>Boolean(w)));for(let f of p.published){let w=B(l,f);await g(w,l),await T(W(w),{recursive:!0}),await at(B(r,f),w,1)}}let s=a(r,"index.md"),o=a(r,"manifest.json");for(let f of[s,o])if(await J(f)){if(await g(f),f===s&&!(await S(f,"utf8")).startsWith(z))throw Error("Refusing to replace a hand-written story index");if(f===o&&JSON.parse(await S(f,"utf8")).version!==1)throw Error("Refusing to replace an unknown story manifest")}let d=[z,`# ${v(c.title??"User stories")}`,"","Videos and screenshots from automated end-to-end journeys.","",...p.results.flatMap((f)=>[`- ${f.page?`[${v(f.title)}](${f.page.path})`:v(f.title)} (${f.platform}): **${f.status}**`,""])].join(`
8
- `),m=a(D,"index.md.tmp");await R(m,d,{flag:"wx"}),p.index={path:"index.md",sha256:I(d),bytes:Buffer.byteLength(d)};let U=a(D,"manifest.json.tmp");return await R(U,`${JSON.stringify(p,null,2)}
9
- `,{flag:"wx"}),await Y(m,s),await Y(U,o),p}finally{process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),t.signal?.removeEventListener("abort",k),await V.close(),await ft(a(r,".recording.lock"))}}export{Et as defineStory,xt as defineStoryConfig,$t as recordStories};
5
+ `}async function Mt(t={}){if(t.list&&t.check)throw Error("Choose --list or --check");let s=await pt(x(t.root??process.cwd())),o=x(s,t.config??"config/stories.ts"),e=await b(o),l=(await import(`${wt(o).href}?story=${N(e)}`)).default;await gt(l);let u=[tt,N(e),N(JSON.stringify(l,(i,f)=>typeof f==="function"?f.toString():f))];for(let i of[...l.inputs??[]].sort())u.push(`${i}:${N(await b(x(s,i)))}`);let r=x(s,t.outDir??l.outDir??"docs/stories"),a=l.publishDir===!1?void 0:x(s,l.publishDir??n(V(r),"public",ht(r)));if(a&&(a===r||!k(r,a).startsWith("..")||!k(a,r).startsWith("..")))throw Error("Published media must have a separate directory outside the story output");if(r===s||k(r,s)===""||!k(r,s).startsWith("..")&&!q(k(r,s)))throw Error("Story output must not contain the project root");let p={version:1,configHash:N(u.join(`
6
+ `)),outDir:r,mediaDir:a,inventory:l.stories.map((i)=>({id:i.id,title:i.title,platform:i.driver.platform,scenes:i.scenes.map(({id:f,title:S})=>({id:f,title:S}))})),results:l.stories.map((i)=>({id:i.id,title:i.title,description:i.description,platform:i.driver.platform,status:"not-run",scenes:i.scenes.map((f)=>({id:f.id,title:f.title,description:f.description,status:"not-run"}))}))},W=new Set(t.only??l.stories.map((i)=>i.id));if(!W.size||[...W].some((i)=>!l.stories.some((f)=>f.id===i)))throw Error("Unknown or empty story selection");if(t.list)return p;if(await y(r),t.check){if(await y(n(r,".stacks-stories")),await b(n(r,".stacks-stories"),"utf8")!==I)throw Error("Unowned story output");let i=JSON.parse(await b(n(r,"manifest.json"),"utf8"));if(i.version!==1||i.configHash!==p.configHash||JSON.stringify(i.inventory)!==JSON.stringify(p.inventory))throw Error("Story recordings are stale");if(!i.index||i.results.length!==p.results.length||i.results.some((c,m)=>c.id!==p.results[m].id||c.status!=="passed"||!c.video||!c.page||c.scenes.length!==p.results[m].scenes.length||c.scenes.some((L,d)=>L.id!==p.results[m].scenes[d].id||L.status!=="passed"||!L.screenshot)))throw Error("Story recordings are incomplete or failed");let f=i.results.flatMap((c)=>[c.video,...c.scenes.map((m)=>m.screenshot)]),S=[i.index,...i.results.map((c)=>c.page)];for(let c of a?S:[...S,...f]){let m=await F(r,G(r,c));if(m.sha256!==c.sha256||m.bytes!==c.bytes)throw Error(`Story artifact changed: ${c.path}`)}if(a){if(await y(a),await y(n(a,".stacks-stories")),await b(n(a,".stacks-stories"),"utf8")!==I||!i.published?.length)throw Error("Published story media is incomplete");if(JSON.stringify(i.published)!==JSON.stringify(f))throw Error("Published story media inventory changed");for(let c of f){let m=await F(a,G(a,c));if(m.sha256!==c.sha256||m.bytes!==c.bytes)throw Error(`Published story media changed: ${c.path}`)}}return{...i,outDir:r,mediaDir:a}}if(await O(r)){if(await y(n(r,".stacks-stories")),!await O(n(r,".stacks-stories"))||await b(n(r,".stacks-stories"),"utf8")!==I)throw Error(`Refusing to overwrite an unowned story directory: ${r}`)}else await U(r,{recursive:!0}),await C(n(r,".stacks-stories"),I,{flag:"wx"});let K=await ut(n(r,".recording.lock"),"wx",384).catch(()=>{throw Error("Story output is locked by another recording; inspect .recording.lock before removing a stale lock")});await K.writeFile(`${process.pid}
7
+ `);let Q=`${new Date().toISOString().replaceAll(/[:.]/g,"-")}-${dt()}`;p.runId=Q;let T=n(r,"runs",Q),h=new AbortController,j=()=>h.abort(t.signal?.reason??Error("Story recording interrupted"));if(process.once("SIGINT",j),process.once("SIGTERM",j),t.signal?.addEventListener("abort",j,{once:!0}),t.signal?.aborted)j();try{await y(T,r),await U(T,{recursive:!0});for(let[d,w]of l.stories.entries()){if(!W.has(w.id))continue;let g=p.results[d],v=n(T,w.id);await U(v);let D,H=performance.now();try{h.signal.throwIfAborted(),D=await w.driver.open({videoPath:n(v,"video.mp4"),fps:l.fps??12,signal:h.signal}),H=performance.now(),g.status="passed";for(let[M,B]of w.scenes.entries()){h.signal.throwIfAborted();let J=g.scenes[M];J.startedMs=Math.round(performance.now()-H),J.status="failed";let Z=!1,nt=setTimeout(()=>h.abort(Error("Story scene timed out")),B.timeoutMs??l.timeoutMs??120000);try{await new Promise((P,A)=>{let R=()=>A(h.signal.reason);if(h.signal.addEventListener("abort",R,{once:!0}),Promise.resolve().then(()=>B.run(D.context,h.signal)).then(P,A).finally(()=>h.signal.removeEventListener("abort",R)),h.signal.aborted)R()}),await new Promise((P,A)=>{let R=()=>{clearTimeout(at),A(h.signal.reason)},at=setTimeout(()=>{h.signal.removeEventListener("abort",R),P()},B.holdMs??l.holdMs??700);if(h.signal.addEventListener("abort",R,{once:!0}),h.signal.aborted)R()}),Z=!0}finally{clearTimeout(nt);let P=await D.screenshot();if(P.length<8||Buffer.from(P.subarray(0,8)).toString("hex")!=="89504e470d0a1a0a")throw Error("Driver did not produce a PNG screenshot");let A=n(v,`${B.id}.png`);await C(A,P,{flag:"wx"}),J.screenshot=await F(r,A),J.status=Z?"passed":"failed",J.endedMs=Math.round(performance.now()-H)}}}catch(M){g.status="failed",t.onError?.(M,w.id)}finally{if(D){try{await D.finish(),g.video=await F(r,n(v,"video.mp4"))}catch(M){g.status="failed",t.onError?.(M,w.id)}try{await D.close()}catch(M){g.status="failed",t.onError?.(M,w.id)}}}let Y=n(v,"index.md");if(await C(Y,mt(g,"../../../"),{flag:"wx"}),g.page=await F(r,Y),t.onProgress?.(g),h.signal.aborted)break}if(a){if(await y(a),await O(a)){if(await y(n(a,".stacks-stories")),await b(n(a,".stacks-stories"),"utf8")!==I)throw Error("Refusing to overwrite unowned published story media")}else await U(a,{recursive:!0}),await C(n(a,".stacks-stories"),I,{flag:"wx"});p.published=p.results.flatMap((d)=>[d.video,...d.scenes.map((w)=>w.screenshot)].filter((w)=>Boolean(w)));for(let d of p.published){let w=G(r,d),g=G(a,d);if(await y(g,a),await U(V(g),{recursive:!0}),await O(g))throw Error(`Published story media already exists: ${d.path}`);await z(w,g).catch(async(v)=>{if(v.code!=="EXDEV")throw v;await ft(w,g,1),await et(w)})}}let i=n(r,"index.md"),f=n(r,"manifest.json");for(let d of[i,f])if(await O(d)){if(await y(d),d===i&&!(await b(d,"utf8")).startsWith(_))throw Error("Refusing to replace a hand-written story index");if(d===f&&JSON.parse(await b(d,"utf8")).version!==1)throw Error("Refusing to replace an unknown story manifest")}let S=[_,`# ${E(l.title??"User stories")}`,"","Videos and screenshots from automated end-to-end journeys.","",...p.results.flatMap((d)=>[`- ${d.page?`[${E(d.title)}](${d.page.path})`:E(d.title)} (${d.platform}): **${d.status}**`,""])].join(`
8
+ `),c=n(T,"index.md.tmp");await C(c,S,{flag:"wx"}),p.index={path:"index.md",sha256:N(S),bytes:Buffer.byteLength(S)};let m=n(T,"manifest.json.tmp"),L={...p,outDir:st(s,r),mediaDir:a&&st(s,a)};return await C(m,`${JSON.stringify(L,null,2)}
9
+ `,{flag:"wx"}),await z(c,i),await z(m,f),p}finally{process.removeListener("SIGINT",j),process.removeListener("SIGTERM",j),t.signal?.removeEventListener("abort",j),await K.close(),await et(n(r,".recording.lock"))}}export{jt as defineStory,$t as defineStoryConfig,st as portablePath,Mt as recordStories};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/docs",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.663",
5
+ "version": "0.75.667",
6
6
  "description": "The Stacks way to document.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -57,20 +57,20 @@
57
57
  "prepublishOnly": "bun run build"
58
58
  },
59
59
  "dependencies": {
60
- "@stacksjs/bunpress": "^0.2.32",
61
- "@stacksjs/cli": "0.75.663",
62
- "@stacksjs/config": "0.75.663",
63
- "@stacksjs/path": "0.75.663",
64
- "@stacksjs/orm": "0.75.663",
65
- "@stacksjs/stx": "^0.2.927",
66
- "@stacksjs/testing": "0.75.663",
60
+ "@stacksjs/bunpress": "^0.2.33",
61
+ "@stacksjs/cli": "0.75.667",
62
+ "@stacksjs/config": "0.75.667",
63
+ "@stacksjs/path": "0.75.667",
64
+ "@stacksjs/orm": "0.75.667",
65
+ "@stacksjs/stx": "^0.2.930",
66
+ "@stacksjs/testing": "0.75.667",
67
67
  "@ts-videos/mp4": "^0.1.2",
68
68
  "craft-native": ">=0.0.499",
69
69
  "ts-videos": "^0.1.2"
70
70
  },
71
71
  "devDependencies": {
72
- "@stacksjs/alias": "0.75.663",
73
- "@stacksjs/server": "0.75.663",
72
+ "@stacksjs/alias": "0.75.667",
73
+ "@stacksjs/server": "0.75.667",
74
74
  "better-dx": "^0.2.39"
75
75
  }
76
76
  }