@stacksjs/docs 0.75.590 → 0.75.592

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { discoverScreenshotModels, screenshotFixturePath, type ScreenshotFixtures, type ScreenshotModelOptions, type ScreenshotModelPlan } from './screenshot-models';
2
+ import { version as generatorVersion } from '../package.json';
2
3
  export type { ScreenshotFixtures, ScreenshotModel, ScreenshotModelOptions, ScreenshotModelPlan } from './screenshot-models';
3
4
  export declare function validateScreenshotConfig(config: ScreenshotConfig, root?: ReturnType<typeof process.cwd>): Promise<void>;
4
5
  /** Capture the explicit inventory; failures remain in the report and fail CI. */
@@ -11,6 +12,7 @@ export declare interface ScreenshotContext {
11
12
  profile: string
12
13
  viewport: ScreenshotViewport
13
14
  page: ScreenshotPage & { path: string }
15
+ httpStatus?: number
14
16
  }
15
17
  export declare interface ScreenshotPathContext { fixtures: ScreenshotFixtures, models: ScreenshotModelPlan, profile: string }
16
18
  export declare interface ScreenshotPage {
@@ -24,6 +26,7 @@ export declare interface ScreenshotPage {
24
26
  sources?: string[]
25
27
  profiles?: string[]
26
28
  waitFor: string
29
+ expectedStatus?: number
27
30
  prepare?: (context: ScreenshotContext) => Promise<void>
28
31
  ready?: (context: ScreenshotContext) => Promise<boolean>
29
32
  masks?: string[]
@@ -36,6 +39,7 @@ export declare interface ScreenshotConfig {
36
39
  viewports?: ScreenshotViewport[]
37
40
  profiles?: Record<string, { prepare?: (context: ScreenshotContext) => Promise<void> }>
38
41
  backend?: 'webkit' | 'chrome'
42
+ requireHttpStatus?: boolean
39
43
  timeoutMs?: number
40
44
  inputs?: string[]
41
45
  coverage?: { directories: string[], exclude?: Record<string, string> }
@@ -56,6 +60,7 @@ export declare interface ScreenshotResult {
56
60
  reason?: string
57
61
  path: string
58
62
  status: 'captured' | 'failed' | 'skipped'
63
+ httpStatus?: number
59
64
  file?: string
60
65
  sha256?: string
61
66
  error?: string
@@ -63,6 +68,7 @@ export declare interface ScreenshotResult {
63
68
  export declare interface ScreenshotReport {
64
69
  format: 1
65
70
  generator: '@stacksjs/docs/screenshots'
71
+ generatorVersion: string
66
72
  configHash: string
67
73
  backend: string
68
74
  bun: string
@@ -1,15 +1,15 @@
1
1
  // @bun
2
- import{createHash as ee}from"crypto";import{lstat as F,mkdir as B,mkdtemp as te,readFile as E,rename as W,rm as re,stat as se}from"fs/promises";import{dirname as ne,isAbsolute as q,join as m,relative as O,resolve as x}from"path";import{pathToFileURL as oe}from"url";import{createHash as I}from"crypto";import{readFile as z}from"fs/promises";import{existsSync as K}from"fs";import{isAbsolute as G,join as Q,relative as X,resolve as Y}from"path";import{loadModelRegistry as Z,modelFiles as H}from"@stacksjs/orm/model-registry";function j(r){let o=Object.entries(r).map(([e,i])=>{let c=Object.entries(i.attributes??{}),f=i.belongsTo??[],k=(Array.isArray(f)?f:Object.values(f)).map((p)=>typeof p==="string"?p:p&&typeof p==="object"?String(p.model??p.name??""):"").filter(Boolean),y=i.traits?.useApi,v=i.traits?.useSeeder??i.traits?.seedable,S=(p,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(p)),b=c.filter(([,p])=>p.required&&!p.nullable&&typeof p.factory!=="function"&&!Object.hasOwn(p,"default")).map(([p])=>p);return{name:String(i.name??e),table:i.table,primaryKey:String(i.primaryKey??"id"),...y?.uri?{api:String(y.uri)}:{},parents:[...new Set([...k,...Array.isArray(v?.after)?v.after.map(String):[]])].sort(),seederCount:typeof v?.count==="number"?v.count:null,factoryFields:c.filter(([,p])=>typeof p.factory==="function").map(([p])=>p),defaultFields:c.filter(([,p])=>Object.hasOwn(p,"default")).map(([p])=>p),requiredWithoutFactory:b,sensitiveFields:c.filter(([p,R])=>S(p,R)).map(([p])=>p),suggestedStates:[...new Set(["empty","populated",...y?.routes?.includes("show")?["detail"]:[],...y?.middleware?.length?["permission-denied"]:[],...i.traits?.useSoftDeletes||i.traits?.softDeletable?["archived"]:[]])]}}).sort((e,i)=>e.name.localeCompare(i.name)),d=new Set(o.map((e)=>e.name)),s=new Map(o.map((e)=>[e.name,e])),l=[];for(;;){let e=[...s.values()].filter((i)=>i.parents.every((c)=>!d.has(c)||l.includes(c)));if(!e.length)break;for(let i of e)l.push(i.name),s.delete(i.name)}let w=new Set,u=new Map,h=new Map,g=[],n=new Set,t=0;function a(e){u.set(e,t),h.set(e,t++),g.push(e),n.add(e);for(let f of s.get(e)?.parents??[]){if(!s.has(f))continue;if(!u.has(f))a(f),h.set(e,Math.min(h.get(e),h.get(f)));else if(n.has(f))h.set(e,Math.min(h.get(e),u.get(f)))}if(h.get(e)!==u.get(e))return;let i=[],c;do c=g.pop(),n.delete(c),i.push(c);while(c!==e);if(i.length>1||s.get(e)?.parents.includes(e))for(let f of i)w.add(f)}for(let e of s.keys())if(!u.has(e))a(e);return{models:o,creationOrder:l,cycles:[...w].sort(),blocked:[...s.keys()].filter((e)=>!w.has(e)),externalParents:[...new Set(o.flatMap((e)=>e.parents).filter((e)=>!d.has(e)))].sort()}}async function U(r,o={}){if(o===!1)return j({});if(o.directory!==void 0&&!o.directory.trim())throw Error("Model directory must not be empty");let d=Y(r,o.directory??"app/Models");if(G(o.directory??"")||X(r,d).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let s=o.includeDefaults?Q(r,"storage/framework/defaults/app/Models"):void 0;if(!K(d)&&!s)return j({});let l=[],w=await Z({userRoot:d,defaultsRoot:s,onImportError:(g)=>l.push(g)});if(l.length)throw Error(`Cannot inspect screenshot models: ${l.join(", ")}`);let u=j(w),h=[...H(d),...s?H(s):[]].sort();return u.sourceHash=I("sha256").update(Buffer.concat(await Promise.all(h.map((g)=>z(g))))).digest("hex"),u}function N(r,o,d,s){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(r))return r;let l=o?s.models.filter((h)=>h.name===o):s.models.filter((h)=>h.api&&r.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),w=l.length===1?l[0]:void 0;if(!w)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let u=d[w.name];if(!u)throw Error(`No screenshot fixture supplied for ${w.name}`);return r.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,g,n)=>{let t=g||n,a=t==="id"?w.primaryKey:t;if(w.sensitiveFields.includes(a)||/token|secret|password/i.test(t))throw Error(`Refusing to publish a sensitive route parameter: ${t}`);let e=u[a];if(e===void 0||e===""||typeof e!=="string"&&typeof e!=="number"||typeof e==="number"&&!Number.isFinite(e))throw Error(`Screenshot fixture ${w.name} has no ${t}`);return encodeURIComponent(String(e))})}import{spawnOwnedProcess as ie}from"@stacksjs/cli/owned-process";var xe=(r)=>r,M=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],A=(r)=>ee("sha256").update(r).digest("hex"),C=(r)=>/^[a-z0-9][a-z0-9._-]*$/i.test(r)&&!r.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r),J=(r)=>{let o=new URL(r);return o.origin+o.pathname};async function ae(r,o=process.cwd()){let d=new URL(r.baseUrl);if(!["http:","https:"].includes(d.protocol)||d.username||d.password||d.search||d.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!r.outDir||!r.pages.length)throw Error("outDir and at least one page are required");if(r.timeoutMs!==void 0&&(!Number.isFinite(r.timeoutMs)||r.timeoutMs<100||r.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(r.backend&&!["webkit","chrome"].includes(r.backend))throw Error("backend must be webkit or chrome");let s=Object.keys(r.profiles??{default:{}});if(!s.length||s.some((n)=>!C(n)))throw Error("Profile names must be safe filenames");let l=new Set,w=new Set;for(let n of r.pages){if(!C(n.id)||l.has(n.id))throw Error(`Duplicate or invalid screen id: ${n.id}`);if(l.add(n.id),!n.title.trim()||!n.description.trim()||!n.waitFor.trim())throw Error(`Screen ${n.id} needs title, description and waitFor`);if(typeof n.path!=="string"&&(typeof n.path!=="function"||!n.route))throw Error(`Screen ${n.id} needs a route pattern for its path resolver`);let t=new URL(typeof n.path==="string"?n.path:n.route,d);if(t.origin!==d.origin||t.username||t.password)throw Error(`Screen ${n.id} must stay on baseUrl's origin`);if(n.profiles?.some((a)=>!s.includes(a))||n.profiles?.length===0)throw Error(`Unknown or empty profiles for ${n.id}`);for(let a of n.sources??[]){let e=x(o,a);if(O(o,e).startsWith("..")||q(a))throw Error(`Source must be inside the project: ${a}`);await E(e),w.add(O(o,e).replaceAll("\\","/"))}}let u=new Set;for(let n of r.viewports??M){if(!C(n.name)||u.has(n.name)||![n.width,n.height].every((t)=>Number.isInteger(t)&&t>=200&&t<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");u.add(n.name)}if(!u.size)throw Error("At least one viewport is required");for(let n of r.inputs??[])await E(x(o,n));let h=[],g=new Set;for(let n of r.coverage?.directories??[]){let t=x(o,n);if(O(o,t).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await se(t)).isDirectory())throw Error(`Missing coverage directory: ${n}`);let a=0;for await(let e of new Bun.Glob("**/*.stx").scan({cwd:t,onlyFiles:!0})){a++;let i=O(o,m(t,e)).replaceAll("\\","/");if(g.add(i),!w.has(i)&&!r.coverage?.exclude?.[i]?.trim())h.push(i)}if(!a)throw Error(`No .stx screens found in ${n}`)}for(let[n,t]of Object.entries(r.coverage?.exclude??{}))if(!t.trim()||!g.has(n))throw Error(`Stale or unexplained coverage exclusion: ${n}`);if(h.length)throw Error(`Undocumented screens:
2
+ import{createHash as se}from"crypto";import{lstat as N,mkdir as C,mkdtemp as oe,readFile as E,rename as W,rm as ne,stat as ie}from"fs/promises";import{dirname as ae,isAbsolute as I,join as y,relative as M,resolve as k}from"path";import{pathToFileURL as ce}from"url";import{createHash as z}from"crypto";import{readFile as G}from"fs/promises";import{existsSync as Q}from"fs";import{isAbsolute as X,join as Y,relative as Z,resolve as ee}from"path";import{loadModelRegistry as te,modelFiles as J}from"@stacksjs/orm/model-registry";function U(r){let i=Object.entries(r).map(([e,n])=>{let a=Object.entries(n.attributes??{}),u=n.belongsTo??[],x=(Array.isArray(u)?u:Object.values(u)).map((p)=>typeof p==="string"?p:p&&typeof p==="object"?String(p.model??p.name??""):"").filter(Boolean),S=n.traits?.useApi,v=n.traits?.useSeeder??n.traits?.seedable,g=(p,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(p)),w=a.filter(([,p])=>p.required&&!p.nullable&&typeof p.factory!=="function"&&!Object.hasOwn(p,"default")).map(([p])=>p);return{name:String(n.name??e),table:n.table,primaryKey:String(n.primaryKey??"id"),...S?.uri?{api:String(S.uri)}:{},parents:[...new Set([...x,...Array.isArray(v?.after)?v.after.map(String):[]])].sort(),seederCount:typeof v?.count==="number"?v.count:null,factoryFields:a.filter(([,p])=>typeof p.factory==="function").map(([p])=>p),defaultFields:a.filter(([,p])=>Object.hasOwn(p,"default")).map(([p])=>p),requiredWithoutFactory:w,sensitiveFields:a.filter(([p,R])=>g(p,R)).map(([p])=>p),suggestedStates:[...new Set(["empty","populated",...S?.routes?.includes("show")?["detail"]:[],...S?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((e,n)=>e.name.localeCompare(n.name)),l=new Set(i.map((e)=>e.name)),s=new Map(i.map((e)=>[e.name,e])),d=[];for(;;){let e=[...s.values()].filter((n)=>n.parents.every((a)=>!l.has(a)||d.includes(a)));if(!e.length)break;for(let n of e)d.push(n.name),s.delete(n.name)}let m=new Set,f=new Map,h=new Map,b=[],o=new Set,t=0;function c(e){f.set(e,t),h.set(e,t++),b.push(e),o.add(e);for(let u of s.get(e)?.parents??[]){if(!s.has(u))continue;if(!f.has(u))c(u),h.set(e,Math.min(h.get(e),h.get(u)));else if(o.has(u))h.set(e,Math.min(h.get(e),f.get(u)))}if(h.get(e)!==f.get(e))return;let n=[],a;do a=b.pop(),o.delete(a),n.push(a);while(a!==e);if(n.length>1||s.get(e)?.parents.includes(e))for(let u of n)m.add(u)}for(let e of s.keys())if(!f.has(e))c(e);return{models:i,creationOrder:d,cycles:[...m].sort(),blocked:[...s.keys()].filter((e)=>!m.has(e)),externalParents:[...new Set(i.flatMap((e)=>e.parents).filter((e)=>!l.has(e)))].sort()}}async function F(r,i={}){if(i===!1)return U({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let l=ee(r,i.directory??"app/Models");if(X(i.directory??"")||Z(r,l).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let s=i.includeDefaults?Y(r,"storage/framework/defaults/app/Models"):void 0;if(!Q(l)&&!s)return U({});let d=[],m=await te({userRoot:l,defaultsRoot:s,onImportError:(b)=>d.push(b)});if(d.length)throw Error(`Cannot inspect screenshot models: ${d.join(", ")}`);let f=U(m),h=[...J(l),...s?J(s):[]].sort();return f.sourceHash=z("sha256").update(Buffer.concat(await Promise.all(h.map((b)=>G(b))))).digest("hex"),f}function T(r,i,l,s){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(r))return r;let d=i?s.models.filter((h)=>h.name===i):s.models.filter((h)=>h.api&&r.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),m=d.length===1?d[0]:void 0;if(!m)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let f=l[m.name];if(!f)throw Error(`No screenshot fixture supplied for ${m.name}`);return r.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,b,o)=>{let t=b||o,c=t==="id"?m.primaryKey:t;if(m.sensitiveFields.includes(c)||/token|secret|password/i.test(t))throw Error(`Refusing to publish a sensitive route parameter: ${t}`);let e=f[c];if(e===void 0||e===""||typeof e!=="string"&&typeof e!=="number"||typeof e==="number"&&!Number.isFinite(e))throw Error(`Screenshot fixture ${m.name} has no ${t}`);return encodeURIComponent(String(e))})}import{spawnOwnedProcess as de}from"@stacksjs/cli/owned-process";var O="0.75.592";var Pe=(r)=>r,P=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],H=(r)=>se("sha256").update(r).digest("hex"),B=(r)=>/^[a-z0-9][a-z0-9._-]*$/i.test(r)&&!r.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r),V=(r)=>{let i=new URL(r);return i.origin+i.pathname};async function le(r,i=process.cwd()){let l=new URL(r.baseUrl);if(!["http:","https:"].includes(l.protocol)||l.username||l.password||l.search||l.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!r.outDir||!r.pages.length)throw Error("outDir and at least one page are required");if(r.timeoutMs!==void 0&&(!Number.isFinite(r.timeoutMs)||r.timeoutMs<100||r.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(r.backend&&!["webkit","chrome"].includes(r.backend))throw Error("backend must be webkit or chrome");if(r.requireHttpStatus!==void 0&&typeof r.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let s=Object.keys(r.profiles??{default:{}});if(!s.length||s.some((o)=>!B(o)))throw Error("Profile names must be safe filenames");let d=new Set,m=new Set;for(let o of r.pages){if(!B(o.id)||d.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(d.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 t=new URL(typeof o.path==="string"?o.path:o.route,l);if(t.origin!==l.origin||t.username||t.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((c)=>!s.includes(c))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let c of o.sources??[]){let e=k(i,c);if(M(i,e).startsWith("..")||I(c))throw Error(`Source must be inside the project: ${c}`);await E(e),m.add(M(i,e).replaceAll("\\","/"))}}let f=new Set;for(let o of r.viewports??P){if(!B(o.name)||f.has(o.name)||![o.width,o.height].every((t)=>Number.isInteger(t)&&t>=200&&t<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");f.add(o.name)}if(!f.size)throw Error("At least one viewport is required");for(let o of r.inputs??[])await E(k(i,o));let h=[],b=new Set;for(let o of r.coverage?.directories??[]){let t=k(i,o);if(M(i,t).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await ie(t)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let c=0;for await(let e of new Bun.Glob("**/*.stx").scan({cwd:t,onlyFiles:!0})){c++;let n=M(i,y(t,e)).replaceAll("\\","/");if(b.add(n),!m.has(n)&&!r.coverage?.exclude?.[n]?.trim())h.push(n)}if(!c)throw Error(`No .stx screens found in ${o}`)}for(let[o,t]of Object.entries(r.coverage?.exclude??{}))if(!t.trim()||!b.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(h.length)throw Error(`Undocumented screens:
3
3
  ${h.sort().join(`
4
- `)}`)}async function V(r){let o=(await import(oe(r).href)).default;if(!o||typeof o!=="object")throw Error("Screenshot configuration must have a default export");return o}async function ce(r,o){let d=Date.now()+o;while(!await r()){if(Date.now()>=d)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function _(r,o){let d=r instanceof Error?r.message:"Screenshot capture failed";for(let s of o.redactEnv??[]){let l=process.env[s];if(l)d=d.replaceAll(l,"[redacted]")}return d.slice(0,1000)}async function le(r,o,d){let s=await V(r),l=x(d.root),w=x(l,d.outDir??s.outDir),u=[],h=await U(l,s.models);try{let g={...s.fixtures,...await s.data?.prepare(h)},n=s.backend??(process.platform==="darwin"?"webkit":"chrome"),t=s.timeoutMs??30000;for(let a of s.viewports??M){if(d.viewports?.length&&!d.viewports.includes(a.name))continue;for(let e of s.pages){if(d.only?.length&&!d.only.includes(e.id))continue;if(!(e.profiles??Object.keys(s.profiles??{default:{}})).includes(o))continue;let i={id:e.id,profile:o,viewport:a,title:e.title,description:e.description,...e.reason?{reason:e.reason}:{},path:new URL(typeof e.path==="string"?e.path:e.route,s.baseUrl).pathname,status:"failed"};if(u.push(i),e.skip){i.status="skipped",i.error=e.skip,process.send?.({type:"screenshot-result",result:i});continue}let c="starting the browser",f,P;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");f=new Bun.WebView({width:a.width,height:a.height,backend:n==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let k=typeof e.path==="function"?await e.path({fixtures:g,models:h,profile:o}):N(e.path,e.model,g,h),y=new URL(k,s.baseUrl);if(y.origin!==new URL(s.baseUrl).origin||y.username||y.password)throw Error("Resolved screenshot path must stay on the configured origin");let v={...e,path:k},S={view:f,baseUrl:s.baseUrl,profile:o,viewport:a,page:v};i.path=y.pathname,c="preparing the review profile",await s.profiles?.[o]?.prepare?.(S),c="opening the screen",await f.navigate(new URL(v.path,s.baseUrl).href),c="preparing the screen state",await e.prepare?.(S),c="waiting for screen readiness",await ce(async()=>Boolean(await f.evaluate(`Boolean(document.querySelector(${JSON.stringify(e.waitFor)}))`))&&(!e.ready||await e.ready(S)),t);let b=String(await f.evaluate("location.href"));if(J(b)!==J(new URL(v.path,s.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(c="loading fonts and visible images",await f.evaluate(`(async () => {
4
+ `)}`)}async function _(r){let i=(await import(ce(r).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function ue(r,i){let l=Date.now()+i;while(!await r()){if(Date.now()>=l)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function K(r,i){let l=r instanceof Error?r.message:"Screenshot capture failed";for(let s of i.redactEnv??[]){let d=process.env[s];if(d)l=l.replaceAll(d,"[redacted]")}return l.slice(0,1000)}async function pe(r,i,l){let s=await _(r),d=k(l.root),m=k(d,l.outDir??s.outDir),f=[],h=await F(d,s.models);try{let b={...s.fixtures,...await s.data?.prepare(h)},o=s.backend??(process.platform==="darwin"?"webkit":"chrome"),t=s.timeoutMs??30000;for(let c of s.viewports??P){if(l.viewports?.length&&!l.viewports.includes(c.name))continue;for(let e of s.pages){if(l.only?.length&&!l.only.includes(e.id))continue;if(!(e.profiles??Object.keys(s.profiles??{default:{}})).includes(i))continue;let n={id:e.id,profile:i,viewport:c,title:e.title,description:e.description,...e.reason?{reason:e.reason}:{},path:new URL(typeof e.path==="string"?e.path:e.route,s.baseUrl).pathname,status:"failed"};if(f.push(n),e.skip){n.status="skipped",n.error=e.skip,process.send?.({type:"screenshot-result",result:n});continue}let a="starting the browser",u,j;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");u=new Bun.WebView({width:c.width,height:c.height,backend:o==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let x=typeof e.path==="function"?await e.path({fixtures:b,models:h,profile:i}):T(e.path,e.model,b,h),S=new URL(x,s.baseUrl);if(S.origin!==new URL(s.baseUrl).origin||S.username||S.password)throw Error("Resolved screenshot path must stay on the configured origin");let v={...e,path:x},g={view:u,baseUrl:s.baseUrl,profile:i,viewport:c,page:v};n.path=S.pathname,a="preparing the review profile",await s.profiles?.[i]?.prepare?.(g),a="opening the screen",await u.navigate(new URL(v.path,s.baseUrl).href),a="checking the document HTTP status";let w=Number(await u.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(w)&&w>=100&&w<=599)g.httpStatus=n.httpStatus=w;if(!g.httpStatus&&(s.requireHttpStatus||e.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(e.expectedStatus!==void 0?g.httpStatus!==e.expectedStatus:w>=400)throw Error(`The screen returned HTTP ${w}${e.expectedStatus!==void 0?` instead of ${e.expectedStatus}`:"; check its route, access and fixture"}`);a="preparing the screen state",await e.prepare?.(g),a="waiting for screen readiness",await ue(async()=>Boolean(await u.evaluate(`Boolean(document.querySelector(${JSON.stringify(e.waitFor)}))`))&&(!e.ready||await e.ready(g)),t);let p=String(await u.evaluate("location.href"));if(V(p)!==V(new URL(v.path,s.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(a="loading fonts and visible images",await u.evaluate(`(async () => {
5
5
  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);
6
6
  for (const selector of ${JSON.stringify(['input[type="password"]',...e.masks??[]])}) for (const node of document.querySelectorAll(selector)) node.style.setProperty('visibility','hidden','important');
7
7
  await document.fonts.ready;
8
8
  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})}); }
9
9
  await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
10
- })()`),await f.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");c="saving the screenshot";let R=new Uint8Array(await(await f.screenshot()).arrayBuffer()),D=`${e.id}/${o}-${a.name}.png`,T=m(w,D);await B(ne(T),{recursive:!0});let L=m(d.staging,`${e.id}-${o}-${a.name}.png`);await Bun.write(L,R),await W(L,T),i.file=D,i.sha256=A(R),i.status="captured"})(),new Promise((k,y)=>{P=setTimeout(()=>{f?.close(),y(Error("Screenshot deadline exceeded"))},t)})])}catch(k){i.error=`${c}: ${_(k,s)}`}finally{if(P)clearTimeout(P);f?.close(),process.send?.({type:"screenshot-result",result:i})}}}return u}finally{await s.data?.cleanup?.()}}async function ke(r={}){if(r.list&&r.check)throw Error("Choose list or check, not both");let o=x(r.root??process.cwd()),d=x(o,r.config??"config/screenshots.ts"),s=await V(d);await ae(s,o);for(let t of r.only??[])if(!s.pages.some((a)=>a.id===t))throw Error(`Unknown screen: ${t}`);for(let t of r.viewports??[])if(!(s.viewports??M).some((a)=>a.name===t))throw Error(`Unknown viewport: ${t}`);let l=x(o,r.outDir??s.outDir),w=[...new Set([...s.inputs??[],...s.pages.flatMap((t)=>t.sources??[])])].sort(),u={format:1,generator:"@stacksjs/docs/screenshots",models:await U(o,s.models),configHash:A(Buffer.concat([await E(d),...await Promise.all(w.map((t)=>E(x(o,t))))])),inventory:s.pages.map((t)=>({id:t.id,title:t.title,path:new URL(typeof t.path==="string"?t.path:t.route,s.baseUrl).pathname,sources:t.sources??[],...t.skip?{skip:t.skip}:{}})),backend:s.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(r.list)return u;if(r.check){let t=JSON.parse(await E(m(l,"manifest.json"),"utf8"));if(t.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(t.configHash!==u.configHash||t.models?.sourceHash!==u.models.sourceHash||t.results.some((a)=>a.status==="failed"))throw Error("Screenshot inventory changed or the previous capture failed; capture again");for(let a of s.pages)for(let e of a.profiles??Object.keys(s.profiles??{default:{}}))for(let i of s.viewports??M){let c=t.results.find((f)=>f.id===a.id&&f.profile===e&&f.viewport.name===i.name);if(!c||!a.skip&&c.status!=="captured")throw Error(`Missing screenshot: ${a.id}/${e}-${i.name}`);if(c.file&&(O(l,x(l,c.file)).split(/[\\/]/)[0]===".."||q(O(l,x(l,c.file)))||A(await E(m(l,c.file)))!==c.sha256))throw Error(`Screenshot bytes changed: ${a.id}`)}return t}let h;try{let t=m(l,"manifest.json");if((await F(t)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(h=JSON.parse(await E(t,"utf8")),h.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest")}catch(t){if(t.code!=="ENOENT")throw t}let g=new Set(h?.results.map((t)=>t.file).filter(Boolean));for(let t of s.pages){let a=m(l,t.id);try{if((await F(a)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${t.id}`)}catch(e){if(e.code!=="ENOENT")throw e}for(let e of t.profiles??Object.keys(s.profiles??{default:{}}))for(let i of s.viewports??M){let c=`${t.id}/${e}-${i.name}.png`;try{if((await F(m(l,c))).isSymbolicLink()||!g.has(c))throw Error(`Refusing to overwrite an unowned screenshot: ${c}`)}catch(f){if(f.code!=="ENOENT")throw f}}}for(let t of["gallery.md","manifest.json.tmp"])try{if((await F(m(l,t))).isSymbolicLink()||!h)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${t}`)}catch(a){if(a.code!=="ENOENT")throw a}await B(l,{recursive:!0});let n=await te(m(l,".stacks-screenshots-"));await Bun.write(m(n,"bunfig.toml"),`preload = []
11
- `);try{for(let e of Object.keys(s.profiles??{default:{}})){let i=m(n,`${e}.json`),c=s.pages.filter((S)=>(!r.only?.length||r.only.includes(S.id))&&(S.profiles??Object.keys(s.profiles??{default:{}})).includes(e)),f=c.length*(s.viewports??M).filter((S)=>!r.viewports?.length||r.viewports.includes(S.name)).length;if(!f)continue;let P=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!P)throw Error("An installed Bun is required for screenshot workers");let k=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",o):import.meta.path,y=ie([P,"--no-env-file",`--config=${m(n,"bunfig.toml")}`,k,"--worker",d,e,JSON.stringify({...r,root:o,staging:n}),i],{ownerRuntime:P,cwd:o,env:process.env,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(S)=>{let b=S;if(b?.type==="screenshot-result"&&b.result)r.onProgress?.(b.result)}}),v;try{if((await Promise.race([y.exited,new Promise((b,p)=>{v=setTimeout(()=>{y.stop(),p(Error(`Screenshot worker timed out for ${e}`))},f*((s.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${e}`);u.results.push(...JSON.parse(await E(i,"utf8")))}catch(S){for(let b of c)for(let p of s.viewports??M){if(r.viewports?.length&&!r.viewports.includes(p.name))continue;u.results.push({id:b.id,profile:e,viewport:p,title:b.title,description:b.description,path:new URL(typeof b.path==="string"?b.path:b.route,s.baseUrl).pathname,status:"failed",error:_(S,s)})}}finally{if(v)clearTimeout(v);await y.stop()}}if(r.only?.length||r.viewports?.length)try{let e=JSON.parse(await E(m(l,"manifest.json"),"utf8"));if(e.configHash===u.configHash&&e.models?.sourceHash===u.models.sourceHash){let i=new Set(u.results.map((c)=>`${c.id}/${c.profile}/${c.viewport.name}`));u.results.unshift(...e.results.filter((c)=>!i.has(`${c.id}/${c.profile}/${c.viewport.name}`)))}}catch{}await B(l,{recursive:!0}),await Bun.write(m(l,"manifest.json.tmp"),`${JSON.stringify(u,null,2)}
12
- `),await W(m(l,"manifest.json.tmp"),m(l,"manifest.json"));let t=(e)=>e.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
13
- `," "),a=["# Screen captures","","Generated from the explicit screen inventory. Review the images before publishing.",""];for(let e of u.results)a.push(`## ${t(e.title)} (${e.profile}, ${e.viewport.name})`,"",t(e.description),"",...e.reason?[t(e.reason),""]:[],e.status==="captured"?`![${t(e.title)}](${e.file})`:`**${e.status}:** ${t(e.error??"No image")}`,"");return await Bun.write(m(l,"gallery.md"),`${a.join(`
10
+ })()`),await u.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");a="saving the screenshot";let D=new Uint8Array(await(await u.screenshot()).arrayBuffer()),A=`${e.id}/${i}-${c.name}.png`,L=y(m,A);await C(ae(L),{recursive:!0});let q=y(l.staging,`${e.id}-${i}-${c.name}.png`);await Bun.write(q,D),await W(q,L),n.file=A,n.sha256=H(D),n.status="captured"})(),new Promise((x,S)=>{j=setTimeout(()=>{u?.close(),S(Error("Screenshot deadline exceeded"))},t)})])}catch(x){n.error=`${a}: ${K(x,s)}`}finally{if(j)clearTimeout(j);u?.close(),process.send?.({type:"screenshot-result",result:n})}}}return f}finally{await s.data?.cleanup?.()}}async function Re(r={}){if(r.list&&r.check)throw Error("Choose list or check, not both");let i=k(r.root??process.cwd()),l=k(i,r.config??"config/screenshots.ts"),s=await _(l);await le(s,i);for(let t of r.only??[])if(!s.pages.some((c)=>c.id===t))throw Error(`Unknown screen: ${t}`);for(let t of r.viewports??[])if(!(s.viewports??P).some((c)=>c.name===t))throw Error(`Unknown viewport: ${t}`);let d=k(i,r.outDir??s.outDir),m=[...new Set([...s.inputs??[],...s.pages.flatMap((t)=>t.sources??[])])].sort(),f={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:O,models:await F(i,s.models),configHash:H(Buffer.concat([Buffer.from(O),await E(l),...await Promise.all(m.map((t)=>E(k(i,t))))])),inventory:s.pages.map((t)=>({id:t.id,title:t.title,path:new URL(typeof t.path==="string"?t.path:t.route,s.baseUrl).pathname,sources:t.sources??[],...t.skip?{skip:t.skip}:{}})),backend:s.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(r.list)return f;if(r.check){let t=JSON.parse(await E(y(d,"manifest.json"),"utf8"));if(t.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(t.generatorVersion!==O||t.configHash!==f.configHash||t.models?.sourceHash!==f.models.sourceHash||t.results.some((c)=>c.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let c of s.pages)for(let e of c.profiles??Object.keys(s.profiles??{default:{}}))for(let n of s.viewports??P){let a=t.results.find((u)=>u.id===c.id&&u.profile===e&&u.viewport.name===n.name);if(!a||!c.skip&&a.status!=="captured")throw Error(`Missing screenshot: ${c.id}/${e}-${n.name}`);if(a.file&&(M(d,k(d,a.file)).split(/[\\/]/)[0]===".."||I(M(d,k(d,a.file)))||H(await E(y(d,a.file)))!==a.sha256))throw Error(`Screenshot bytes changed: ${c.id}`)}return t}let h;try{let t=y(d,"manifest.json");if((await N(t)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(h=JSON.parse(await E(t,"utf8")),h.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((r.only?.length||r.viewports?.length)&&h.configHash!==f.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(t){if(t.code!=="ENOENT")throw t}let b=new Set(h?.results.map((t)=>t.file).filter(Boolean));for(let t of s.pages){let c=y(d,t.id);try{if((await N(c)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${t.id}`)}catch(e){if(e.code!=="ENOENT")throw e}for(let e of t.profiles??Object.keys(s.profiles??{default:{}}))for(let n of s.viewports??P){let a=`${t.id}/${e}-${n.name}.png`;try{if((await N(y(d,a))).isSymbolicLink()||!b.has(a))throw Error(`Refusing to overwrite an unowned screenshot: ${a}`)}catch(u){if(u.code!=="ENOENT")throw u}}}for(let t of["gallery.md","manifest.json.tmp"])try{if((await N(y(d,t))).isSymbolicLink()||!h)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${t}`)}catch(c){if(c.code!=="ENOENT")throw c}await C(d,{recursive:!0});let o=await oe(y(d,".stacks-screenshots-"));await Bun.write(y(o,"bunfig.toml"),`preload = []
11
+ `);try{for(let e of Object.keys(s.profiles??{default:{}})){let n=y(o,`${e}.json`),a=s.pages.filter((g)=>(!r.only?.length||r.only.includes(g.id))&&(g.profiles??Object.keys(s.profiles??{default:{}})).includes(e)),u=a.length*(s.viewports??P).filter((g)=>!r.viewports?.length||r.viewports.includes(g.name)).length;if(!u)continue;let j=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!j)throw Error("An installed Bun is required for screenshot workers");let x=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,S=de([j,"--no-env-file",`--config=${y(o,"bunfig.toml")}`,x,"--worker",l,e,JSON.stringify({...r,root:i,staging:o}),n],{ownerRuntime:j,cwd:i,env:process.env,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(g)=>{let w=g;if(w?.type==="screenshot-result"&&w.result)r.onProgress?.(w.result)}}),v;try{if((await Promise.race([S.exited,new Promise((w,p)=>{v=setTimeout(()=>{S.stop(),p(Error(`Screenshot worker timed out for ${e}`))},u*((s.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${e}`);f.results.push(...JSON.parse(await E(n,"utf8")))}catch(g){for(let w of a)for(let p of s.viewports??P){if(r.viewports?.length&&!r.viewports.includes(p.name))continue;f.results.push({id:w.id,profile:e,viewport:p,title:w.title,description:w.description,path:new URL(typeof w.path==="string"?w.path:w.route,s.baseUrl).pathname,status:"failed",error:K(g,s)})}}finally{if(v)clearTimeout(v);await S.stop()}}if(r.only?.length||r.viewports?.length)try{let e=JSON.parse(await E(y(d,"manifest.json"),"utf8"));if(e.configHash===f.configHash&&e.models?.sourceHash===f.models.sourceHash){let n=new Set(f.results.map((a)=>`${a.id}/${a.profile}/${a.viewport.name}`));f.results.unshift(...e.results.filter((a)=>!n.has(`${a.id}/${a.profile}/${a.viewport.name}`)))}}catch{}for(let e of f.results){if(e.status!=="failed"||e.file)continue;let n=h?.results.find((a)=>a.id===e.id&&a.profile===e.profile&&a.viewport.name===e.viewport.name);if(n?.file)e.file=n.file,e.sha256=n.sha256}await C(d,{recursive:!0}),await Bun.write(y(d,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
12
+ `),await W(y(d,"manifest.json.tmp"),y(d,"manifest.json"));let t=(e)=>e.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
13
+ `," "),c=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${O}. Review the images before publishing.`,""];for(let e of f.results)c.push(`## ${t(e.title)} (${e.profile}, ${e.viewport.name})`,"",t(e.description),"",...e.reason?[t(e.reason),""]:[],e.status==="captured"?`![${t(e.title)}](${e.file})`:`**${e.status}:** ${t(e.error??"No image")}`,"");return await Bun.write(y(d,"gallery.md"),`${c.join(`
14
14
  `)}
15
- `),u}finally{await re(n,{recursive:!0,force:!0})}}if(import.meta.main&&process.argv[2]==="--worker")try{let r=await le(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(r))}catch{process.exitCode=1}export{ke as captureScreenshots,xe as defineScreenshotConfig,U as discoverScreenshotModels,j as planScreenshotModels,N as screenshotFixturePath,ae as validateScreenshotConfig};
15
+ `),f}finally{await ne(o,{recursive:!0,force:!0})}}if(import.meta.main&&process.argv[2]==="--worker")try{let r=await pe(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(r))}catch{process.exitCode=1}export{Re as captureScreenshots,Pe as defineScreenshotConfig,F as discoverScreenshotModels,U as planScreenshotModels,T as screenshotFixturePath,le as validateScreenshotConfig};
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.590",
5
+ "version": "0.75.592",
6
6
  "description": "The Stacks way to document.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,15 +58,15 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@stacksjs/bunpress": "^0.2.25",
61
- "@stacksjs/cli": "0.75.590",
62
- "@stacksjs/config": "0.75.590",
63
- "@stacksjs/path": "0.75.590",
64
- "@stacksjs/orm": "0.75.590",
61
+ "@stacksjs/cli": "0.75.592",
62
+ "@stacksjs/config": "0.75.592",
63
+ "@stacksjs/path": "0.75.592",
64
+ "@stacksjs/orm": "0.75.592",
65
65
  "@stacksjs/stx": "^0.2.872"
66
66
  },
67
67
  "devDependencies": {
68
- "@stacksjs/alias": "0.75.590",
69
- "@stacksjs/server": "0.75.590",
68
+ "@stacksjs/alias": "0.75.592",
69
+ "@stacksjs/server": "0.75.592",
70
70
  "better-dx": "^0.2.39"
71
71
  }
72
72
  }