@stacksjs/docs 0.75.585 → 0.75.590
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/screenshot-models.d.ts +30 -0
- package/dist/screenshot-models.js +2 -0
- package/dist/screenshots.d.ts +83 -0
- package/dist/screenshots.js +15 -0
- package/package.json +7 -5
package/README.md
CHANGED
|
@@ -36,3 +36,7 @@ bun test ./storage/framework/core/docs/tests
|
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
MIT license. Contributions follow the Stacks repository conventions.
|
|
39
|
+
|
|
40
|
+
## Automated UI documentation
|
|
41
|
+
|
|
42
|
+
`@stacksjs/docs/screenshots` exports `defineScreenshotConfig`, `validateScreenshotConfig` and `captureScreenshots`. Run a configured inventory with `buddy docs:screenshots`; use `--list` to verify template coverage and `--check` to validate saved captures. Each authentication profile owns a separate Bun WebView worker process. See the [screen documentation guide](https://stacksjs.com/docs/guide/screenshots) for readiness hooks, role setup, masks, artifacts and CI examples.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Metadata only: factories are detected, never executed by the planner. */
|
|
2
|
+
export declare function planScreenshotModels(definitions: Record<string, Definition>): ScreenshotModelPlan;
|
|
3
|
+
export declare function discoverScreenshotModels(root: string, options?: ScreenshotModelOptions | false): Promise<ScreenshotModelPlan>;
|
|
4
|
+
/** Bind concrete fixture fields to [id], [slug], or :id route parameters. */
|
|
5
|
+
export declare function screenshotFixturePath(path: string, model: string | undefined, fixtures: ScreenshotFixtures, plan: ScreenshotModelPlan): string;
|
|
6
|
+
export declare interface ScreenshotModel {
|
|
7
|
+
name: string
|
|
8
|
+
table?: string
|
|
9
|
+
primaryKey: string
|
|
10
|
+
api?: string
|
|
11
|
+
parents: string[]
|
|
12
|
+
seederCount: number | null
|
|
13
|
+
factoryFields: string[]
|
|
14
|
+
defaultFields: string[]
|
|
15
|
+
requiredWithoutFactory: string[]
|
|
16
|
+
sensitiveFields: string[]
|
|
17
|
+
suggestedStates: string[]
|
|
18
|
+
}
|
|
19
|
+
export declare interface ScreenshotModelPlan {
|
|
20
|
+
models: ScreenshotModel[]
|
|
21
|
+
creationOrder: string[]
|
|
22
|
+
cycles: string[]
|
|
23
|
+
blocked: string[]
|
|
24
|
+
externalParents: string[]
|
|
25
|
+
sourceHash?: string
|
|
26
|
+
}
|
|
27
|
+
export declare interface ScreenshotModelOptions { directory?: string, includeDefaults?: boolean }
|
|
28
|
+
export type ScreenshotFixtures = Record<string, Record<string, string | number>>;
|
|
29
|
+
declare type Definition = Record<string, any>;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{createHash as k}from"crypto";import{readFile as O}from"fs/promises";import{existsSync as D}from"fs";import{isAbsolute as P,join as R,relative as j,resolve as A}from"path";import{loadModelRegistry as E,modelFiles as M}from"@stacksjs/orm/model-registry";function S(d){let i=Object.entries(d).map(([e,r])=>{let a=Object.entries(r.attributes??{}),c=r.belongsTo??[],x=(Array.isArray(c)?c:Object.values(c)).map((t)=>typeof t==="string"?t:t&&typeof t==="object"?String(t.model??t.name??""):"").filter(Boolean),w=r.traits?.useApi,b=r.traits?.useSeeder??r.traits?.seedable,v=(t,y)=>Boolean(y.hidden||y.encrypted||y.personal||/password|token|secret|api.?key|email|phone|address/i.test(t)),F=a.filter(([,t])=>t.required&&!t.nullable&&typeof t.factory!=="function"&&!Object.hasOwn(t,"default")).map(([t])=>t);return{name:String(r.name??e),table:r.table,primaryKey:String(r.primaryKey??"id"),...w?.uri?{api:String(w.uri)}:{},parents:[...new Set([...x,...Array.isArray(b?.after)?b.after.map(String):[]])].sort(),seederCount:typeof b?.count==="number"?b.count:null,factoryFields:a.filter(([,t])=>typeof t.factory==="function").map(([t])=>t),defaultFields:a.filter(([,t])=>Object.hasOwn(t,"default")).map(([t])=>t),requiredWithoutFactory:F,sensitiveFields:a.filter(([t,y])=>v(t,y)).map(([t])=>t),suggestedStates:[...new Set(["empty","populated",...w?.routes?.includes("show")?["detail"]:[],...w?.middleware?.length?["permission-denied"]:[],...r.traits?.useSoftDeletes||r.traits?.softDeletable?["archived"]:[]])]}}).sort((e,r)=>e.name.localeCompare(r.name)),u=new Set(i.map((e)=>e.name)),n=new Map(i.map((e)=>[e.name,e])),f=[];for(;;){let e=[...n.values()].filter((r)=>r.parents.every((a)=>!u.has(a)||f.includes(a)));if(!e.length)break;for(let r of e)f.push(r.name),n.delete(r.name)}let o=new Set,l=new Map,s=new Map,p=[],h=new Set,g=0;function m(e){l.set(e,g),s.set(e,g++),p.push(e),h.add(e);for(let c of n.get(e)?.parents??[]){if(!n.has(c))continue;if(!l.has(c))m(c),s.set(e,Math.min(s.get(e),s.get(c)));else if(h.has(c))s.set(e,Math.min(s.get(e),l.get(c)))}if(s.get(e)!==l.get(e))return;let r=[],a;do a=p.pop(),h.delete(a),r.push(a);while(a!==e);if(r.length>1||n.get(e)?.parents.includes(e))for(let c of r)o.add(c)}for(let e of n.keys())if(!l.has(e))m(e);return{models:i,creationOrder:f,cycles:[...o].sort(),blocked:[...n.keys()].filter((e)=>!o.has(e)),externalParents:[...new Set(i.flatMap((e)=>e.parents).filter((e)=>!u.has(e)))].sort()}}async function N(d,i={}){if(i===!1)return S({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let u=A(d,i.directory??"app/Models");if(P(i.directory??"")||j(d,u).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let n=i.includeDefaults?R(d,"storage/framework/defaults/app/Models"):void 0;if(!D(u)&&!n)return S({});let f=[],o=await E({userRoot:u,defaultsRoot:n,onImportError:(p)=>f.push(p)});if(f.length)throw Error(`Cannot inspect screenshot models: ${f.join(", ")}`);let l=S(o),s=[...M(u),...n?M(n):[]].sort();return l.sourceHash=k("sha256").update(Buffer.concat(await Promise.all(s.map((p)=>O(p))))).digest("hex"),l}function W(d,i,u,n){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(d))return d;let f=i?n.models.filter((s)=>s.name===i):n.models.filter((s)=>s.api&&d.replace(/^\//,"").startsWith(`${s.api.replace(/^\//,"")}/`)),o=f.length===1?f[0]:void 0;if(!o)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let l=u[o.name];if(!l)throw Error(`No screenshot fixture supplied for ${o.name}`);return d.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(s,p,h)=>{let g=p||h,m=g==="id"?o.primaryKey:g;if(o.sensitiveFields.includes(m)||/token|secret|password/i.test(g))throw Error(`Refusing to publish a sensitive route parameter: ${g}`);let e=l[m];if(e===void 0||e===""||typeof e!=="string"&&typeof e!=="number"||typeof e==="number"&&!Number.isFinite(e))throw Error(`Screenshot fixture ${o.name} has no ${g}`);return encodeURIComponent(String(e))})}export{N as discoverScreenshotModels,S as planScreenshotModels,W as screenshotFixturePath};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { discoverScreenshotModels, screenshotFixturePath, type ScreenshotFixtures, type ScreenshotModelOptions, type ScreenshotModelPlan } from './screenshot-models';
|
|
2
|
+
export type { ScreenshotFixtures, ScreenshotModel, ScreenshotModelOptions, ScreenshotModelPlan } from './screenshot-models';
|
|
3
|
+
export declare function validateScreenshotConfig(config: ScreenshotConfig, root?: ReturnType<typeof process.cwd>): Promise<void>;
|
|
4
|
+
/** Capture the explicit inventory; failures remain in the report and fail CI. */
|
|
5
|
+
export declare function captureScreenshots(options?: ScreenshotOptions): Promise<ScreenshotReport>;
|
|
6
|
+
export declare const defineScreenshotConfig: (config: ScreenshotConfig) => ScreenshotConfig;
|
|
7
|
+
export declare interface ScreenshotViewport { name: string, width: number, height: number }
|
|
8
|
+
export declare interface ScreenshotContext {
|
|
9
|
+
view: Bun.WebView
|
|
10
|
+
baseUrl: string
|
|
11
|
+
profile: string
|
|
12
|
+
viewport: ScreenshotViewport
|
|
13
|
+
page: ScreenshotPage & { path: string }
|
|
14
|
+
}
|
|
15
|
+
export declare interface ScreenshotPathContext { fixtures: ScreenshotFixtures, models: ScreenshotModelPlan, profile: string }
|
|
16
|
+
export declare interface ScreenshotPage {
|
|
17
|
+
id: string
|
|
18
|
+
title: string
|
|
19
|
+
path: string | ((context: ScreenshotPathContext) => string | Promise<string>)
|
|
20
|
+
route?: string
|
|
21
|
+
description: string
|
|
22
|
+
reason?: string
|
|
23
|
+
model?: string
|
|
24
|
+
sources?: string[]
|
|
25
|
+
profiles?: string[]
|
|
26
|
+
waitFor: string
|
|
27
|
+
prepare?: (context: ScreenshotContext) => Promise<void>
|
|
28
|
+
ready?: (context: ScreenshotContext) => Promise<boolean>
|
|
29
|
+
masks?: string[]
|
|
30
|
+
skip?: string
|
|
31
|
+
}
|
|
32
|
+
export declare interface ScreenshotConfig {
|
|
33
|
+
baseUrl: string
|
|
34
|
+
outDir: string
|
|
35
|
+
pages: ScreenshotPage[]
|
|
36
|
+
viewports?: ScreenshotViewport[]
|
|
37
|
+
profiles?: Record<string, { prepare?: (context: ScreenshotContext) => Promise<void> }>
|
|
38
|
+
backend?: 'webkit' | 'chrome'
|
|
39
|
+
timeoutMs?: number
|
|
40
|
+
inputs?: string[]
|
|
41
|
+
coverage?: { directories: string[], exclude?: Record<string, string> }
|
|
42
|
+
redactEnv?: string[]
|
|
43
|
+
models?: ScreenshotModelOptions | false
|
|
44
|
+
fixtures?: ScreenshotFixtures
|
|
45
|
+
data?: {
|
|
46
|
+
prepare: (plan: ScreenshotModelPlan) => Promise<ScreenshotFixtures>
|
|
47
|
+
cleanup?: () => Promise<void>
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export declare interface ScreenshotResult {
|
|
51
|
+
id: string
|
|
52
|
+
profile: string
|
|
53
|
+
viewport: ScreenshotViewport
|
|
54
|
+
title: string
|
|
55
|
+
description: string
|
|
56
|
+
reason?: string
|
|
57
|
+
path: string
|
|
58
|
+
status: 'captured' | 'failed' | 'skipped'
|
|
59
|
+
file?: string
|
|
60
|
+
sha256?: string
|
|
61
|
+
error?: string
|
|
62
|
+
}
|
|
63
|
+
export declare interface ScreenshotReport {
|
|
64
|
+
format: 1
|
|
65
|
+
generator: '@stacksjs/docs/screenshots'
|
|
66
|
+
configHash: string
|
|
67
|
+
backend: string
|
|
68
|
+
bun: string
|
|
69
|
+
results: ScreenshotResult[]
|
|
70
|
+
models: ScreenshotModelPlan
|
|
71
|
+
inventory: Array<{ id: string, title: string, path: string, sources: string[], skip?: string }>
|
|
72
|
+
}
|
|
73
|
+
export declare interface ScreenshotOptions {
|
|
74
|
+
config?: string
|
|
75
|
+
root?: string
|
|
76
|
+
outDir?: string
|
|
77
|
+
only?: string[]
|
|
78
|
+
viewports?: string[]
|
|
79
|
+
list?: boolean
|
|
80
|
+
check?: boolean
|
|
81
|
+
onProgress?: (result: ScreenshotResult) => void
|
|
82
|
+
}
|
|
83
|
+
export { discoverScreenshotModels, planScreenshotModels, screenshotFixturePath } from './screenshot-models';
|
|
@@ -0,0 +1,15 @@
|
|
|
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:
|
|
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 () => {
|
|
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
|
+
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
|
+
await document.fonts.ready;
|
|
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
|
+
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"?``:`**${e.status}:** ${t(e.error??"No image")}`,"");return await Bun.write(m(l,"gallery.md"),`${a.join(`
|
|
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};
|
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.590",
|
|
6
6
|
"description": "The Stacks way to document.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,13 +58,15 @@
|
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@stacksjs/bunpress": "^0.2.25",
|
|
61
|
-
"@stacksjs/
|
|
62
|
-
"@stacksjs/
|
|
61
|
+
"@stacksjs/cli": "0.75.590",
|
|
62
|
+
"@stacksjs/config": "0.75.590",
|
|
63
|
+
"@stacksjs/path": "0.75.590",
|
|
64
|
+
"@stacksjs/orm": "0.75.590",
|
|
63
65
|
"@stacksjs/stx": "^0.2.872"
|
|
64
66
|
},
|
|
65
67
|
"devDependencies": {
|
|
66
|
-
"@stacksjs/alias": "0.75.
|
|
67
|
-
"@stacksjs/server": "0.75.
|
|
68
|
+
"@stacksjs/alias": "0.75.590",
|
|
69
|
+
"@stacksjs/server": "0.75.590",
|
|
68
70
|
"better-dx": "^0.2.39"
|
|
69
71
|
}
|
|
70
72
|
}
|