@stacksjs/docs 0.75.661 → 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.
- package/dist/screenshots.js +19 -19
- package/dist/stories.d.ts +2 -0
- package/dist/stories.js +7 -7
- package/dist/story-drivers.d.ts +1 -0
- package/dist/story-drivers.js +13 -13
- package/package.json +10 -10
package/dist/screenshots.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createHash as
|
|
3
|
-
${
|
|
4
|
-
${
|
|
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
|
-
${
|
|
13
|
-
${
|
|
14
|
-
${
|
|
15
|
-
`}import{join as
|
|
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(
|
|
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
|
-
})()`,
|
|
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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),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,
|
|
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
|
|
115
|
-
`).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);
|
|
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
|
|
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}/${
|
|
127
|
-
`);try{for(let
|
|
128
|
-
`),await K(g(c,"manifest.json.tmp"),g(c,"manifest.json"));let l=(
|
|
129
|
-
`," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let
|
|
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"?``:`**${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(
|
|
132
|
-
`),await K(g(t,"manifest.json.tmp"),c),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await
|
|
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
|
|
3
|
-
`,
|
|
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("&","&").replaceAll("<","<").replaceAll(">",">").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(``,"");else o.push("No screenshot was captured for this scene.","");return`${o.join(`
|
|
4
4
|
`).trimEnd()}
|
|
5
|
-
`}async function
|
|
6
|
-
`)),outDir:r,mediaDir:
|
|
7
|
-
`);let
|
|
8
|
-
`),
|
|
9
|
-
`,{flag:"wx"}),await
|
|
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/dist/story-drivers.d.ts
CHANGED
|
@@ -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>
|
package/dist/story-drivers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{spawnOwnedProcess as
|
|
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
|
|
98
|
-
${
|
|
99
|
-
${
|
|
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
|
-
${
|
|
108
|
-
${
|
|
109
|
-
${
|
|
110
|
-
`}function
|
|
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(
|
|
113
|
+
maskSheet.replaceSync(${JSON.stringify(N)});
|
|
114
114
|
document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
|
|
115
|
-
const host = document.createElement('div'); host.id = ${JSON.stringify(
|
|
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:${
|
|
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 ${
|
|
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
|
|
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.
|
|
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.
|
|
61
|
-
"@stacksjs/cli": "0.75.
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
63
|
-
"@stacksjs/path": "0.75.
|
|
64
|
-
"@stacksjs/orm": "0.75.
|
|
65
|
-
"@stacksjs/stx": "^0.2.
|
|
66
|
-
"@stacksjs/testing": "0.75.
|
|
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.
|
|
73
|
-
"@stacksjs/server": "0.75.
|
|
72
|
+
"@stacksjs/alias": "0.75.667",
|
|
73
|
+
"@stacksjs/server": "0.75.667",
|
|
74
74
|
"better-dx": "^0.2.39"
|
|
75
75
|
}
|
|
76
76
|
}
|