@stacksjs/docs 0.75.661 → 0.75.663

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.
@@ -109,7 +109,7 @@ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
109
109
  return true
110
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(`
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.661";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,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:
113
113
  ${u.sort().join(`
114
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
115
  `).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);a=`${a.split(`
package/dist/stories.js CHANGED
@@ -1,5 +1,5 @@
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.661";function xt(t){return t}function Et(t){return t}var C=`stacks-story-recordings-v1
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
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(`
4
4
  `).trimEnd()}
5
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(`
@@ -17,6 +17,7 @@ export declare interface BrowserStoryOptions {
17
17
  viewport?: LaunchOptions['viewport']
18
18
  chromePath?: string
19
19
  headless?: boolean
20
+ ffmpeg?: string
20
21
  masks?: string[]
21
22
  cursor?: { color?: string, size?: number, moveMs?: number, clickMs?: number }
22
23
  beforeNavigate?: (cdp: Cdp) => Promise<void>
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{spawnOwnedProcess as q}from"@stacksjs/cli/owned-process";import{click as oe,launch as J,settle as ne,waitFor as L}from"@stacksjs/testing/browser";import{randomUUID as _}from"crypto";import{readFile as ae,rm as j}from"fs/promises";import{dirname as W,join as H}from"path";import{Mp4Muxer as G}from"@ts-videos/mp4";import{BufferTarget as Q}from"ts-videos";function R(e={}){let t=Bun.serve({port:0,hostname:"127.0.0.1",fetch(i){let m=e[new URL(i.url).pathname];if(m)return new Response(Bun.file(m),{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:${t.port}/`,stop:()=>{t.stop(!0)}}}var Z=["6400","4d00","42e0"],ee=(e)=>`(() => {
2
+ import{spawnOwnedProcess as D}from"@stacksjs/cli/owned-process";import{click as oe,launch as W,settle as ne,waitFor as _}from"@stacksjs/testing/browser";import{randomUUID as V}from"crypto";import{readFile as ae,rm as H}from"fs/promises";import{dirname as q,join as X}from"path";import{Mp4Muxer as G}from"@ts-videos/mp4";import{BufferTarget as Q}from"ts-videos";function z(e={}){let r=Bun.serve({port:0,hostname:"127.0.0.1",fetch(o){let a=e[new URL(o.url).pathname];if(a)return new Response(Bun.file(a),{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:${r.port}/`,stop:()=>{r.stop(!0)}}}var Z=["6400","4d00","42e0"],ee=(e)=>`(() => {
3
3
  if (window.__stacksFilm) return true
4
4
  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) }
5
5
  const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
@@ -94,9 +94,9 @@ import{spawnOwnedProcess as q}from"@stacksjs/cli/owned-process";import{click as
94
94
  return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
95
  }
96
96
  return true
97
- })()`,te=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function z(e,t){if(!Number.isInteger(t.fps)||t.fps<1||t.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(ee(t));let i=[],m,f={width:0,height:0},d=0,n=async(r)=>{let o=JSON.parse(String(await e(`window.__stacksFilm.drain(${r})`)));if(f={width:o.width,height:o.height},o.description)m=new Uint8Array(Buffer.from(o.description,"base64"));for(let[u,c,p]of o.chunks)i.push([u,c,new Uint8Array(Buffer.from(p,"base64"))])};return{frames:()=>d,async add(r,o){if(!Number.isInteger(o)||o<1)return;let u=r?`${JSON.stringify(Buffer.from(r).toString("base64"))}, ${JSON.stringify(te(r))}`:"null, null";if(await e(`window.__stacksFilm.add(${u}, ${o})`),d+=o,d%(t.fps*20)<o)await n(!1)},async addVideo(r,o=[]){for(let c of o)if(![c.x,c.y,c.size,c.start,c.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(c.color))throw Error("Invalid film mark");let u=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(r)})`)));for(let c=0;c<u.frames;c+=t.fps){let p=Math.min(t.fps,u.frames-c);await e(`window.__stacksFilm.copy(${c}, ${p}, ${JSON.stringify(o)})`),d+=p,await n(!1)}return u.seconds},async finish(){if(await n(!0),!i.length||!m)throw Error("The browser encoded no video");let r=new Q,o=new G(r),u=o.addVideoTrack({codec:"h264",width:f.width,height:f.height,frameRate:t.fps,codecDescription:m});for(let[c,p,w]of i)await o.writePacket(u.id,{data:w,timestamp:p/1e6,duration:1/t.fps,isKeyframe:c===1});return await o.finalize(),r.buffer}}}import{join as re}from"path";import{launch as ie}from"@stacksjs/testing/browser";function pe(e,t){let i=re(e,"stx-b-");return t!=="win32"&&Buffer.byteLength(i)+6>60?"/tmp/stx-b-":i}function V(e){let t,i;return{async view(m,f){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:m,height:f,backend:e});if(!i){let d=await ie({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let n=`127.0.0.1:${d.port}`,r=await fetch(`http://${n}/json/version`,{signal:AbortSignal.timeout(5000)});if(!r.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${r.status})`);let o=await r.json(),u=URL.parse(o.webSocketDebuggerUrl||"");if(u?.protocol!=="ws:"||u.host!==n||!u.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");i=u.href,t=d}catch(n){throw await d.close(),n}}return new Bun.WebView({width:m,height:f,backend:{type:"chrome",url:i}})},async close(){try{await t?.close()}finally{t=void 0,i=void 0}}}}function D(e){let t=`:is(${['input[type="password"]',...e].join(",")})`,i=`${t}: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`
98
- ${t}: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; }
99
- ${i}, ${i}::selection {
97
+ })()`,te=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function L(e,r){if(!Number.isInteger(r.fps)||r.fps<1||r.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(ee(r));let o=[],a,u={width:0,height:0},c=0,n=async(t)=>{let i=JSON.parse(String(await e(`window.__stacksFilm.drain(${t})`)));if(u={width:i.width,height:i.height},i.description)a=new Uint8Array(Buffer.from(i.description,"base64"));for(let[d,l,p]of i.chunks)o.push([d,l,new Uint8Array(Buffer.from(p,"base64"))])};return{frames:()=>c,async add(t,i){if(!Number.isInteger(i)||i<1)return;let d=t?`${JSON.stringify(Buffer.from(t).toString("base64"))}, ${JSON.stringify(te(t))}`:"null, null";if(await e(`window.__stacksFilm.add(${d}, ${i})`),c+=i,c%(r.fps*20)<i)await n(!1)},async addVideo(t,i=[]){for(let l of i)if(![l.x,l.y,l.size,l.start,l.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(l.color))throw Error("Invalid film mark");let d=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(t)})`)));for(let l=0;l<d.frames;l+=r.fps){let p=Math.min(r.fps,d.frames-l);await e(`window.__stacksFilm.copy(${l}, ${p}, ${JSON.stringify(i)})`),c+=p,await n(!1)}return d.seconds},async finish(){if(await n(!0),!o.length||!a)throw Error("The browser encoded no video");let t=new Q,i=new G(t),d=i.addVideoTrack({codec:"h264",width:u.width,height:u.height,frameRate:r.fps,codecDescription:a});for(let[l,p,h]of o)await i.writePacket(d.id,{data:h,timestamp:p/1e6,duration:1/r.fps,isKeyframe:l===1});return await i.finalize(),t.buffer}}}import{join as re}from"path";import{launch as ie}from"@stacksjs/testing/browser";function we(e,r){let o=re(e,"stx-b-");return r!=="win32"&&Buffer.byteLength(o)+6>60?"/tmp/stx-b-":o}function J(e){let r,o;return{async view(a,u){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:a,height:u,backend:e});if(!o){let c=await ie({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let n=`127.0.0.1:${c.port}`,t=await fetch(`http://${n}/json/version`,{signal:AbortSignal.timeout(5000)});if(!t.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${t.status})`);let i=await t.json(),d=URL.parse(i.webSocketDebuggerUrl||"");if(d?.protocol!=="ws:"||d.host!==n||!d.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");o=d.href,r=c}catch(n){throw await c.close(),n}}return new Bun.WebView({width:a,height:u,backend:{type:"chrome",url:o}})},async close(){try{await r?.close()}finally{r=void 0,o=void 0}}}}function j(e){let r=`:is(${['input[type="password"]',...e].join(",")})`,o=`${r}: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`
98
+ ${r}: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; }
99
+ ${o}, ${o}::selection {
100
100
  color: transparent !important;
101
101
  -webkit-text-fill-color: transparent !important;
102
102
  -webkit-text-stroke: 0 transparent !important;
@@ -104,20 +104,20 @@ ${i}, ${i}::selection {
104
104
  caret-color: transparent !important;
105
105
  forced-color-adjust: none !important;
106
106
  }
107
- ${i}::selection { background: transparent !important; }
108
- ${i}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
109
- ${i}::-webkit-search-cancel-button { visibility: hidden !important; }
110
- `}function N(e,t,i,m){if(!Number.isFinite(e)||e<t||e>i)throw Error(`Invalid ${m}`)}function se(e){let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return t}async function E(e,t,i=30000){t?.throwIfAborted();let m=q(e),f=!1,d=()=>{m.stop().catch(()=>{})};t?.addEventListener("abort",d,{once:!0});let n=setTimeout(()=>{f=!0,d()},i);try{let[r,o]=await Promise.all([m.exited,new Response(m.stdout).bytes(),new Response(m.stderr).text()]);if(t?.throwIfAborted(),f)throw Error("Story tool timed out");if(r.code!==0)throw Error(`Story tool failed: ${e[0]}`);return o}finally{clearTimeout(n),t?.removeEventListener("abort",d),await m.stop()}}function Ee(e){let t=se(e.baseUrl),i={color:"#2563eb",size:18,moveMs:450,clickMs:400,...e.cursor};if(!/^#[0-9a-f]{6}$/i.test(i.color))throw Error("Cursor color must be a six-digit hex color");return N(i.size,6,80,"cursor size"),N(i.moveMs,0,5000,"cursor movement"),N(i.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:m,fps:f,signal:d}){let n=await J({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:r}=n,o,u,c,p=!1,w,x,B,A,M=new Map,I=r.on("Network.responseReceived",(s)=>{if(s.type==="Document")M.set(s.frameId,{status:s.response.status})}),h,k=new Promise((s)=>{h=s}),T=async()=>{h(),u?.stop(),u=void 0;let s=o;o=void 0,await Promise.race([s?.close().catch(()=>{}),Bun.sleep(5000)])},l=()=>{p=!0,T(),n.close().catch(()=>{})};d.addEventListener("abort",l,{once:!0});try{d.throwIfAborted();let s=`stacks-story-${_()}`,v=D(e.masks??[]),O=`(() => {
107
+ ${o}::selection { background: transparent !important; }
108
+ ${o}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
109
+ ${o}::-webkit-search-cancel-button { visibility: hidden !important; }
110
+ `}function A(e,r,o,a){if(!Number.isFinite(e)||e<r||e>o)throw Error(`Invalid ${a}`)}function se(e){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return r}async function M(e,r,o=30000){r?.throwIfAborted();let a=D(e),u=!1,c=()=>{a.stop().catch(()=>{})};r?.addEventListener("abort",c,{once:!0});let n=setTimeout(()=>{u=!0,c()},o);try{let[t,i]=await Promise.all([a.exited,new Response(a.stdout).bytes(),new Response(a.stderr).text()]);if(r?.throwIfAborted(),u)throw Error("Story tool timed out");if(t.code!==0)throw Error(`Story tool failed: ${e[0]}`);return i}finally{clearTimeout(n),r?.removeEventListener("abort",c),await a.stop()}}async function ce(e,r,o){let a=D([e,"-hide_banner","-loglevel","error","-nostdin","-n","-threads","2","-f","image2pipe","-framerate",String(r),"-vcodec","mjpeg","-i","pipe:0","-an","-filter_threads","1","-vf","pad=ceil(iw/2)*2:ceil(ih/2)*2","-c:v","libx264","-threads","2","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",o],{stdin:"pipe"}),u=new Response(a.stderr).text(),c=new Response(a.stdout).arrayBuffer();try{await a.started;let n=a.stdin;if(!n)throw Error("Story encoder has no input stream");return{async add(t,i){for(let d=0;d<i;d++)n.write(t),await n.flush()},async finish(){await n.end();let[t,i]=await Promise.all([a.exited,u,c]);if(t.code!==0)throw Error(`Story encoder failed: ${i.trim()||t.signal||t.code}`)},async close(){await a.stop()}}}catch(n){throw await a.stop(),n}}function Me(e){let r=se(e.baseUrl),o={color:"#2563eb",size:18,moveMs:450,clickMs:400,...e.cursor};if(!/^#[0-9a-f]{6}$/i.test(o.color))throw Error("Cursor color must be a six-digit hex color");return A(o.size,6,80,"cursor size"),A(o.moveMs,0,5000,"cursor movement"),A(o.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:a,fps:u,signal:c}){let n=await W({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:t}=n,i,d,l,p,h=!1,E,T,C,P,F=new Map,v=t.on("Network.responseReceived",(f)=>{if(f.type==="Document")F.set(f.frameId,{status:f.response.status})}),k,O=new Promise((f)=>{k=f}),m=async()=>{k(),d?.stop(),d=void 0;let f=i,N=p;i=void 0,p=void 0,await Promise.allSettled([Promise.race([f?.close(),Bun.sleep(5000)]),N?.close()])},w=()=>{h=!0,m(),n.close().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{c.throwIfAborted();let f=`stacks-story-${V()}`,N=j(e.masks??[]),I=`(() => {
111
111
  const start = () => {
112
112
  const maskSheet = new CSSStyleSheet();
113
- maskSheet.replaceSync(${JSON.stringify(v)});
113
+ maskSheet.replaceSync(${JSON.stringify(N)});
114
114
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
115
- const host = document.createElement('div'); host.id = ${JSON.stringify(s)};
115
+ const host = document.createElement('div'); host.id = ${JSON.stringify(f)};
116
116
  host.style.cssText='all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important;';
117
117
  const shadow=host.attachShadow({mode:'closed'}); const dot=document.createElement('div');
118
- dot.style.cssText=${JSON.stringify(`position:absolute;width:${i.size}px;height:${i.size}px;border:2px solid white;border-radius:50%;background:${i.color};box-shadow:0 1px 4px #0008;left:24px;top:24px;transform:translate(-50%,-50%);pointer-events:none;`)};
118
+ dot.style.cssText=${JSON.stringify(`position:absolute;width:${o.size}px;height:${o.size}px;border:2px solid white;border-radius:50%;background:${o.color};box-shadow:0 1px 4px #0008;left:24px;top:24px;transform:translate(-50%,-50%);pointer-events:none;`)};
119
119
  shadow.append(dot); document.documentElement.append(host);
120
120
  addEventListener('mousemove', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px'},true);
121
- addEventListener('pointerdown', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px';const pulse=document.createElement('div');pulse.style.cssText='position:absolute;left:'+event.clientX+'px;top:'+event.clientY+'px;width:12px;height:12px;border:4px solid ${i.color};border-radius:50%;transform:translate(-50%,-50%);';shadow.append(pulse);pulse.animate([{opacity:1,width:'12px',height:'12px'},{opacity:0,width:'70px',height:'70px'}],{duration:${i.clickMs}}).finished.then(()=>pulse.remove())},true);
121
+ addEventListener('pointerdown', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px';const pulse=document.createElement('div');pulse.style.cssText='position:absolute;left:'+event.clientX+'px;top:'+event.clientY+'px;width:12px;height:12px;border:4px solid ${o.color};border-radius:50%;transform:translate(-50%,-50%);';shadow.append(pulse);pulse.animate([{opacity:1,width:'12px',height:'12px'},{opacity:0,width:'70px',height:'70px'}],{duration:${o.clickMs}}).finished.then(()=>pulse.remove())},true);
122
122
  }; if(document.documentElement) start(); else new MutationObserver((_,observer)=>{if(document.documentElement){observer.disconnect();start()}}).observe(document,{childList:true});
123
- })()`;await r.send("Page.addScriptToEvaluateOnNewDocument",{source:O});let P={x:24,y:24},y={cdp:r,async goto(a,g={}){let b=new URL(a,t);if(b.origin!==t.origin||b.username||b.password)throw Error("Story navigation must stay on baseUrl origin");let S=g.expectedStatus??200;if(!Number.isInteger(S)||S<100||S>599)throw Error("Invalid expected document status");let C=await r.send("Page.navigate",{url:b.href});if(C.errorText||!await ne(r,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(M.get(C.frameId)?.status!==S)throw Error("Unexpected story document HTTP status");if(new URL(await r.evaluate("location.href")).origin!==t.origin)throw Error("Story page redirected outside baseUrl origin")},async click(a){d.throwIfAborted();let g=typeof a==="string"?a:a.selector,b=typeof a==="string"?void 0:a.text,S=await L(async()=>r.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(g)})].filter(el=>${b===void 0?"true":`el.textContent.trim()===${JSON.stringify(b)}`});if(all.length!==1)return null;const el=all[0];el.scrollIntoView({block:'center',behavior:'instant'});const r=el.getBoundingClientRect();return r.width&&r.height?{x:r.x+r.width/2,y:r.y+r.height/2}:null})()`),12000),C=P,Y=performance.now();do{d.throwIfAborted();let U=i.moveMs?Math.min(1,(performance.now()-Y)/i.moveMs):1;if(P={x:C.x+(S.x-C.x)*U,y:C.y+(S.y-C.y)*U},await r.send("Input.dispatchMouseEvent",{type:"mouseMoved",...P}),U===1)break;await Bun.sleep(16)}while(!0);await oe(r,a),await Bun.sleep(i.clickMs)},async type(a,g){await y.click(a),await r.send("Input.insertText",{text:g})},async expectText(a,g){await L(()=>r.evaluate(`document.querySelector(${JSON.stringify(a)})?.textContent.includes(${JSON.stringify(g)}) ?? false`),12000)}};if(await e.beforeNavigate?.(r),d.throwIfAborted(),await y.goto(t.href),e.prepare)await e.prepare(y);B=Buffer.from((await r.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),A=r.on("Page.screencastFrame",(a)=>{B=Buffer.from(a.data,"base64"),r.send("Page.screencastFrameAck",{sessionId:a.sessionId}).catch((g)=>{x=g})}),u=R(),o=await J({viewport:{width:320,height:240},chromePath:e.chromePath,headless:e.headless});let F=o.cdp;await F.send("Page.navigate",{url:u.url}),await L(()=>F.evaluate('document.readyState === "complete"'),15000),c=await z((a)=>F.evaluate(a),{fps:f}),await r.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let X=performance.now();w=(async()=>{let a=0,g;while(!p){if(d.throwIfAborted(),x)throw x;let b=Math.floor((performance.now()-X)/1000*f)+1;if(b-a>f*10)throw Error("Story encoder cannot keep up with the recording");if(b>a){let S=B;await Promise.race([c.add(S===g?void 0:S,b-a),k]),g=S,a=b}await Bun.sleep(Math.max(1,1000/f/2))}})().catch((a)=>{x=a});let K;return{context:y,screenshot:async()=>Buffer.from((await r.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>K??=(async()=>{p=!0;let a=!1,g=setTimeout(()=>{a=!0,T()},60000);try{if(await w,await r.send("Page.stopScreencast"),A?.(),x)throw Error("Story video capture failed",{cause:x});let b;try{b=await Promise.race([c.finish(),k.then(()=>{throw Error("The encoder page closed")})])}catch(S){throw Error(a?"Story video finalization timed out":"Story video capture failed",{cause:S})}if(await Bun.write(m,b),e.failOnBrowserErrors!==!1&&r.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(g),await T()}})(),async close(){p=!0,A?.(),I(),d.removeEventListener("abort",l);try{await T(),await w}finally{await n.close()}}}}catch(s){p=!0,A?.(),I(),d.removeEventListener("abort",l);try{await T(),await w}finally{await n.close()}throw s}}}}function Me(e){let t=e.platform==="ios";if(t?!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(e.device):!/^emulator-\d+$/.test(e.device))throw Error("Native stories require an explicit simulator UUID or emulator serial");if(t&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let i=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(i))throw Error("Tap color must be a six-digit hex color");N(e.tapMs??450,100,5000,"tap feedback");let m=e.tapSize??72;return N(m,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:f,fps:d,signal:n}){let r=H(W(f),"native-raw.mp4"),o=e.adb??"adb",u=e.xcrun??"xcrun",c=`/sdcard/stacks-story-${_()}.mp4`,p,w,x,B=0,A=[],M=e.input??{async tap(h,k){await E([o,"-s",e.device,"shell","input","tap",String(Math.round(h)),String(Math.round(k))],n)},async swipe(h,k,T){await E([o,"-s",e.device,"shell","input","swipe",String(Math.round(h.x)),String(Math.round(h.y)),String(Math.round(k.x)),String(Math.round(k.y)),String(Math.round(T))],n)},async type(h){if(!/^[a-z0-9@._+ -]*$/i.test(h))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await E([o,"-s",e.device,"shell","input","text",h.replaceAll(" ","%s")],n)}},I=(h,k)=>{N(h,0,16384,"tap x"),N(k,0,16384,"tap y")};try{if(n.throwIfAborted(),t){let{recordIosSimulatorVideo:l}=await import("craft-native/testing");p=(await l({device:e.device,path:r,xcrun:u})).stop}else{if(new TextDecoder().decode(await E([o,"-s",e.device,"get-state"],n)).trim()!=="device")throw Error("Android emulator is unavailable");w=q([o,"-s",e.device,"shell",`screenrecord --time-limit 180 ${c} & recorder=$!; trap 'kill -2 "$recorder" 2>/dev/null; wait "$recorder"; exit' HUP INT TERM; echo STACKS_RECORDER:$recorder; wait "$recorder"; result=$?; trap - HUP INT TERM; exit "$result"`]),await w.started;let s=w.stdout.getReader(),v="",O=setTimeout(()=>{w.stop()},15000);try{while(!x){let y=await s.read();if(y.done)throw Error("Android recorder stopped before startup");v+=new TextDecoder().decode(y.value);let F=/STACKS_RECORDER:(\d+)/.exec(v);if(F)x=Number(F[1]);if(v.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(O)}(async()=>{while(!(await s.read()).done);})().catch(()=>{}),new Response(w.stderr).text();let P=async()=>{await E([o,"-s",e.device,"shell",`case "$(cat /proc/${x}/cmdline 2>/dev/null)" in *${c}*) kill -2 ${x};; *) exit 3;; esac`])};await E([o,"-s",e.device,"shell","kill","-0",String(x)],n),p=async()=>{await P();let y=setTimeout(()=>{w.stop()},15000);try{await w.exited}finally{clearTimeout(y)}await E([o,"-s",e.device,"pull",c,r])},await E([o,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${c} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${x} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],n,20000)}B=performance.now();let h={async tap(l,s){n.throwIfAborted(),I(l,s);let v={x:l,y:s,start:(performance.now()-B)/1000,end:0};A.push(v);try{await M.tap(l,s)}finally{v.end=(performance.now()-B)/1000+(e.tapMs??450)/1000}},async swipe(l,s,v){if(n.throwIfAborted(),I(l.x,l.y),I(s.x,s.y),N(v,1,1e4,"swipe duration"),!M.swipe)throw Error("Native driver does not support swipes");await M.swipe(l,s,v)},async type(l){if(n.throwIfAborted(),!M.type)throw Error("Native driver does not support typing");await M.type(l)}},k;return{context:h,async screenshot(){if(n.throwIfAborted(),!t)return E([o,"-s",e.device,"exec-out","screencap","-p"],n);let l=H(W(f),`screenshot-${_()}.png`);try{return await E([u,"simctl","io",e.device,"screenshot",l],n),await ae(l)}finally{await j(l,{force:!0})}},finish:()=>k??=(async()=>{await p();let l=V(process.platform==="darwin"?"webkit":"chrome"),s=R({"/raw.mp4":r}),v;try{v=await l.view(320,240);let O=v;await O.navigate(s.url);let P=await z((y)=>O.evaluate(y),{fps:d});await P.addVideo("/raw.mp4",e.tapFeedback===!1?[]:A.map((y)=>({x:y.x,y:y.y,size:m,color:i,start:y.start,end:y.end}))),await Bun.write(f,await P.finish())}finally{s.stop();try{v?.close()}finally{await l.close()}}await j(r)})(),async close(){try{if(!k)await p?.()}finally{if(await w?.stop(),!t)await E([o,"-s",e.device,"shell","rm","-f",c])}}}}catch(h){try{await p?.()}finally{await w?.stop()}throw h}}}}export{Ee as browserStory,Me as nativeStory};
123
+ })()`;await t.send("Page.addScriptToEvaluateOnNewDocument",{source:I});let b={x:24,y:24},B={cdp:t,async goto(s,y={}){let g=new URL(s,r);if(g.origin!==r.origin||g.username||g.password)throw Error("Story navigation must stay on baseUrl origin");let x=y.expectedStatus??200;if(!Number.isInteger(x)||x<100||x>599)throw Error("Invalid expected document status");let S=await t.send("Page.navigate",{url:g.href});if(S.errorText||!await ne(t,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(F.get(S.frameId)?.status!==x)throw Error("Unexpected story document HTTP status");if(new URL(await t.evaluate("location.href")).origin!==r.origin)throw Error("Story page redirected outside baseUrl origin")},async click(s){c.throwIfAborted();let y=typeof s==="string"?s:s.selector,g=typeof s==="string"?void 0:s.text,x=await _(async()=>t.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(y)})].filter(el=>${g===void 0?"true":`el.textContent.trim()===${JSON.stringify(g)}`});if(all.length!==1)return null;const el=all[0];el.scrollIntoView({block:'center',behavior:'instant'});const r=el.getBoundingClientRect();return r.width&&r.height?{x:r.x+r.width/2,y:r.y+r.height/2}:null})()`),12000),S=b,R=performance.now();do{c.throwIfAborted();let U=o.moveMs?Math.min(1,(performance.now()-R)/o.moveMs):1;if(b={x:S.x+(x.x-S.x)*U,y:S.y+(x.y-S.y)*U},await t.send("Input.dispatchMouseEvent",{type:"mouseMoved",...b}),U===1)break;await Bun.sleep(16)}while(!0);await oe(t,s),await Bun.sleep(o.clickMs)},async type(s,y){await B.click(s),await t.send("Input.insertText",{text:y})},async expectText(s,y){await _(()=>t.evaluate(`document.querySelector(${JSON.stringify(s)})?.textContent.includes(${JSON.stringify(y)}) ?? false`),12000)}};if(await e.beforeNavigate?.(t),c.throwIfAborted(),await B.goto(r.href),e.prepare)await e.prepare(B);if(C=Buffer.from((await t.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),P=t.on("Page.screencastFrame",(s)=>{C=Buffer.from(s.data,"base64"),t.send("Page.screencastFrameAck",{sessionId:s.sessionId}).catch((y)=>{T=y})}),e.ffmpeg)p=await ce(e.ffmpeg,u,a);else{d=z(),i=await W({viewport:{width:320,height:240},chromePath:e.chromePath,headless:e.headless});let s=i.cdp;await s.send("Page.navigate",{url:d.url}),await _(()=>s.evaluate('document.readyState === "complete"'),15000),l=await L((y)=>s.evaluate(y),{fps:u})}c.throwIfAborted(),await t.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let K=performance.now();E=(async()=>{let s=0,y;while(!h){if(c.throwIfAborted(),T)throw T;let g=Math.floor((performance.now()-K)/1000*u)+1;if(g-s>u*10)throw Error("Story encoder cannot keep up with the recording");if(g>s){let x=C,S=g-s,R=p?p.add(x,S):l.add(x===y?void 0:x,S);await Promise.race([R,O]),y=x,s=g}await Bun.sleep(Math.max(1,1000/u/2))}})().catch((s)=>{T=s});let Y;return{context:B,screenshot:async()=>Buffer.from((await t.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>Y??=(async()=>{h=!0;let s=p,y=!1,g=setTimeout(()=>{y=!0,m()},60000);try{if(await E,await t.send("Page.stopScreencast"),P?.(),T)throw Error("Story video capture failed",{cause:T});let x=s?s.finish():l.finish().then((S)=>Bun.write(a,S));try{await Promise.race([x,O.then(()=>{throw Error("The story encoder closed")})])}catch(S){throw Error(y?"Story video finalization timed out":"Story video capture failed",{cause:S})}if(e.failOnBrowserErrors!==!1&&t.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(g),await m()}})(),async close(){h=!0,P?.(),v(),c.removeEventListener("abort",w);try{await m(),await E}finally{await n.close()}}}}catch(f){h=!0,P?.(),v(),c.removeEventListener("abort",w);try{await m(),await E}finally{await n.close()}throw f}}}}function Te(e){let r=e.platform==="ios";if(r?!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(e.device):!/^emulator-\d+$/.test(e.device))throw Error("Native stories require an explicit simulator UUID or emulator serial");if(r&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let o=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(o))throw Error("Tap color must be a six-digit hex color");A(e.tapMs??450,100,5000,"tap feedback");let a=e.tapSize??72;return A(a,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:u,fps:c,signal:n}){let t=X(q(u),"native-raw.mp4"),i=e.adb??"adb",d=e.xcrun??"xcrun",l=`/sdcard/stacks-story-${V()}.mp4`,p,h,E,T=0,C=[],P=e.input??{async tap(v,k){await M([i,"-s",e.device,"shell","input","tap",String(Math.round(v)),String(Math.round(k))],n)},async swipe(v,k,O){await M([i,"-s",e.device,"shell","input","swipe",String(Math.round(v.x)),String(Math.round(v.y)),String(Math.round(k.x)),String(Math.round(k.y)),String(Math.round(O))],n)},async type(v){if(!/^[a-z0-9@._+ -]*$/i.test(v))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await M([i,"-s",e.device,"shell","input","text",v.replaceAll(" ","%s")],n)}},F=(v,k)=>{A(v,0,16384,"tap x"),A(k,0,16384,"tap y")};try{if(n.throwIfAborted(),r){let{recordIosSimulatorVideo:m}=await import("craft-native/testing");p=(await m({device:e.device,path:t,xcrun:d})).stop}else{if(new TextDecoder().decode(await M([i,"-s",e.device,"get-state"],n)).trim()!=="device")throw Error("Android emulator is unavailable");h=D([i,"-s",e.device,"shell",`screenrecord --time-limit 180 ${l} & recorder=$!; trap 'kill -2 "$recorder" 2>/dev/null; wait "$recorder"; exit' HUP INT TERM; echo STACKS_RECORDER:$recorder; wait "$recorder"; result=$?; trap - HUP INT TERM; exit "$result"`]),await h.started;let w=h.stdout.getReader(),f="",N=setTimeout(()=>{h.stop()},15000);try{while(!E){let b=await w.read();if(b.done)throw Error("Android recorder stopped before startup");f+=new TextDecoder().decode(b.value);let B=/STACKS_RECORDER:(\d+)/.exec(f);if(B)E=Number(B[1]);if(f.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(N)}(async()=>{while(!(await w.read()).done);})().catch(()=>{}),new Response(h.stderr).text();let I=async()=>{await M([i,"-s",e.device,"shell",`case "$(cat /proc/${E}/cmdline 2>/dev/null)" in *${l}*) kill -2 ${E};; *) exit 3;; esac`])};await M([i,"-s",e.device,"shell","kill","-0",String(E)],n),p=async()=>{await I();let b=setTimeout(()=>{h.stop()},15000);try{await h.exited}finally{clearTimeout(b)}await M([i,"-s",e.device,"pull",l,t])},await M([i,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${l} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${E} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],n,20000)}T=performance.now();let v={async tap(m,w){n.throwIfAborted(),F(m,w);let f={x:m,y:w,start:(performance.now()-T)/1000,end:0};C.push(f);try{await P.tap(m,w)}finally{f.end=(performance.now()-T)/1000+(e.tapMs??450)/1000}},async swipe(m,w,f){if(n.throwIfAborted(),F(m.x,m.y),F(w.x,w.y),A(f,1,1e4,"swipe duration"),!P.swipe)throw Error("Native driver does not support swipes");await P.swipe(m,w,f)},async type(m){if(n.throwIfAborted(),!P.type)throw Error("Native driver does not support typing");await P.type(m)}},k;return{context:v,async screenshot(){if(n.throwIfAborted(),!r)return M([i,"-s",e.device,"exec-out","screencap","-p"],n);let m=X(q(u),`screenshot-${V()}.png`);try{return await M([d,"simctl","io",e.device,"screenshot",m],n),await ae(m)}finally{await H(m,{force:!0})}},finish:()=>k??=(async()=>{await p();let m=J(process.platform==="darwin"?"webkit":"chrome"),w=z({"/raw.mp4":t}),f;try{f=await m.view(320,240);let N=f;await N.navigate(w.url);let I=await L((b)=>N.evaluate(b),{fps:c});await I.addVideo("/raw.mp4",e.tapFeedback===!1?[]:C.map((b)=>({x:b.x,y:b.y,size:a,color:o,start:b.start,end:b.end}))),await Bun.write(u,await I.finish())}finally{w.stop();try{f?.close()}finally{await m.close()}}await H(t)})(),async close(){try{if(!k)await p?.()}finally{if(await h?.stop(),!r)await M([i,"-s",e.device,"shell","rm","-f",l])}}}}catch(v){try{await p?.()}finally{await h?.stop()}throw v}}}}export{Me as browserStory,Te as nativeStory};
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.661",
5
+ "version": "0.75.663",
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.25",
61
- "@stacksjs/cli": "0.75.661",
62
- "@stacksjs/config": "0.75.661",
63
- "@stacksjs/path": "0.75.661",
64
- "@stacksjs/orm": "0.75.661",
65
- "@stacksjs/stx": "^0.2.908",
66
- "@stacksjs/testing": "0.75.661",
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",
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.661",
73
- "@stacksjs/server": "0.75.661",
72
+ "@stacksjs/alias": "0.75.663",
73
+ "@stacksjs/server": "0.75.663",
74
74
  "better-dx": "^0.2.39"
75
75
  }
76
76
  }