@zappie/check 0.14.0 → 0.16.0
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/CHANGELOG.md +27 -0
- package/README.md +40 -0
- package/dist/chunk-PWFNNCJC.js +1 -0
- package/dist/index.d.ts +55 -8
- package/dist/index.js +9 -4
- package/dist/step-worker.js +1 -1
- package/package.json +4 -3
- package/schema/check-result.v1.json +3 -1
- package/dist/chunk-ISB7GXMV.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,SITE_ENV,binaryArgs,checkConfig,checkLint,command,inCliState,isolated,json,loadConfig,owned,problem,readCssInputs,relative,scriptArgs,siteFilesFor,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-ISB7GXMV.js";import{SITE_CODE_FOLDERS,carriesSecrets,developerMayChange,inSiteCode,isTestFile,zappieManages}from"./chunk-DX7SE6KL.js";import path2 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry.hasInstallScript){scripted.push(`${name}@${entry.version}`)}if(entry.name){aliases.set(path.join(base,key),entry.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry of await list(nodeModules)){const directory=path.join(nodeModules,entry);if(entry===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry}/${item}`)}}else if(!entry.startsWith(".")){await visit(directory,entry)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;try{manifest=await json(path2.join(cwd,"package.json"))}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry=>matches(entry,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path2.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path2.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry=>entry===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value2=loaded.value;return Array.isArray(value2?.packages?.allow)?value2.packages.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}function matches(pattern,value2){return pattern.endsWith("/*")?value2.startsWith(pattern.slice(0,-1)):pattern===value2}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path2.dirname(directory)){const found=path2.join(directory,"node_modules",...name.split("/"));if(await json(path2.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path2.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile2}from"fs/promises";import path3 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();if(!timeout.aborted&¬Installed(error)){return withProblems(unavailable(mode,`Could not audit dependencies because ${invocation.executable} isn't installed.`,missingManagerFix(invocation.executable),relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path3.resolve(cwd);for(;;){if(directory!==path3.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path3.resolve(cwd))){return null}for(const name of names){const candidate=path3.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path3.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile2(path3.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path3.relative(directory,cwd).replaceAll(path3.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path3.relative(cwd,lockfile2).replaceAll(path3.sep,"/")}function notInstalled(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"&&"syscall"in error&&typeof error.syscall==="string"&&error.syscall.startsWith("spawn")}function missingManagerFix(executable){return executable==="pnpm"?"Run corepack enable, or install pnpm, then run zappie check again.":"Install Node.js with npm, then run zappie check again."}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value2=JSON.parse(source);requireAuditReport(manager,value2);const parsed=manager==="npm"?npmAdvisories(value2):pnpmAdvisories(value2);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value2){if(record(value2.error)){throw new Error(string(value2.error.message)??string(value2.error.code)??string(value2.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value2.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value2.advisories)&&!record(value2.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value2){if(!record(value2.advisories)){return[]}return Object.entries(value2.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value2){if(!record(value2.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName,raw]of Object.entries(value2.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value2,problems=[]){if(value2===void 0){return[]}if(!Array.isArray(value2)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value2.forEach((entry,index)=>{if(!ignoreEntry(entry)||!entry.id.trim()||!entry.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry.id}.`));return}const expiry=Date.parse(`${entry.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value2){return record(value2)&&typeof value2.id==="string"&&typeof value2.reason==="string"&&typeof value2.until==="string"}function npmUpgrade(value2){if(record(value2)&&typeof value2.name==="string"&&typeof value2.version==="string"){return{upgradePackage:value2.name,upgradeVersion:value2.version}}if(value2===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value2){if(!value2||value2==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value2)?.[1]??null}function ghsaFrom(value2){const id=value2?/GHSA-[\w-]+/i.exec(value2)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value2){return value2.trim().toLowerCase()}function malicious(value2){return/^MAL-/i.test(value2.trim())}function normalizedSeverity(value2){const severity=typeof value2==="string"?value2.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value2){return typeof value2==="string"?value2:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}import{access as access3,readFile as readFile5}from"fs/promises";import path6 from"path";import{readFile as readFile3,readdir as readdir2}from"fs/promises";import path4 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path4.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path4.relative(root,file).split(path4.sep).join("/"),bytes:gzipSync(await readFile3(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry of await readdir2(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path4.join(directory,entry.name);if(entry.isDirectory()){await collect(file,files)}else if(entry.isFile()){files.push(file)}}}import{readFile as readFile4}from"fs/promises";import path5 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>routeSource(entry.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>entry.isEntry&&!routeSource(entry.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry=>Boolean(entry)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}async function graphCssSizes(cwd,manifest,roots){const files=new Set([...closure(manifest,roots)].flatMap(key=>manifest[key]?.css??[]));return Promise.all([...files].sort().map(async file=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry=manifest[key];if(!entry){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeId(manifest,key){return(manifest[key]?.src??key).replace(/\?.*$/,"").replace(/^\/?app\//,"").replace(/\.[^./]+$/,"")}function routeSource(value2){return value2.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;async function checkBudgets({cwd,signal}){signal?.throwIfAborted();const manifestFile=path6.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile5(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const problems=[];let failed=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed||=over;problems.push(routeProblem(route,sizes,limits.jsKbGz,over))}const routeCss=config.budgets?.routeCssKbGz;const perRoute=typeof routeCss==="object"?routeCss:void 0;const measured=[];for(const route of routes){const id=routeId(manifest,route);const sizes=await graphCssSizes(cwd,manifest,[...clients,route]);const limitKb=typeof routeCss==="object"?routeCss[id]:routeCss;const missing3=perRoute!==void 0&&limitKb===void 0;const over=limitKb!==void 0&&total(sizes)>limitKb*KIB;failed||=over||missing3;measured.push([id,total(sizes)]);problems.push(routeCssProblem(id,sizes,limitKb,over,missing3))}const ids=new Set(measured.map(([id])=>id));for(const key of Object.keys(perRoute??{}).filter(key2=>!ids.has(key2))){failed=true;problems.push(problem(`budgets.routeCssKbGz names ${key}, which is not a route in this build. Its routes are ${[...ids].join(", ")}.`,"Rename the key to the route id it means, or remove it. A route id is the route file's path under app/ without its extension.",{rule:"budgets/css-route-unknown",file:"zappie.config.ts"}))}if(typeof routeCss!=="number"){problems.push(routeCssRecord(measured))}const styles=await cssSizes(cwd);const cssOver=routeCss===void 0&&total(styles)>limits.cssKbGz*KIB;failed||=cssOver;problems.push(cssProblem(styles,routeCss===void 0?limits.cssKbGz:void 0,cssOver));problems.push(problem(`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function routeCssProblem(id,sizes,limitKb,over,missing3){const bytes=total(sizes);const limit=missing3?"budgets.routeCssKbGz has no entry for it":limitKb===void 0?"no limit set: budgets.routeCssKbGz sets one":`limit ${limitKb*KIB} B`;return problem(`${id}: ${bytes} B gzip of CSS on first load (${limit}).${over?` Stylesheets: ${sizes.map(({file,bytes:size})=>`${file} (${size} B)`).join(", ")}.`:""}`,missing3?`Add ${JSON.stringify(id)}: ${suggestedKb(bytes)} to budgets.routeCssKbGz, the measured figure with 10 percent headroom.`:over?"Move styles only one route or overlay draws out of the root stylesheet and into a stylesheet that route or overlay imports.":null,{rule:missing3?"budgets/css-route-missing":over?"budgets/css-route-over":"budgets/css-route",file:"build/client/.vite/manifest.json"})}function routeCssRecord(measured){const entries=measured.map(([id,bytes])=>` ${JSON.stringify(id)}: ${suggestedKb(bytes)},`).join("\n");return problem("Each route's first-load CSS with 10 percent headroom, as a budgets.routeCssKbGz record.",`Paste it into budgets in zappie.config.ts, so the build fails a route whose CSS grows past it:
|
|
1
|
+
import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,SITE_ENV,advised,advises,binaryArgs,checkConfig,checkLint,command,hostsFor,inCliState,isolated,json,loadConfig,owned,problem,readCssInputs,relative,scriptArgs,siteFilesFor,siteHosts,skipped,step,supportsTypeScriptImport,validateBrand,warning}from"./chunk-PWFNNCJC.js";import{SITE_CODE_FOLDERS,carriesSecrets,developerMayChange,inSiteCode,isTestFile,zappieManages}from"./chunk-DX7SE6KL.js";import{readFile as readFile3}from"fs/promises";import path3 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry2]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry2.hasInstallScript){scripted.push(`${name}@${entry2.version}`)}if(entry2.name){aliases.set(path.join(base,key),entry2.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry2 of await list(nodeModules)){const directory=path.join(nodeModules,entry2);if(entry2===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry2.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry2}/${item}`)}}else if(!entry2.startsWith(".")){await visit(directory,entry2)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}import{lstat,readFile as readFile2}from"fs/promises";import path2 from"path";var MAX_WORKSPACE=64<<10;var NAME=/^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/i;var MAX_NAME=214;var MAX_RANGE=256;var NR="(?:0|[1-9]\\d*)";var XR=`(?:${NR}|[xX*])`;var PART="[0-9A-Za-z-]+";var QUALIFIER=`(?:-${PART}(?:\\.${PART})*)?(?:\\+${PART}(?:\\.${PART})*)?`;var PARTIAL=`v?${XR}(?:\\.${XR}(?:\\.${XR}${QUALIFIER})?)?`;var SIMPLE=new RegExp(`^(?:~>|[~^]|[<>]=?|=)?${PARTIAL}$`);var HYPHEN=new RegExp(`^${PARTIAL}\\s+-\\s+${PARTIAL}$`);var PARENT=/[^ |@]>/;var RANGE_CHARACTERS=/^[\x20-\x7e]+$/;var REFUSED_VALUE="is not a version or version range: aliases, protocols, paths, tags and references are not allowed";var REFUSED_KEY="must name a registry package: name, @scope/name, name@range or parent>child";function versionRange(value2){if(typeof value2!=="string"||!RANGE_CHARACTERS.test(value2)||value2.trim()===""||value2.length>MAX_RANGE){return false}return value2.split("||").every(range=>{const trimmed=range.trim();if(trimmed===""){return false}if(HYPHEN.test(trimmed)){return true}return trimmed.replace(/(~>|[~^]|[<>]=?|=)\s+/g,"$1").split(/\s+/).every(part=>SIMPLE.test(part))})}function overrideSelector(key){const at=key.search(PARENT);if(at<0){return packageSelector(key)}return packageSelector(key.slice(0,at+1))&&packageSelector(key.slice(at+2))}function packageSelector(selector){const at=selector.lastIndexOf("@");if(at<=0){return packageName(selector)}return packageName(selector.slice(0,at))&&versionRange(selector.slice(at+1))}function packageName(name){return name.length<=MAX_NAME&&NAME.test(name)}function overrideProblem(key,value2){if(!overrideSelector(key)){return`overrides entry ${JSON.stringify(key)} ${REFUSED_KEY}`}if(!versionRange(value2)){return`overrides entry ${JSON.stringify(key)}: ${JSON.stringify(value2)} ${REFUSED_VALUE}`}return null}function readOverrides(text){const lines=text.replace(/^\uFEFF/,"").split("\n").map(line=>line.replace(/\r$/,""));const starts=[];for(const[index,line]of lines.entries()){if(/^(?:overrides|'overrides'|"overrides")[ \t]*:(?:[ \t]|$)/.test(line)){starts.push(index)}}if(starts.length===0){return{overrides:[]}}if(starts.length>1){return failure(starts[1]+1,"overrides is set twice")}const start=starts[0];const first3=lines[start];const head=withoutComment(first3.slice(first3.indexOf(":")+1));if(head===null){return failure(start+1,"overrides must be a map of package names to versions")}const entries=head.trim()===""?blockEntries(lines,start):flowEntries(head.trim(),start);if(entries.problem!==void 0){return failure(entries.line,entries.problem)}const seen=new Set;for(const{line,key,value:value2}of entries.pairs){if(seen.has(key)){return failure(line,`overrides entry ${JSON.stringify(key)} is set twice`)}seen.add(key);const problem2=overrideProblem(key,value2);if(problem2){return failure(line,problem2)}}return{overrides:entries.pairs.map(({key,value:value2})=>[key,value2])}}function failure(line,problem2){return{problem:`line ${line}: ${problem2}`,line}}function broken(line,problem2){return{problem:problem2,line}}function blockEntries(lines,start){const pairs=[];let indent=null;for(let index=start+1;index<lines.length;index++){const line=lines[index];const at=index+1;if(line.trim()===""||line.trim().startsWith("#")){continue}const leading=/^[ \t]*/.exec(line)[0];if(leading===""){if(pairs.length===0&&line.startsWith("-")){return broken(at,"overrides must be a map of package names to versions")}break}if(leading.includes(" ")){return broken(at,"overrides is indented with a tab")}indent??=leading.length;if(leading.length!==indent){return broken(at,'overrides entries must be single-line "name: version" pairs')}const pair=entry(line.slice(indent));if(!pair){return broken(at,'overrides entries must be single-line "name: version" pairs')}pairs.push({line:at,...pair})}return{pairs}}function flowEntries(head,start){const at=start+1;if(!head.startsWith("{")||!head.endsWith("}")){return broken(at,"overrides must be a map of package names to versions")}const body=head.slice(1,-1).trim();if(body===""){return{pairs:[]}}const pairs=[];for(const part of body.split(",")){const pair=entry(part.trim());if(!pair){return broken(at,'overrides entries must be "name: version" pairs')}pairs.push({line:at,...pair})}return{pairs}}function entry(text){const key=scalar(text,true);if(!key){return null}const rest=text.slice(key.end).replace(/^[ \t]*/,"");if(!rest.startsWith(":")||rest.length>1&&!/^:[ \t]/.test(rest)){return null}const valueText=rest.slice(1).trim();const value2=scalar(valueText,false);if(!value2){return null}const tail=withoutComment(valueText.slice(value2.end));if(tail===null||tail.trim()!==""){return null}return{key:key.text,value:value2.text}}function scalar(text,isKey){if(text.startsWith("'")){const match=/^'((?:[^']|'')*)'/.exec(text);return match?{text:match[1].replaceAll("''","'"),end:match[0].length}:null}if(text.startsWith('"')){const match=/^"([^"\\]*)"/.exec(text);return match?{text:match[1],end:match[0].length}:null}if(isKey){const match=/^(.*?)[ \t]*:(?:[ \t]|$)/.exec(text);return match&&match[1]!==""?{text:match[1],end:match[1].length}:null}const plain=withoutComment(text);return plain===null||plain.trim()===""?null:{text:plain.trim(),end:text.length}}function withoutComment(text){let quote="";for(let index=0;index<text.length;index++){const char=text[index];if(quote!==""){if(char===quote){quote=""}continue}if(char==="'"||char==='"'){quote=char;continue}if(char==="#"&&(index===0||/[ \t]/.test(text[index-1]))){return text.slice(0,index)}}return quote===""?text:null}var WORKSPACE_FILE="pnpm-workspace.yaml";var OVERRIDES_RULE="allowlist/package-overrides";var WORKSPACE_OVERRIDES_RULE="allowlist/workspace-overrides";var MOVE=`Move each entry under overrides in ${WORKSPACE_FILE}, one per line:
|
|
2
|
+
|
|
3
|
+
overrides:
|
|
4
|
+
ws: ^8.23.1
|
|
5
|
+
|
|
6
|
+
Use a registry package name or parent>child as the key and a version or range as the value. Yarn paths such as **/ws, npm: aliases and $ references are refused there. Then remove the field from package.json and run pnpm install.`;function manifestOverrideProblems(text){const fields=topLevelFields(text);const problems=[];const raw=fields.get("overrides");if(raw!==void 0&&hasJSONValue(raw)){problems.push(moved("overrides","Studio builds refuse it and pnpm 11 ignores it"))}const pnpmText=fields.get("pnpm");const pnpm=pnpmText===void 0?null:JSON.parse(pnpmText);if(pnpm!==null&&(typeof pnpm!=="object"||Array.isArray(pnpm))){problems.push(problem("package.json sets pnpm to something other than an object, which Studio builds refuse.","Make pnpm in package.json an object, or remove it.",{rule:OVERRIDES_RULE,file:"package.json"}))}else if(pnpm!==null&&present(fieldOf(pnpm,"overrides"))){problems.push(moved("pnpm.overrides","pnpm 11 ignores it, so its versions never reach the build"))}const resolutions=fields.get("resolutions");if(resolutions!==void 0&&present(JSON.parse(resolutions))){problems.push(moved("resolutions","pnpm 11 ignores it, so its versions never reach the build"))}return problems}function moved(field,why){return problem(`package.json sets ${field}, but ${why}.`,MOVE,{rule:OVERRIDES_RULE,file:"package.json"})}function hasJSONValue(raw){const trimmed=raw.trim();return trimmed!==""&&trimmed!=="null"&&trimmed!=="{}"}function present(value2){if(value2===void 0||value2===null){return false}return!(typeof value2==="object"&&!Array.isArray(value2)&&Object.keys(value2).length===0)}function sameKey(key,field){if(key.length!==field.length){return false}for(let index=0;index<key.length;index++){const char=key[index];const want=field[index];if(char.toLowerCase()===want){continue}if(want==="s"&&char==="\u017F"){continue}return false}return true}function fieldOf(object,field){let found;for(const[key,value2]of Object.entries(object)){if(sameKey(key,field)){found=value2}}return found}var FIELDS=["overrides","pnpm","resolutions"];function topLevelFields(text){const fields=new Map;let at=skipSpace(text,0);if(text[at]!=="{"){return fields}at=skipSpace(text,at+1);while(at<text.length&&text[at]!=="}"){const keyEnd=stringEnd(text,at);const key=JSON.parse(text.slice(at,keyEnd));at=skipSpace(text,skipSpace(text,keyEnd)+1);const valueEnd=valueEndAt(text,at);const field=FIELDS.find(name=>sameKey(key,name));if(field){fields.set(field,text.slice(at,valueEnd))}at=skipSpace(text,valueEnd);if(text[at]===","){at=skipSpace(text,at+1)}}return fields}function skipSpace(text,at){while(at<text.length&&/[ \t\r\n]/.test(text[at])){at++}return at}function stringEnd(text,at){for(let index=at+1;index<text.length;index++){if(text[index]==="\\"){index++}else if(text[index]==='"'){return index+1}}return text.length}function valueEndAt(text,at){if(text[at]==='"'){return stringEnd(text,at)}if(text[at]==="{"||text[at]==="["){let depth=0;for(let index2=at;index2<text.length;index2++){const char=text[index2];if(char==='"'){index2=stringEnd(text,index2)-1}else if(char==="{"||char==="["){depth++}else if(char==="}"||char==="]"){depth--;if(depth===0){return index2+1}}}return text.length}let index=at;while(index<text.length&&!/[,}\s]/.test(text[index])){index++}return index}var ENTRIES=`Make overrides in ${WORKSPACE_FILE} a map of registry package names to versions or ranges, one "name: version" pair per line, such as "ws: ^8.23.1". Aliases, protocols, paths, tags and references aren't allowed.`;function fixFor(why){if(why==="it is a link"){return`Replace the ${WORKSPACE_FILE} link with a plain file at the site's root.`}if(why==="it is not a file"){return`Replace ${WORKSPACE_FILE} at the site's root with a plain file, or remove it.`}if(why.startsWith("it is larger than")){return`Keep ${WORKSPACE_FILE} under ${MAX_WORKSPACE>>10} KiB. Remove what the site doesn't need.`}if(why.endsWith(": overrides is set twice")){return`Keep one overrides key in ${WORKSPACE_FILE} and merge the entries of the other into it.`}if(/: overrides entry ".*" is set twice$/.test(why)){return`Keep one line for each package under overrides in ${WORKSPACE_FILE}.`}if(why.endsWith("overrides is indented with a tab")){return`Indent the overrides entries in ${WORKSPACE_FILE} with spaces.`}if(/^line \d+: /.test(why)){return ENTRIES}return`Make ${WORKSPACE_FILE} a readable file, or remove it.`}async function workspaceOverrideProblems(cwd){const file=path2.join(cwd,WORKSPACE_FILE);const refused=(why,line)=>problem(`Studio builds can't use ${WORKSPACE_FILE}: ${why}.`,fixFor(why),{rule:WORKSPACE_OVERRIDES_RULE,file:WORKSPACE_FILE,...line?{line}:{}});let info;try{info=await lstat(file)}catch(error){const code=error.code;if(code==="ENOENT"||code==="ENOTDIR"){return[]}return[refused(error instanceof Error?error.message:String(error))]}if(info.isSymbolicLink()){return[refused("it is a link")]}if(!info.isFile()){return[refused("it is not a file")]}if(info.size>MAX_WORKSPACE){return[refused(`it is larger than ${MAX_WORKSPACE>>10} KiB`)]}const read4=readOverrides(await readFile2(file,"utf8"));return read4.problem===void 0?[]:[refused(read4.problem,read4.line)]}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;let manifestText;try{manifestText=await readFile3(path3.join(cwd,"package.json"),"utf8");manifest=JSON.parse(manifestText)}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}problems.push(...manifestOverrideProblems(manifestText),...await workspaceOverrideProblems(cwd));const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry2=>matches(entry2,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path3.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path3.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry2=>entry2===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value2=loaded.value;return Array.isArray(value2?.packages?.allow)?value2.packages.allow.filter(entry2=>typeof entry2==="string"):[]}catch{return[]}}function matches(pattern,value2){return pattern.endsWith("/*")?value2.startsWith(pattern.slice(0,-1)):pattern===value2}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path3.dirname(directory)){const found=path3.join(directory,"node_modules",...name.split("/"));if(await json(path3.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path3.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile4}from"fs/promises";import path4 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();if(!timeout.aborted&¬Installed(error)){return withProblems(unavailable(mode,`Could not audit dependencies because ${invocation.executable} isn't installed.`,missingManagerFix(invocation.executable),relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path4.resolve(cwd);for(;;){if(directory!==path4.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path4.resolve(cwd))){return null}for(const name of names){const candidate=path4.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path4.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile4(path4.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path4.relative(directory,cwd).replaceAll(path4.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path4.relative(cwd,lockfile2).replaceAll(path4.sep,"/")}function notInstalled(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"&&"syscall"in error&&typeof error.syscall==="string"&&error.syscall.startsWith("spawn")}function missingManagerFix(executable){return executable==="pnpm"?"Run corepack enable, or install pnpm, then run zappie check again.":"Install Node.js with npm, then run zappie check again."}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value2=JSON.parse(source);requireAuditReport(manager,value2);const parsed=manager==="npm"?npmAdvisories(value2):pnpmAdvisories(value2);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value2){if(record(value2.error)){throw new Error(string(value2.error.message)??string(value2.error.code)??string(value2.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value2.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value2.advisories)&&!record(value2.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value2){if(!record(value2.advisories)){return[]}return Object.entries(value2.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value2){if(!record(value2.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName2,raw]of Object.entries(value2.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName2);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName2,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName2?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value2,problems=[]){if(value2===void 0){return[]}if(!Array.isArray(value2)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value2.forEach((entry2,index)=>{if(!ignoreEntry(entry2)||!entry2.id.trim()||!entry2.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry2.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry2.id}.`));return}const expiry=Date.parse(`${entry2.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry2.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry2.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry2)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value2){return record(value2)&&typeof value2.id==="string"&&typeof value2.reason==="string"&&typeof value2.until==="string"}function npmUpgrade(value2){if(record(value2)&&typeof value2.name==="string"&&typeof value2.version==="string"){return{upgradePackage:value2.name,upgradeVersion:value2.version}}if(value2===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value2){if(!value2||value2==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value2)?.[1]??null}function ghsaFrom(value2){const id=value2?/GHSA-[\w-]+/i.exec(value2)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value2){return value2.trim().toLowerCase()}function malicious(value2){return/^MAL-/i.test(value2.trim())}function normalizedSeverity(value2){const severity=typeof value2==="string"?value2.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value2){return typeof value2==="string"?value2:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}import{access as access3,readFile as readFile7}from"fs/promises";import path7 from"path";import{readFile as readFile5,readdir as readdir2}from"fs/promises";import path5 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path5.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path5.relative(root,file).split(path5.sep).join("/"),bytes:gzipSync(await readFile5(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry2 of await readdir2(directory,{withFileTypes:true})){if(entry2.isSymbolicLink()){continue}const file=path5.join(directory,entry2.name);if(entry2.isDirectory()){await collect(file,files)}else if(entry2.isFile()){files.push(file)}}}import{readFile as readFile6}from"fs/promises";import path6 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry2])=>routeSource(entry2.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry2])=>entry2.isEntry&&!routeSource(entry2.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry2=>Boolean(entry2)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile6(path6.join(cwd,"build/client",file),"utf8")).byteLength})))}async function graphCssSizes(cwd,manifest,roots){const files=new Set([...closure(manifest,roots)].flatMap(key=>manifest[key]?.css??[]));return Promise.all([...files].sort().map(async file=>({file,bytes:gzipSync2(await readFile6(path6.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry2=manifest[key];if(!entry2){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry2.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeId(manifest,key){return(manifest[key]?.src??key).replace(/\?.*$/,"").replace(/^\/?app\//,"").replace(/\.[^./]+$/,"")}function routeSource(value2){return value2.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;var kb=bytes=>`${(bytes/KIB).toFixed(1)} KB`;var PUBLISH_GOES_AHEAD="Publish goes ahead: on a site with its own code, size is a guide.";async function checkBudgets({cwd,signal,site}){signal?.throwIfAborted();const manifestFile=path7.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile7(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const guide=advises(site);const problems=[];let failed=false;const over=found=>{if(guide){problems.push(warning(found));return}failed=true;problems.push(found)};for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const jsOver=total(sizes)>limits.jsKbGz*KIB;const found=routeProblem(route,sizes,limits.jsKbGz,jsOver,guide);if(jsOver){over(found)}else{problems.push(found)}}const routeCss=config.budgets?.routeCssKbGz;const perRoute=typeof routeCss==="object"?routeCss:void 0;const measured=[];for(const route of routes){const id=routeId(manifest,route);const sizes=await graphCssSizes(cwd,manifest,[...clients,route]);const limitKb=typeof routeCss==="object"?routeCss[id]:routeCss;const missing3=perRoute!==void 0&&limitKb===void 0;const cssOver2=limitKb!==void 0&&total(sizes)>limitKb*KIB;measured.push([id,total(sizes)]);const found=routeCssProblem(id,sizes,limitKb,cssOver2,missing3,guide);if(cssOver2||missing3){over(found)}else{problems.push(found)}}const ids=new Set(measured.map(([id])=>id));for(const key of Object.keys(perRoute??{}).filter(key2=>!ids.has(key2))){over(problem(`budgets.routeCssKbGz names ${key}, which is not a route in this build. Its routes are ${[...ids].join(", ")}.`,"Rename the key to the route id it means, or remove it. A route id is the route file's path under app/ without its extension.",{rule:"budgets/css-route-unknown",file:"zappie.config.ts"}))}if(typeof routeCss!=="number"){problems.push(routeCssRecord(measured))}const styles=await cssSizes(cwd);const cssOver=routeCss===void 0&&total(styles)>limits.cssKbGz*KIB;const css=cssProblem(styles,routeCss===void 0?limits.cssKbGz:void 0,cssOver,guide);if(cssOver){over(css)}else{problems.push(css)}problems.push(problem(guide?`LCP is not measured by zappie check. zappie verify measures it against the ${limits.lcpMs} ms guide.`:`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over,guide){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");if(over&&guide){return problem(`${route}: JavaScript is ${kb(bytes)} gzip, above the ${kb(limitKb*KIB)} guide. Largest chunks: ${largest}.`,`${PUBLISH_GOES_AHEAD} Less client JavaScript on the route makes the page faster.`,{rule:"budgets/js-over",file:"build/client/.vite/manifest.json"})}return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function routeCssProblem(id,sizes,limitKb,over,missing3,guide){const bytes=total(sizes);if(over&&guide){return problem(`${id}: CSS on first load is ${kb(bytes)} gzip, above the ${kb((limitKb??0)*KIB)} guide.`,`${PUBLISH_GOES_AHEAD} Moving styles only one route or overlay draws into a stylesheet it imports makes the page faster.`,{rule:"budgets/css-route-over",file:"build/client/.vite/manifest.json"})}const limit=missing3?"budgets.routeCssKbGz has no entry for it":limitKb===void 0?"no limit set: budgets.routeCssKbGz sets one":`limit ${limitKb*KIB} B`;return problem(`${id}: ${bytes} B gzip of CSS on first load (${limit}).${over?` Stylesheets: ${sizes.map(({file,bytes:size})=>`${file} (${size} B)`).join(", ")}.`:""}`,missing3?`Add ${JSON.stringify(id)}: ${suggestedKb(bytes)} to budgets.routeCssKbGz, the measured figure with 10 percent headroom.`:over?"Move styles only one route or overlay draws out of the root stylesheet and into a stylesheet that route or overlay imports.":null,{rule:missing3?"budgets/css-route-missing":over?"budgets/css-route-over":"budgets/css-route",file:"build/client/.vite/manifest.json"})}function routeCssRecord(measured){const entries=measured.map(([id,bytes])=>` ${JSON.stringify(id)}: ${suggestedKb(bytes)},`).join("\n");return problem("Each route's first-load CSS with 10 percent headroom, as a budgets.routeCssKbGz record.",`Paste it into budgets in zappie.config.ts, so the build fails a route whose CSS grows past it:
|
|
2
7
|
routeCssKbGz: {
|
|
3
8
|
${entries}
|
|
4
|
-
},`,{rule:"budgets/css-route-record",file:"zappie.config.ts"})}var suggestedKb=bytes=>Math.ceil(bytes*1.1/KIB*2)/2;function cssProblem(sizes,limitKb,over){const bytes=total(sizes);const limit=limitKb===void 0?"not enforced: budgets.routeCssKbGz limits each route instead":`limit ${limitKb*KIB} B`;return problem(`Client CSS: ${bytes} B gzip (${limit}).`,over?"Reduce client CSS or raise the reviewed budget override.":null,{rule:over?"budgets/css-over":"budgets/css"})}var total=sizes=>sizes.reduce((sum,asset)=>sum+asset.bytes,0);import{readdir as readdir5,readFile as readFile8}from"fs/promises";import path9 from"path";import{readdir as readdir4,readFile as readFile7}from"fs/promises";import path8 from"path";var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);import{readFile as readFile6,readdir as readdir3}from"fs/promises";import path7 from"path";var BUILD_OUTPUT=["build/client","build/server"];var QUOTE="[\"'`]";var URL_TEXT="((?:[a-z][a-z\\d+.-]*:|//|\\\\\\\\)[^\"'`\\s]*)";var JS_NAVIGATION=[new RegExp(`\\blocation(?:\\.href)?\\s*=\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\blocation\\.(?:assign|replace)\\(\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\bopen\\(\\s*${QUOTE}${URL_TEXT}`,"gi")];var REFRESH_URL=`\\d*\\s*;?\\s*url\\s*=\\s*['"]?([^"'\`\\s$;]+)`;var JS_REFRESH=[new RegExp(`http-?equiv["']?\\s*[:,=]\\s*["']refresh["']\\s*,\\s*["']?content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi"),new RegExp(`content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}['"]?${QUOTE}\\s*,\\s*["']?http-?equiv["']?\\s*[:,=]\\s*["']refresh`,"gi"),new RegExp(`["']refresh["']\\s*[:,]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi")];var HTML_META=/<meta\b[^>]*>/gi;var ABSOLUTE="((?:https?:)?//[^\"'`\\s<>$]+)";var HTML_LINK=new RegExp(`\\s(?:href|action|formaction|src|poster|data)\\s*=\\s*["']?\\s*${ABSOLUTE}`,"gi");var JS_LINK=[new RegExp(`[{,]\\s*["']?(?:href|to|action|formAction|src|poster)["']?\\s*:\\s*${QUOTE}\\s*${ABSOLUTE}`,"g"),new RegExp(`setAttribute\\(\\s*["'](?:href|action|formaction|src)["']\\s*,\\s*${QUOTE}\\s*${ABSOLUTE}`,"gi"),new RegExp(`\\.(?:href|action|src)\\s*=\\s*${QUOTE}\\s*${ABSOLUTE}`,"g")];var HTML_SCRIPT=/<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;var APP_SCHEMES=/^(?:tel|mailto|sms):/;function untrusted(value2,trusted){const url=value2.trim().replaceAll("\\","/").toLowerCase();if(!/^(?:[a-z][a-z\d+.-]*:|\/\/)/.test(url)||APP_SCHEMES.test(url)){return false}return!trusted.some(origin=>url===origin||url.startsWith(`${origin}/`))}function lineAt(source,index){return source.slice(0,index).split("\n").length}var PACKAGE_HOSTS=["maps.googleapis.com"];var CSP_HOSTS=["fonts.googleapis.com","fonts.gstatic.com"];async function knownHosts(cwd){let config;try{config=(await loadConfig(cwd)).value}catch{config=void 0}const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links].flatMap(list3=>Array.isArray(list3)?list3:[]).filter(host=>typeof host==="string");return[...new Set(["*.zappie.ai","zappie.ai","zappie.shop","images.zappie.shop",...typeof config?.store==="string"?[`${config.store}.zappie.shop`]:[],...RESIZE_HOSTS,...PACKAGE_HOSTS,...CSP_HOSTS,...configured])].filter(Boolean).map(host=>host.toLowerCase())}function listedHost(url,hosts){let host;try{host=new URL(url.startsWith("//")?`https:${url}`:url).hostname.toLowerCase()}catch{return false}return hosts.some(entry=>entry.startsWith("*.")?host.endsWith(entry.slice(1)):host===entry)}function linkFindings(source,patterns,hosts){const found=[];for(const pattern of patterns){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(!listedHost(url,hosts)){found.push({rule:"build/unlisted-link-host",index:match.index,url})}}}return found}function scanScript(source,hosts,trusted){const found=linkFindings(source,JS_LINK,hosts);for(const pattern of JS_NAVIGATION){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-offsite-navigation",index:match.index,url})}}}for(const pattern of JS_REFRESH){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}}return found}function scanHtml(source,hosts,trusted){const found=linkFindings(source,[HTML_LINK],hosts);for(const match of source.matchAll(HTML_META)){const tag=match[0];if(!/\bhttp-equiv\s*=\s*["']?\s*refresh/i.test(tag)){continue}const url=new RegExp(REFRESH_URL,"i").exec(tag)?.[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}for(const match of source.matchAll(HTML_SCRIPT)){const src=match[1]??match[2]??match[3]??"";if(/^\s*(?:[a-z][a-z\d+.-]*:|\/\/|\\\\)/i.test(src)){found.push({rule:"build/no-external-script",index:match.index,url:src})}}return found}var MESSAGES={"build/no-offsite-navigation":{message:url=>`The build output sends the shopper to ${url} from code. Only Zappie's checkout and accounts may be opened this way.`,fix:"Find the code or package that navigates there and remove it, or link to the page with an <a href> the shopper clicks."},"build/no-meta-refresh":{message:url=>`The build output has a refresh that moves the shopper to ${url} without a click.`,fix:"Remove the refresh tag or header, or the package that adds it. Use a router redirect to a path on this site."},"build/unlisted-link-host":{message:url=>`The build output links to or loads ${url}, on a host the site doesn't list.`,fix:"If the store means to link there, add the host to security.links in zappie.config.ts (or security.csp for an image or font host). Otherwise find the code or content that names it and remove it."},"build/no-external-script":{message:url=>`The built page loads a script from ${url}.`,fix:"Install the code as a package so it ships in the storefront bundle, and remove the script tag."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path7.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const html=/\.html?$/i.test(entry);if(!html&&!/\.[cm]?js$/i.test(entry)){continue}const file=path7.join(cwd,directory,entry);const source=await readFile6(file,"utf8").catch(()=>"");const findings=html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted);const named=new Set(findings.filter(finding=>finding.rule!=="build/unlisted-link-host").map(finding=>finding.url));const reported=new Set;for(const finding of findings.sort((a,b)=>a.index-b.index)){const link=finding.rule==="build/unlisted-link-host";const key=`${finding.rule}\0${link?finding.url:finding.index}`;if(reported.has(key)||link&&named.has(finding.url)){continue}reported.add(key);const text=MESSAGES[finding.rule];if(!text){continue}problems.push(problem(text.message(finding.url),text.fix,{rule:finding.rule,file:relative(cwd,file),line:lineAt(source,finding.index)}))}}}return problems}var ATTRIBUTES=["data-zappie-source","data-zappie-component"];async function devSourceProblems(cwd){const problems=[];for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir4(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const file=path8.join(cwd,directory,entry);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry)){continue}const source=await readFile7(file,"utf8").catch(()=>"");const found=ATTRIBUTES.find(attribute=>source.includes(attribute));if(found){problems.push(problem(`The build output has the dev-only ${found} attribute, which shows where the site's code lives.`,"Add zappieSource() to the Vite plugins only for the dev server, as the starter does, and remove any copy of the attribute from your code.",{rule:"build/no-dev-source-attributes",file:relative(cwd,file)}))}}}return problems}var PREBUILT_ENV="ZAPPIE_CHECK_PREBUILT";var PREBUILT_RULE="build/prebuilt";async function checkBuild({cwd,packageManager,signal,prebuilt}){signal?.throwIfAborted();const manifest=JSON.parse(await readFile8(path9.join(cwd,"package.json"),"utf8"));const invocation=manifest.dependencies?.["react-router"]?await binaryArgs(packageManager,cwd,"react-router",["build"]):manifest.scripts?.build?scriptArgs(packageManager,"build"):void 0;if(!invocation){return skipped("build","No react-router dependency or build script is defined in package.json.")}if((prebuilt??process.env[PREBUILT_ENV]==="1")&&await hasBuildOutput(cwd)){const problems=await scanProblems(cwd);signal?.throwIfAborted();return step("build",problems.length?"failed":"passed",[...problems,problem("Used the existing build output instead of building again.",null,{rule:PREBUILT_RULE})])}const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){const problems=await scanProblems(cwd);return step("build",problems.length?"failed":"passed",problems)}return step("build","failed",[problem(`The project build failed.
|
|
5
|
-
${usefulTail(result.stdout,result.stderr)}`,"Fix the reported build errors and run zappie check again.",{rule:"build/failed"})])}async function scanProblems(cwd){return[...await devSourceProblems(cwd),...await outputProblems(cwd)]}async function hasBuildOutput(cwd){for(const directory of BUILD_OUTPUT){const entries=await readdir5(
|
|
6
|
-
${stderr}`.split(/\r?\n/).map(line=>line.trimEnd()).filter(Boolean).slice(-12);return lines.length>0?lines.join("\n"):"The build exited without output."}import postcss3 from"postcss";import postcss from"postcss";var DEFAULT_CORNER_FILES=["app/**/checkout/**","app/**/{account,orders,order,sign-in,cart-notice,bag-drawer,closed,not-found}{,-*}.{tsx,jsx,ts,js,mdx,css}"];var ALLOW=/zappie-allow-radius:\s*\S/;var SIDE="(?:-(?:[trblse]|tl|tr|br|bl|ss|se|es|ee))?";var ROUNDED=new RegExp(`^-?rounded${SIDE}(?:-(.+))?$`);var ZERO=/^(?:none|0|\[0(?:px|rem|em|%)?\])$/;var FIX="Use one of the site's radius tokens, such as rounded-[var(--z-radius-md)], a rounded-<name> your @theme defines or var(--radius-<name>) in CSS, so this screen follows the brand. A true circle on an icon-only control can stay with zappie-allow-radius: <reason> on its line or the line above.";function globPattern(glob){let source="";let depth=0;for(let index=0;index<glob.length;index++){const character=glob[index];if(glob.startsWith("**/",index)){source+="(?:.*/)?";index+=2}else if(glob.startsWith("**",index)){source+=".*";index++}else if(character==="*"){source+="[^/]*"}else if(character==="?"){source+="[^/]"}else if(character==="{"){depth++;source+="(?:"}else if(character==="}"&&depth){depth--;source+=")"}else if(character===","&&depth){source+="|"}else{source+=character.replace(/[.+^$()|[\]\\]/g,"\\$&")}}return new RegExp(`^${source}$`)}function literalRadii(inputs,corners={}){const patterns=(corners.files??DEFAULT_CORNER_FILES).map(globPattern);const shared=({file})=>patterns.some(pattern=>pattern.test(file));const tokens=new Set([...inputs.sourceCss.map(({text})=>text).join("\n").matchAll(/--radius-([\w-]+)\s*:/g)].map(match=>match[1]));const problems=[];const report=(file,line,what)=>problems.push(problem(`${what} sets a corner radius the site's theme doesn't control.`,FIX,{rule:"css/literal-radius",file,line}));const literal2=(tokensInList,token)=>{const match=ROUNDED.exec(withoutVariants(token).utility);if(!match){return false}const size=match[1];if(size===void 0){return true}if(ZERO.test(size)||/--|var\(/.test(size)||tokens.has(size)){return false}return!(/^(?:full|\[50%\])$/.test(size)&&square(tokensInList))};for(const entry of inputs.sourceCode.filter(shared)){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(ALLOW.test(text)||ALLOW.test(lines[index-1]??"")){return}for(const list3 of classLists(text.replace(/\$\{[^{}]*\}/g," "))){const tokensInList=list3.split(/\s+/);for(const token of tokensInList){if(literal2(tokensInList,token)){report(entry.file,index+1,token)}}}for(const match of text.matchAll(/borderRadius\s*:\s*(["'`]?)([^"'`,}]+)\1/g)){const value2=match[2].trim();if((match[1]||/^[\d.]+$/.test(value2))&&literalValue(value2)){report(entry.file,index+1,`borderRadius: ${value2}`)}}})}for(const entry of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry.text)}catch{continue}const lines=entry.text.split(/\r?\n/);const allowed=(line=0)=>ALLOW.test(lines[line-1]??"")||ALLOW.test(lines[line-2]??"");root.walkDecls(/^border(?:-[a-z]+)*-radius$/i,decl=>{const line=decl.source?.start?.line??0;if(literalValue(decl.value)&&!allowed(line)){report(entry.file,line,`${decl.prop}: ${decl.value}`)}});root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line??0;const list3=rule.params.split(/\s+/);for(const token of list3){if(literal2(list3,token)&&!allowed(line)){report(entry.file,line,`@apply ${token}`)}}})}return problems}function literalValue(value2){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value2)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value2)}function square(list3){const utilities=list3.map(token=>withoutVariants(token).utility);return utilities.some(utility=>/^size-/.test(utility)||utility==="aspect-square"||/^h-/.test(utility)&&utilities.includes(`w-${utility.slice(2)}`))}import path10 from"path";import postcss2 from"postcss";var ROOT_ROUTE_CSS="css/root-route-css";var ROOT_MODULES=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES=["",".tsx",".ts",".jsx",".js",".mjs","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var CSS_IMPORT=/^\s*(?:url\()?["']?([^"')\s]+)["']?\)?/;var CLASS=/\.(-?[_a-zA-Z][\w-]*)/g;var TOKEN=/[_a-zA-Z][\w-]*/g;var SHOWN=4;function rootRouteCss(inputs){const code=new Map(inputs.sourceCode.map(entry=>[entry.file,entry]));const css=new Map(inputs.sourceCss.map(entry=>[entry.file,entry]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known=file=>code.has(file)||css.has(file);const graph=new Set;const sheets=new Set;const pending=[root];while(pending.length){const file=pending.pop();if(graph.has(file)){continue}graph.add(file);for(const[,specifier]of code.get(file).text.matchAll(STATIC_IMPORT)){const target=resolve(file,specifier,known);if(target&&css.has(target)){sheets.add(target)}else if(target&&code.has(target)){pending.push(target)}}}for(const sheet of[...sheets]){cssImports(css.get(sheet),known).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry=>{let found=tokens.get(entry.file);if(!found){found=new Set(entry.text.match(TOKEN)??[]);tokens.set(entry.file,found)}return found};const problems=[];for(const sheet of[...sheets].sort()){const groups=new Map;for(const[name,line]of classesOf(css.get(sheet))){const users=inputs.sourceCode.filter(entry=>tokensOf(entry).has(name)).map(entry=>entry.file);if(users.length===0||users.some(file=>graph.has(file))){continue}const key=users.sort().join("\n");const group=groups.get(key)??{classes:[]};group.classes.push(name);group.line??=line;groups.set(key,group)}for(const[key,{classes,line}]of groups){const users=key.split("\n");problems.push(problem(`${sheet} loads on every page through ${root}, but ${list2(classes.map(name=>`.${name}`))} ${classes.length===1?"is":"are"} drawn only by ${list2(users)}.`,`Move ${classes.length===1?"it":"them"} into a stylesheet that ${users.length===1?"module":"one of those modules"} imports, so ${classes.length===1?"it loads":"they load"} with that route or overlay and not on every page.`,{rule:ROOT_ROUTE_CSS,file:sheet,...line?{line}:{}}))}}return problems}function resolve(from,specifier,known){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path10.posix.join(path10.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known)}function cssImports(entry,known){const found=[];try{postcss2.parse(entry.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry.file,specifier,known);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry){const classes=new Map;try{postcss2.parse(entry.text).walkRules(rule=>{const parent=rule.parent;if(parent?.type==="atrule"&&/keyframes$/i.test(parent.name)){return}for(const[,name]of rule.selector.matchAll(CLASS)){if(!classes.has(name)){classes.set(name,rule.source?.start?.line)}}})}catch{}return classes}function list2(names){const shown=names.slice(0,SHOWN);const rest=names.length-shown.length;if(rest>0){return`${shown.join(", ")} and ${rest} more`}return shown.length>1?`${shown.slice(0,-1).join(", ")} and ${shown.at(-1)}`:shown[0]}var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs,corners){const source=parseAll(inputs.sourceCss);const built=parseAll(inputs.builtCss);return[...source.problems,...built.problems,...important(source.parsed,inputs.sourceCode),...duplicateKeyframes(source.parsed,built.parsed),...duplicateSelectors(source.parsed),...arbitraryTokens(source.parsed,inputs.sourceCode),...unusedCustomProperties(source.parsed,built.parsed,inputs),...reducedMotion(source.parsed),...classPatches(source.parsed),...literalTokens(source.parsed),...rootRouteCss(inputs),...literalRadii(inputs,corners)]}function parseAll(files){const parsed=[];const problems=[];for(const entry of files){try{parsed.push({...entry,root:postcss3.parse(entry.text,{from:entry.file}),lines:entry.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry of css){entry.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry.file,line))}});entry.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry.file,line))}})}for(const entry of code){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list3 of classLists(text)){for(const token of list3.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value2=match[2]?.trim()??"";if(!value2){continue}const tokens=value2.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value2)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry of files){entry.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value2=>value2.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value2){return value2.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first2,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first2?.file}${first2?.line?`:${first2.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first2=group[0];problems.push(problem(`@keyframes ${first2?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first2)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first2,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first2?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry){return{rule,...entry?{file:entry.file}:{},...entry?.line?{line:entry.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry of source){entry.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first2=seen.get(key);if(!first2){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first2.file}${first2.line?`:${first2.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry of source){entry.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value2=>value2.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value2=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value2===candidate.value||value2===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry of code){scan(entry.text,entry.file)}for(const entry of source){entry.root.walkAtRules("apply",rule=>{scan(rule.params,entry.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read3=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read3.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry.text.matchAll(scriptMentions)){read3.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read3.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry of source){entry.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry of source){entry.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{const value2=compact(decl.value);if(value2.includes("var(")||trivialValue.test(value2)||tokens.has(value2)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value2,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal,site}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const corners=await cornerSettings(cwd);const problems=analyseCss(inputs,corners);signal?.throwIfAborted();const checked=owned(site,problems.map(found=>({problem:found,blocks:CSS_ERRORS.has(found.rule)||found.rule==="css/literal-radius"&&corners.fail===true})));return step("css",checked.failed?"failed":"passed",checked.problems)}async function cornerSettings(cwd){try{const value2=(await loadConfig(cwd)).value;const{files,fail}=value2?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile13}from"fs/promises";import path15 from"path";import{pathToFileURL}from"url";import{readFile as readFile9}from"fs/promises";import path11 from"path";var CLOSED_PAGE_RULE="readiness/closed-page";var WORKERS=["workers/app.ts","workers/app.js"];var ROOTS=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES2=["",".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT2=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var MARKS=/\b(?:siteWorker|markClosedPage)\s*[<(]/;var COMMENTS=/\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g;async function read(cwd,file){try{return(await readFile9(path11.join(cwd,file),"utf8")).replace(COMMENTS,"$1")}catch{return void 0}}async function first(cwd,files){for(const file of files){const text=await read(cwd,file);if(text!==void 0){return{file,text}}}return void 0}function local(from,specifier){if(specifier.startsWith("~/")){return path11.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path11.posix.join(path11.posix.dirname(from),specifier)}return void 0}var HOST_ADAPTERS=["siteHost","zappieHost"];function namesOf(text,exported){const names=[...exported];const pattern=new RegExp(`\\b(?:${exported.join("|")})\\s+as\\s+(\\w+)`,"g");for(const[,alias]of text.matchAll(pattern)){names.push(alias)}return names}function adapterCall(text){return`\\b(?:${namesOf(text,HOST_ADAPTERS).join("|")})\\s*\\([^()]*\\)`}function adapterNames(text){const bound=new RegExp(`\\b(?:const|let|var)\\s+(\\w+)\\s*(?::[^=;]+)?=\\s*${adapterCall(text)}`,"g");return[...text.matchAll(bound)].map(([,name])=>name)}function readsClosed(text,adapters){const closed=[adapterCall(text),...adapters.map(name=>`(?<![\\w$.])${name}`)];return namesOf(text,["siteClosed"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(text))||new RegExp(`(?:${closed.join("|")})\\s*\\.\\s*closed\\s*\\(`).test(text)}async function rootModules(cwd){const root=await first(cwd,ROOTS);const texts=[];const seen=new Set;const pending=root?[root.file]:[];while(pending.length){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);const text=file===root?.file?root.text:await read(cwd,file);if(text===void 0){continue}texts.push(text);for(const[,specifier]of text.matchAll(STATIC_IMPORT2)){const target=local(file,specifier);if(!target){continue}for(const suffix of SUFFIXES2){if(await read(cwd,target+suffix)!==void 0){pending.push(target+suffix);break}}}}return{file:root?.file,texts}}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const{file:rootFile,texts}=await rootModules(cwd);const adapters=texts.flatMap(adapterNames);if(texts.some(text=>readsClosed(text,adapters))){return[]}const file=rootFile??"app/root.tsx";return[problem(`${worker.file} marks a closed page, but ${file} never reads siteClosed(request) to draw one`,`In ${file}'s loader, call siteHost(context).closed(request) from @zappie/foundations/site/server, or siteClosed(request) from @zappie/sdk/site-closed, and return your closed page's data when it answers, as the starter's root does. Until then a switched-off store shows Zappie's closed page, or your full shop where the Worker calls markClosedPage itself.`,{rule:CLOSED_PAGE_RULE,file})]}import{readFile as readFile12,readdir as readdir8}from"fs/promises";import path14 from"path";import{readFile as readFile11,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path13 from"path";import{readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 from"path";function parseModule(ts,file,text,deep){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,false,scriptKind(ts,file));const parsed={imports:[],reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set};const locals=new Map;const line=node=>source.getLineAndCharacterOfPosition(node.getStart(source)).line+1;const exported=(name,node,local2=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local2)}};for(const statement of source.statements){if(ts.isImportDeclaration(statement)){readImport(ts,statement,parsed)}else if(ts.isExportDeclaration(statement)){readExport(ts,statement,parsed,exported)}else if(ts.isExportAssignment(statement)){exported("default",statement,"")}else if(hasExport(ts,statement)){for(const[name,local2]of declaredNames(ts,statement)){exported(name,statement,local2)}}}const references=new Set;const visit=(node,parent)=>{if(ts.isIdentifier(node)){if(parent&&!namesOnly(ts,parent,node)){references.add(node.text)}return}if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword){const specifier=literal(ts,node.arguments[0]);if(specifier!==void 0){parsed.imports.push({specifier,names:"all"})}}else if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal)){const qualifier=node.qualifier;parsed.imports.push({specifier:node.argument.literal.text,names:qualifier&&ts.isIdentifier(qualifier)?new Set([qualifier.text]):"all"})}else if(deep&&ts.isCallExpression(node)){const callee=node.expression;if(ts.isIdentifier(callee)){parsed.calls.push({callee:callee.text,args:node.arguments.map(argument=>literal(ts,argument))})}}if(deep&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))){parsed.strings.push(node.text)}ts.forEachChild(node,child=>visit(child,node))};visit(source);for(const[name,local2]of locals){if(local2&&references.has(local2)){parsed.usedHere.add(name)}}return parsed}function scriptKind(ts,file){if(/\.[jt]sx$/.test(file)){return ts.ScriptKind.TSX}return/\.[cm]?js$/.test(file)?ts.ScriptKind.JS:ts.ScriptKind.TS}function literal(ts,node){return node&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))?node.text:void 0}function readImport(ts,statement,parsed){const specifier=literal(ts,statement.moduleSpecifier);if(specifier===void 0){return}const clause=statement.importClause;const names=new Set;let taken=names;if(clause?.name){names.add("default");parsed.bindings.set(clause.name.text,{specifier,name:"default"})}const bindings=clause?.namedBindings;if(bindings&&ts.isNamespaceImport(bindings)){taken="all"}else if(bindings){for(const element of bindings.elements){const name=(element.propertyName??element.name).text;names.add(name);parsed.bindings.set(element.name.text,{specifier,name})}}parsed.imports.push({specifier,names:taken})}function readExport(ts,statement,parsed,exported){const specifier=literal(ts,statement.moduleSpecifier);const clause=statement.exportClause;if(specifier===void 0){if(clause&&ts.isNamedExports(clause)){for(const element of clause.elements){exported(element.name.text,element,(element.propertyName??element.name).text)}}return}if(!clause){parsed.reexports.push({specifier,names:"star"})}else if(ts.isNamespaceExport(clause)){exported(clause.name.text,clause,"");parsed.imports.push({specifier,names:"all"})}else{const names=new Map;for(const element of clause.elements){names.set(element.name.text,(element.propertyName??element.name).text);exported(element.name.text,element,"")}parsed.reexports.push({specifier,names})}}function hasExport(ts,statement){return ts.canHaveModifiers(statement)&&(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)}function namesOnly(ts,parent,node){if(ts.isImportSpecifier(parent)||ts.isExportSpecifier(parent)||ts.isImportClause(parent)||ts.isNamespaceImport(parent)){return true}if(ts.isPropertyAccessExpression(parent)||ts.isQualifiedName(parent)){return(ts.isPropertyAccessExpression(parent)?parent.name:parent.right)===node}return(ts.isFunctionDeclaration(parent)||ts.isClassDeclaration(parent)||ts.isInterfaceDeclaration(parent)||ts.isTypeAliasDeclaration(parent)||ts.isEnumDeclaration(parent)||ts.isModuleDeclaration(parent)||ts.isVariableDeclaration(parent)||ts.isPropertyAssignment(parent)||ts.isPropertySignature(parent)||ts.isPropertyDeclaration(parent)||ts.isMethodDeclaration(parent)||ts.isMethodSignature(parent)||ts.isJsxAttribute(parent))&&parent.name===node}function declaredNames(ts,statement){const name=statement.name;const local2=name&&(ts.isIdentifier(name)||ts.isStringLiteral(name))?name.text:"";const isDefault=(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword);if(isDefault){return[["default",local2]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry=>[entry,entry])}return local2?[[local2,local2]]:[]}function bindingNames(ts,name){if(ts.isIdentifier(name)){return[name.text]}return name.elements.flatMap(element=>ts.isOmittedExpression(element)?[]:bindingNames(ts,element.name))}var skippedDirectories=new Set(["node_modules","build","dist","public","vendor","coverage","test-results","playwright-report"]);var codeFile=/\.(?:[cm]?[jt]sx?)$/;var sourceFile=/\.(?:[cm]?[jt]sx?|css)$/;var probeExtensions=[".ts",".tsx",".js",".jsx",".mts",".mjs",".cts",".cjs"];var testDirectories=new Set(["test","tests","__tests__","__mocks__","e2e"]);var testName=/(?:\.(?:test|spec|bench)\.[cm]?[jt]sx?$)|(?:^(?:vitest|playwright)\.[^/]*$)/;var configFile=/^(?:vite|react-router)\.config\.[cm]?[jt]s$/;var routeExports=new Set(["default","loader","clientLoader","action","clientAction","meta","links","headers","handle","ErrorBoundary","HydrateFallback","Layout","shouldRevalidate","middleware","clientMiddleware","unstable_middleware","unstable_clientMiddleware"]);async function findUnused(project,ts,appDirectory2="app"){const cwd=path12.resolve(project);const app=path12.join(cwd,appDirectory2);const files=await listFiles(cwd);const known=new Set(files);const modules=new Map;const routesFile=probe(path12.join(app,"routes"),known);const configs=files.filter(file=>path12.dirname(file)===cwd&&configFile.test(path12.basename(file)));for(const file of files){const deep=file===routesFile||configs.includes(file);const module={file,test:isTest(cwd,file)};if(codeFile.test(file)){module.parsed=parseModule(ts,file,await readFile10(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile10(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path12.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path12.join(app,"root"),known);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry=probe(path12.join(app,name),known);if(entry){quiet.add(entry)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value2=>{const target=resolver.fromRoot(value2);return target?[target]:[]}));for(const file of named){quiet.add(file)}const productionRoots=[...routeModules,...quiet,...named,...files.filter(file=>!inApp(file)&&!modules.get(file)?.test)];const testRoots=files.filter(file=>modules.get(file)?.test);const edges=file=>[...modules.get(file)?.parsed?.imports??[],...modules.get(file)?.parsed?.reexports??[]].flatMap(({specifier})=>{const target=resolver.resolve(file,specifier);return target?[target]:[]});const production=reach(productionRoots,edges);const tested=reach(testRoots,edges);const used=usage([...production].filter(file=>!modules.get(file)?.test),modules,resolver.resolve);const testUsed=usage(testRoots,modules,resolver.resolve);const findings=[];for(const module of modules.values()){if(!candidate(module)){continue}const file=relative(cwd,module.file);if(!production.has(module.file)){findings.push({rule:tested.has(module.file)?"unused/test-only":"unused/file",file});continue}if(quiet.has(module.file)||kit.has(module.file)){continue}const isRoute=routeModules.has(module.file);for(const[name,line]of module.parsed?.exports??[]){if(isRoute&&routeExports.has(name)){continue}if(used.get(module.file)?.has(name)){continue}findings.push({rule:testUsed.get(module.file)?.has(name)?"unused/test-only":"unused/export",file,name,line,usedHere:module.parsed?.usedHere.has(name)??false})}}return findings.sort((left,right)=>left.file.localeCompare(right.file)||(left.line??0)-(right.line??0))}async function kitFiles(cwd){try{const manifest=JSON.parse(await readFile10(path12.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry=>Object.keys(entry?.files??{}).map(file=>path12.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir6(directory,{withFileTypes:true});for(const entry of entries){if(entry.name.startsWith(".")){continue}const full=path12.join(directory,entry.name);if(entry.isDirectory()){if(!skippedDirectories.has(entry.name)){await walk(full)}}else if(entry.isFile()&&sourceFile.test(entry.name)){found.push(full)}}};await walk(cwd);return found.sort()}function isTest(cwd,file){const parts=relative(cwd,file).split("/");return testName.test(parts.at(-1)??"")||parts.slice(0,-1).some(part=>testDirectories.has(part))}function cssModule(text){const imports=[];const plain=text.replace(/\/\*[\s\S]*?\*\//g,"");const pattern=/@(?:import|reference|plugin|config)\s+(?:url\(\s*)?["']([^"']+)["']/g;for(const match of plain.matchAll(pattern)){imports.push({specifier:match[1]??"",names:new Set})}return{imports,reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set}}function probe(base,known){if(known.has(base)){return base}for(const extension of probeExtensions){if(known.has(base+extension)){return base+extension}}const compiled=/\.([cm]?)js(x?)$/.exec(base);if(compiled){const stem=base.slice(0,-compiled[0].length);for(const extension of[`.${compiled[1]}ts${compiled[2]}`,`.${compiled[1]}tsx`]){if(known.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path12.join(base,`index${extension}`);if(known.has(index)){return index}}return void 0}function routeFiles(parsed,app,known){if(!parsed){return[]}const helper=local2=>{const binding=parsed.bindings.get(local2);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value2=>{const file=value2?probe(path12.resolve(app,value2),known):void 0;if(file){files.add(file)}};for(const call of parsed.calls){const name=helper(call.callee);if(name==="route"){add2(call.args[1])}else if(name==="index"||name==="layout"){add2(call.args[0])}else if(name==="flatRoutes"){const directory=path12.join(app,"routes")+path12.sep;for(const file of known){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value2 of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value2)){add2(value2)}}return files}async function createResolver(cwd,app,known,ts){const aliases=[...await tsconfigPaths(cwd,ts),...await packageImports(cwd)];for(const prefix of["~/","@/"]){if(!aliases.some(({pattern})=>pattern.startsWith(prefix))){aliases.push({pattern:`${prefix}*`,targets:[path12.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path12.resolve(path12.dirname(from),bare),known)}if(bare.startsWith("/")){return probe(path12.join(cwd,bare),known)}for(const{pattern,targets}of aliases){const star=pattern.indexOf("*");const head=star<0?pattern:pattern.slice(0,star);const tail=star<0?"":pattern.slice(star+1);const matches2=star<0?bare===pattern:bare.startsWith(head)&&bare.endsWith(tail)&&bare.length>=head.length+tail.length;if(!matches2){continue}const middle=star<0?"":bare.slice(head.length,bare.length-tail.length);for(const target of targets){const file=probe(target.replace("*",middle),known);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path12.join(cwd,value2),known):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile10(path12.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value2])=>{const target=typeof value2==="string"?value2:value2&&typeof value2==="object"?value2.import??value2.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path12.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir6(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read3=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path12.resolve(path12.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path12.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path12.resolve(path12.dirname(file),parent);read3(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read3(path12.join(cwd,name),0)}return aliases}function reach(roots,edges){const seen=new Set;const pending=[...roots];while(pending.length>0){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);pending.push(...edges(file))}return seen}function usage(importers,modules,resolve2){const used=new Map;const visited=new Set;const mark=(file,names)=>{const parsed=modules.get(file)?.parsed;if(!parsed){return}const list3=names==="all"?[...parsed.exports.keys(),"*"]:names;for(const name of list3){const key=`${file}\0${name}`;if(visited.has(key)){continue}visited.add(key);let own=used.get(file);if(!own){own=new Set;used.set(file,own)}own.add(name);for(const{specifier,names:forwarded}of parsed.reexports){const target=resolve2(file,specifier);if(!target){continue}if(forwarded==="star"){if(name==="*"){mark(target,"all")}else if(!parsed.exports.has(name)){mark(target,new Set([name]))}}else if(name==="*"){mark(target,new Set(forwarded.values()))}else{const source=forwarded.get(name);if(source!==void 0){mark(target,new Set([source]))}}}}};for(const importer of importers){const parsed=modules.get(importer)?.parsed;for(const{specifier,names}of parsed?.imports??[]){const target=resolve2(importer,specifier);if(target){mark(target,names)}}for(const{specifier,names}of parsed?.reexports??[]){const target=resolve2(importer,specifier);if(target&&names!=="star"){mark(target,new Set(names.values()))}}}return used}async function checkUnused({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("unused","TypeScript isn't installed, so unused code wasn't checked.")}const app=await appDirectory(cwd);const entries=await readdir7(path13.join(cwd,app)).catch(()=>void 0);if(!entries){return skipped("unused",`No ${app} directory was found.`)}if(!entries.some(name=>/^(?:routes|root)\.[cm]?[jt]sx?$/.test(name))){return skipped("unused",`No ${app}/routes.ts or ${app}/root.tsx was found to start from.`)}const findings=await findUnused(cwd,ts,app);signal?.throwIfAborted();const fail=findings.length>0&&await failsOnUnused(cwd);const checked=owned(site,findings.map(finding=>({problem:toProblem(finding),blocks:fail})));return step("unused",checked.failed?"failed":"passed",checked.problems)}function toProblem(finding){const details={rule:finding.rule,file:finding.file,...finding.line?{line:finding.line}:{}};const{name}=finding;if(name===void 0){return finding.rule==="unused/file"?problem("Nothing imports this file.","Delete it, or import it where it's meant to be used.",details):problem("Only tests import this file, so it never ships.","Delete it with its tests, or import it where it's meant to be used.",details)}return problem(finding.rule==="unused/export"?`No other file imports ${name}.`:`Only tests import ${name}. No shipped code uses it from here.`,exportFix(finding.rule,name,finding.usedHere),details)}function exportFix(rule,name,here){if(rule==="unused/test-only"){return here?"Remove the export and test it through the code in this file that uses it.":`Delete ${name} with its tests, or use it where it's meant to be used.`}if(here){return"Remove the export keyword. This file still uses it."}return name==="default"?"Remove the default export, or import it where it's meant to be used.":`Delete ${name}. Nothing in the site uses it.`}function loadTypeScript(cwd){for(const base of[path13.join(cwd,"package.json"),import.meta.url]){try{return createRequire(base)("typescript")}catch{continue}}return void 0}async function appDirectory(cwd){for(const name of["react-router.config.ts","react-router.config.js"]){try{const source=await readFile11(path13.join(cwd,name),"utf8");const match=/appDirectory\s*:\s*["'`]([^"'`]+)["'`]/.exec(source);return match?.[1]?.replace(/^\.\//,"").replace(/\/$/,"")??"app"}catch{continue}}return"app"}async function failsOnUnused(cwd){try{const value2=(await loadConfig(cwd)).value;return value2?.unused?.fail===true}catch{return false}}var RULES_RULES={invalid:"rules/invalid",enforcement:"rules/enforcement",unknownId:"rules/unknown-id",secret:"rules/secret-variable",itemAccess:"rules/item-access",notWired:"rules/not-wired",rootGate:"rules/root-gate"};var FILES=["app/rules.ts","app/rules.tsx","app/rules.js"];var NAME=/^[A-Z][A-Z0-9_]*$/;var ISO_TIME=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;async function rulesKnowledge(env=process.env){const known={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile12(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known.items=new Set(catalogue.items)}}catch{}}return known}async function read2(cwd,file){try{return await readFile12(path14.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry of object.properties){if((ts.isPropertyAssignment(entry)||ts.isMethodDeclaration(entry))&&entry.name&&(ts.isIdentifier(entry.name)||ts.isStringLiteral(entry.name))&&entry.name.text===name){return entry}if(ts.isShorthandPropertyAssignment(entry)&&entry.name.text===name){return entry}}return void 0}function value(ts,object,name){const entry=property(ts,object,name);return entry&&ts.isPropertyAssignment(entry)?entry.initializer:void 0}function readIds(ts,node){if(!node){return void 0}if(ts.isArrayLiteralExpression(node)){const ids=node.elements.flatMap(element=>ts.isStringLiteralLike(element)?[element.text]:[]);return ids.length===node.elements.length?{ids}:{unknown:true}}if(ts.isStringLiteralLike(node)){return{ids:[node.text]}}if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="variable"&&node.arguments[0]&&ts.isStringLiteralLike(node.arguments[0])){return{variable:node.arguments[0].text}}return{unknown:true}}function readSecret(ts,gate){if(gate&&ts.isCallExpression(gate)&&gate.arguments[0]&&ts.isObjectLiteralExpression(gate.arguments[0])){const secret=value(ts,gate.arguments[0],"secret");return secret&&ts.isStringLiteralLike(secret)?secret.text:""}return void 0}function findRules(ts,source){let found;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="defineRules"&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=node.arguments[0]}ts.forEachChild(node,visit)};visit(source);return found}var describeIds=(ids,kind)=>!ids?[]:"variable"in ids?[`${kind} from ${ids.variable}`]:"ids"in ids?[`${ids.ids.length} ${kind}`]:[kind];async function pages(cwd,directory="app"){let entries;try{entries=await readdir8(path14.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry of entries){const file=path14.posix.join(directory,entry.name);if(entry.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry.name)&&!/\.(test|spec)\./.test(entry.name)){files.push(file)}}return files}async function rulesProblems(cwd,known={}){let file;let text;for(const candidate of FILES){text=await read2(cwd,candidate);if(text!==void 0){file=candidate;break}}if(!file||text===void 0){return[]}const found=[];const add2=(blocks,message4,fix,rule,at=file)=>found.push({problem:problem(message4,fix,{rule,file:at}),blocks});const ts=loadTypeScript(cwd);if(!ts){add2(false,"TypeScript isn't installed, so app/rules.ts wasn't checked.","Install typescript.",RULES_RULES.invalid);return found}const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);const rules=findRules(ts,source);if(!rules){add2(true,`${file} doesn't export defineRules({ \u2026 })`,'Export the rules as `export default defineRules({ \u2026 })` from "@zappie/sdk/rules".',RULES_RULES.invalid);return found}const declared=[];const collections=value(ts,rules,"collections");if(collections&&ts.isArrayLiteralExpression(collections)){collections.elements.forEach((element,index)=>{if(!ts.isObjectLiteralExpression(element)){return}const categories=readIds(ts,value(ts,element,"categories"));const items=readIds(ts,value(ts,element,"items"));const secret=readSecret(ts,value(ts,element,"gate"));declared.push({label:`collections[${index}]`,...secret!==void 0?{secret}:{},...categories?{categories}:{},...items?{items}:{}});if(!categories&&!items){add2(true,`collections[${index}] names no categories and no items`,"Give it categories, items or both.",RULES_RULES.invalid)}})}const site=value(ts,rules,"site");if(site){const{file:root,texts}=await rootModules(cwd);const reads=texts.some(code=>namesOf(code,["siteGate"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(code)));if(root&&!reads){add2(false,`${file} gates the whole site, and ${root}'s loader never reads siteGate, so a page the router renders for a shopper the gate holds can draw the shop`,`In ${root}'s loader, call siteGate(rules, request, env) from @zappie/sdk/rules/server and return the gate page's data, and nothing of the shop, while it isn't open. Decide it there, never from the path.`,RULES_RULES.rootGate,root)}}if(site&&ts.isObjectLiteralExpression(site)){const secret=readSecret(ts,value(ts,site,"gate"));const until=readIds(ts,value(ts,site,"until"));const time=until&&"ids"in until?until.ids[0]:void 0;if(time!==void 0&&!ISO_TIME.test(time)){add2(true,`site.until is "${time}", and the gate reads only an ISO 8601 date and time with its offset or Z, so it never lifts`,"Write it as 2026-12-15T18:00:00+01:00, or keep it in a site variable with variable(name).",RULES_RULES.invalid)}declared.push({label:"site",...secret!==void 0?{secret}:{},...until?{until}:{}})}for(const rule of declared){if(rule.secret!==void 0&&!NAME.test(rule.secret)){add2(true,`${rule.label}'s gate secret must name a site variable, such as DROPS_PASSWORD, not hold the password`,"Put the password in a secret site variable and name the variable in secret.",RULES_RULES.invalid)}else if(rule.secret&&known.variables&&!known.variables.has(rule.secret)){add2(true,`${rule.label}'s gate reads ${rule.secret}, and the site has no variable by that name`,`Add ${rule.secret} as a secret site variable with the password, or name the variable the site has.`,RULES_RULES.secret)}for(const ids of[rule.categories,rule.items,rule.until]){if(ids&&"variable"in ids&&known.variables&&!known.variables.has(ids.variable)){add2(false,`${rule.label} reads ${ids.variable}, and the site has no variable by that name, so it gates nothing yet`,`Add ${ids.variable} as a site variable.`,RULES_RULES.secret)}}for(const[ids,kind]of[[rule.categories,"category"],[rule.items,"item"]]){const menus=ids&&"ids"in ids?ids.ids.filter(id=>/^(menu|mgrp)_/.test(id.trim())):[];if(menus.length){add2(true,`${rule.label} names ${menus.join(", ")}, a menu's ID, not ${kind==="item"?"an item's":"a category's"}`,`Copy the ${kind}'s ID from the dashboard. It works with or without its ${kind==="item"?"item_":"cat_"} prefix.`,RULES_RULES.invalid)}}for(const[ids,shop,kind]of[[rule.categories,known.categories,"category"],[rule.items,known.items,"item"]]){if(ids&&"ids"in ids&&shop){const prefix=kind==="category"?"cat_":"item_";const missing3=ids.ids.filter(id=>!shop.has(id)&&!shop.has(`${prefix}${id}`)&&!/^(var|opt|menu|mgrp)_/.test(id));if(missing3.length){add2(false,`${rule.label} names ${missing3.length===1?kind==="item"?"an item":"a category":kind==="category"?"categories":"items"} the shop doesn't have: ${missing3.join(", ")}. The rule ignores ${missing3.length===1?"it":"them"}.`,`Check the ID${missing3.length===1?"":"s"} against the dashboard, or remove ${missing3.length===1?"it":"them"}.`,RULES_RULES.unknownId)}}}const what=[...describeIds(rule.categories,"categories"),...describeIds(rule.items,"items")];add2(false,`${rule.label}${what.length?` (${what.join(", ")})`:""}: enforced by this site only. Someone who calls the API directly can still read and buy what it keeps back.`,null,RULES_RULES.enforcement)}for(const name of["visible","purchasable"]){if(property(ts,rules,name)){add2(false,`${name}(item, ctx): enforced by this site only, as code Zappie can't run in the API.`,null,RULES_RULES.enforcement)}}const worker=await read2(cwd,"workers/app.ts")??await read2(cwd,"workers/app.js");if(worker!==void 0&&!/\brules\b/.test(worker)){add2(true,`${file} declares rules, and workers/app.ts never passes them to siteWorker, so no gate is enforced`,'Pass them to siteWorker: rules: () => import("../app/rules").',RULES_RULES.notWired,"workers/app.ts")}for(const page of await pages(cwd)){const code=await read2(cwd,page);if(code&&/\b(useItem|useMenu)\s*\(/.test(code)&&!/\baccess\b/.test(code)){add2(false,`${page} renders items without reading their access, so a locked item looks like any other until add to bag refuses it`,"Read access from useItem (or useMenu().access(id)) and show its locked state.",RULES_RULES.itemAccess,page)}}return found}async function checkReadiness({cwd,signal,site:files}){signal?.throwIfAborted();const closedPage=await closedPageProblems(cwd);return outcome(files,[...await routeDiscovery(cwd),...closedPage.map(found=>({problem:found,blocks:true})),...await rulesProblems(cwd,await rulesKnowledge())])}async function routeDiscovery(cwd){const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return[{problem:problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"}),blocks:false}]}const file=path15.join(cwd,"react-router.config.ts");try{await readFile13(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return[]}}catch(error){return[{problem:problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}return[{problem:problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}function outcome(files,found){const checked=owned(files,found);return step("readiness",checked.failed?"failed":"passed",checked.problems)}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat,readFile as readFile14,readdir as readdir9}from"fs/promises";import path16 from"path";import{promisify}from"util";var FIX2="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value2=>{const live=value2.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX2,severity:"error"}});if(!envFile){add(matches2,source,/pk_live_[A-Za-z0-9]{16,}/g,()=>({rule:"secrets/pk-live",message:"Warning: detected pk_live_\u2026 outside an .env file.",fix:"Move the publishable key to a server-provided environment variable.",severity:"warning"}))}add(matches2,source,/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,()=>({rule:"secrets/private-key",message:"Detected a PEM private key header.",fix:FIX2,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX2,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX2,severity:"error"}));const gitleaksDefaults=[[/\bghp_[A-Za-z0-9]{36}\b/g,"github-pat","GitHub personal access token"],[/\bgithub_pat_[A-Za-z0-9_]{82}\b/g,"github-fine-grained-pat","GitHub fine-grained access token"],[/\bglpat-[A-Za-z0-9_-]{20,}\b/g,"gitlab-pat","GitLab personal access token"],[/\bnpm_[A-Za-z0-9]{36}\b/g,"npm-token","npm access token"],[/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,"slack-token","Slack token"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"google-api-key","Google API key"],[/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g,"sendgrid-api-key","SendGrid API key"]];for(const[pattern,rule,label]of gitleaksDefaults){add(matches2,source,pattern,()=>({rule:`secrets/${rule}`,message:`Detected a ${label}.`,fix:FIX2,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value2=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value2);if(entropy(value2)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value2.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX2,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value2){const counts=new Map;for(const character of value2){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value2.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile14(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path16.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal,site}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const checked=owned(site,findings.map(({severity,...finding})=>({problem:finding,blocks:severity==="error"})));return step("secrets",checked.failed?"failed":"passed",checked.problems)}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect2(path16.join(cwd,directory),files)}return[...new Set(files)].filter(file=>{const name=relative(cwd,file);return!lockfile.test(name)&&!inCliState(name)}).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path16.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect2(path16.join(cwd,directory),files)}try{for(const entry of await readdir9(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path16.join(cwd,entry.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect2(directory,files,accept=()=>true){try{for(const entry of await readdir9(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path16.join(directory,entry.name);if(entry.isDirectory()){await collect2(file,files,accept)}else if(entry.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import path17 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path17.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path18 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path18.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,budgets:3e4,css:6e4,unused:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss},{name:"unused",run:checkUnused}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list3,options,settleMs=SETTLE_MS){const{all,onProgress,site:_site,...rest}=options;const site=siteFilesFor(options);const stepOptions={...rest,...site?{site}:{}};const report=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry=>entry.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value2=options.timeouts?.[name];return value2!==void 0&&Number.isFinite(value2)&&value2>0?value2:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_CORNER_FILES,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,SITE_CODE_FOLDERS,SITE_ENV,analyseCss,carriesSecrets,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkTests,checkTypes,checkUnused,devSourceProblems,developerMayChange,evaluateAudit,findUnused,inSiteCode,isTestFile,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand,zappieManages};
|
|
9
|
+
},`,{rule:"budgets/css-route-record",file:"zappie.config.ts"})}var suggestedKb=bytes=>Math.ceil(bytes*1.1/KIB*2)/2;function cssProblem(sizes,limitKb,over,guide){const bytes=total(sizes);if(over&&guide){return problem(`CSS is ${kb(bytes)} gzip, above the ${kb((limitKb??0)*KIB)} guide.`,`${PUBLISH_GOES_AHEAD} Less client CSS makes the pages faster.`,{rule:"budgets/css-over"})}const limit=limitKb===void 0?"not enforced: budgets.routeCssKbGz limits each route instead":`limit ${limitKb*KIB} B`;return problem(`Client CSS: ${bytes} B gzip (${limit}).`,over?"Reduce client CSS or raise the reviewed budget override.":null,{rule:over?"budgets/css-over":"budgets/css"})}var total=sizes=>sizes.reduce((sum,asset)=>sum+asset.bytes,0);import{readdir as readdir5,readFile as readFile10}from"fs/promises";import path10 from"path";import{readdir as readdir4,readFile as readFile9}from"fs/promises";import path9 from"path";var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);import{readFile as readFile8,readdir as readdir3}from"fs/promises";import path8 from"path";var BUILD_OUTPUT=["build/client","build/server"];var QUOTE="[\"'`]";var URL_TEXT="((?:[a-z][a-z\\d+.-]*:|//|\\\\\\\\)[^\"'`\\s]*)";var JS_NAVIGATION=[new RegExp(`\\blocation(?:\\.href)?\\s*=\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\blocation\\.(?:assign|replace)\\(\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\bopen\\(\\s*${QUOTE}${URL_TEXT}`,"gi")];var REFRESH_URL=`\\d*\\s*;?\\s*url\\s*=\\s*['"]?([^"'\`\\s$;]+)`;var JS_REFRESH=[new RegExp(`http-?equiv["']?\\s*[:,=]\\s*["']refresh["']\\s*,\\s*["']?content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi"),new RegExp(`content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}['"]?${QUOTE}\\s*,\\s*["']?http-?equiv["']?\\s*[:,=]\\s*["']refresh`,"gi"),new RegExp(`["']refresh["']\\s*[:,]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi")];var HTML_META=/<meta\b[^>]*>/gi;var ABSOLUTE="((?:https?:)?//[^\"'`\\s<>$]+)";var HTML_LINK=new RegExp(`\\s(?:href|action|formaction|src|poster|data)\\s*=\\s*["']?\\s*${ABSOLUTE}`,"gi");var JS_LINK=[new RegExp(`[{,]\\s*["']?(?:href|to|action|formAction|src|poster)["']?\\s*:\\s*${QUOTE}\\s*${ABSOLUTE}`,"g"),new RegExp(`setAttribute\\(\\s*["'](?:href|action|formaction|src)["']\\s*,\\s*${QUOTE}\\s*${ABSOLUTE}`,"gi"),new RegExp(`\\.(?:href|action|src)\\s*=\\s*${QUOTE}\\s*${ABSOLUTE}`,"g")];var HTML_SCRIPT=/<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;var APP_SCHEMES=/^(?:tel|mailto|sms):/;function untrusted(value2,trusted){const url=value2.trim().replaceAll("\\","/").toLowerCase();if(!/^(?:[a-z][a-z\d+.-]*:|\/\/)/.test(url)||APP_SCHEMES.test(url)){return false}return!trusted.some(origin=>url===origin||url.startsWith(`${origin}/`))}function lineAt(source,index){return source.slice(0,index).split("\n").length}var PACKAGE_HOSTS=["maps.googleapis.com"];var CSP_HOSTS=["fonts.googleapis.com","fonts.gstatic.com"];async function siteConfig(cwd){try{return(await loadConfig(cwd)).value}catch{return void 0}}async function knownHosts(cwd){const config=await siteConfig(cwd);const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links,siteHosts(config).map(({host})=>host)].flatMap(list3=>Array.isArray(list3)?list3:[]).filter(host=>typeof host==="string");return[...new Set(["*.zappie.ai","zappie.ai","zappie.shop","images.zappie.shop",...typeof config?.store==="string"?[`${config.store}.zappie.shop`]:[],...RESIZE_HOSTS,...PACKAGE_HOSTS,...CSP_HOSTS,...configured])].filter(Boolean).map(host=>host.toLowerCase())}function listedHost(url,hosts){let host;try{host=new URL(url.startsWith("//")?`https:${url}`:url).hostname.toLowerCase()}catch{return false}return hosts.some(entry2=>entry2.startsWith("*.")?host.endsWith(entry2.slice(1)):host===entry2)}function linkFindings(source,patterns,hosts){const found=[];for(const pattern of patterns){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(!listedHost(url,hosts)){found.push({rule:"build/unlisted-link-host",index:match.index,url})}}}return found}function scanScript(source,hosts,trusted){const found=linkFindings(source,JS_LINK,hosts);for(const pattern of JS_NAVIGATION){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-offsite-navigation",index:match.index,url})}}}for(const pattern of JS_REFRESH){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}}return found}function scanHtml(source,hosts,trusted){const found=linkFindings(source,[HTML_LINK],hosts);for(const match of source.matchAll(HTML_META)){const tag=match[0];if(!/\bhttp-equiv\s*=\s*["']?\s*refresh/i.test(tag)){continue}const url=new RegExp(REFRESH_URL,"i").exec(tag)?.[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}for(const match of source.matchAll(HTML_SCRIPT)){const src=match[1]??match[2]??match[3]??"";if(/^\s*(?:[a-z][a-z\d+.-]*:|\/\/|\\\\)/i.test(src)){found.push({rule:"build/no-external-script",index:match.index,url:src})}}return found}var MESSAGES={"build/no-offsite-navigation":{message:url=>`The build output sends the shopper to ${url} from code. Only Zappie's checkout and accounts may be opened this way.`,fix:"Find the code or package that navigates there and remove it, or link to the page with an <a href> the shopper clicks."},"build/no-meta-refresh":{message:url=>`The build output has a refresh that moves the shopper to ${url} without a click.`,fix:"Remove the refresh tag or header, or the package that adds it. Use a router redirect to a path on this site."},"build/unlisted-link-host":{message:url=>`The build output links to or loads ${url}, on a host the site doesn't list.`,fix:"If the site loads from that host, add it with zappie hosts add <host> --for image (or font, style, frame). If the store means to link there, add it to security.links in zappie.config.ts. Otherwise find the code or content that names it and remove it."},"build/no-external-script":{message:url=>`The built page loads a script from ${url}.`,fix:"Install the code as a package so it ships in the storefront bundle, and remove the script tag. Or, for an https script the site means to load, add its host with zappie hosts add <host> --for script."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const scripts=hostsFor(await siteConfig(cwd),"script");const chosenScript=finding=>finding.rule==="build/no-external-script"&&finding.url!==void 0&&/^\s*https:\/\//i.test(finding.url)&&listedHost(finding.url.trim(),scripts);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry2 of entries.sort()){const html=/\.html?$/i.test(entry2);if(!html&&!/\.[cm]?js$/i.test(entry2)){continue}const file=path8.join(cwd,directory,entry2);const source=await readFile8(file,"utf8").catch(()=>"");const findings=(html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted)).filter(finding=>!chosenScript(finding));const named=new Set(findings.filter(finding=>finding.rule!=="build/unlisted-link-host").map(finding=>finding.url));const reported=new Set;for(const finding of findings.sort((a,b)=>a.index-b.index)){const link=finding.rule==="build/unlisted-link-host";const key=`${finding.rule}\0${link?finding.url:finding.index}`;if(reported.has(key)||link&&named.has(finding.url)){continue}reported.add(key);const text=MESSAGES[finding.rule];if(!text){continue}problems.push(problem(text.message(finding.url),text.fix,{rule:finding.rule,file:relative(cwd,file),line:lineAt(source,finding.index)}))}}}return problems}var ATTRIBUTES=["data-zappie-source","data-zappie-component"];async function devSourceProblems(cwd){const problems=[];for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir4(path9.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry2 of entries.sort()){const file=path9.join(cwd,directory,entry2);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry2)){continue}const source=await readFile9(file,"utf8").catch(()=>"");const found=ATTRIBUTES.find(attribute=>source.includes(attribute));if(found){problems.push(problem(`The build output has the dev-only ${found} attribute, which shows where the site's code lives.`,"Add zappieSource() to the Vite plugins only for the dev server, as the starter does, and remove any copy of the attribute from your code.",{rule:"build/no-dev-source-attributes",file:relative(cwd,file)}))}}}return problems}var PREBUILT_ENV="ZAPPIE_CHECK_PREBUILT";var PREBUILT_RULE="build/prebuilt";async function checkBuild({cwd,packageManager,signal,prebuilt}){signal?.throwIfAborted();const manifest=JSON.parse(await readFile10(path10.join(cwd,"package.json"),"utf8"));const invocation=manifest.dependencies?.["react-router"]?await binaryArgs(packageManager,cwd,"react-router",["build"]):manifest.scripts?.build?scriptArgs(packageManager,"build"):void 0;if(!invocation){return skipped("build","No react-router dependency or build script is defined in package.json.")}if((prebuilt??process.env[PREBUILT_ENV]==="1")&&await hasBuildOutput(cwd)){const problems=await scanProblems(cwd);signal?.throwIfAborted();return step("build",problems.length?"failed":"passed",[...problems,problem("Used the existing build output instead of building again.",null,{rule:PREBUILT_RULE})])}const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){const problems=await scanProblems(cwd);return step("build",problems.length?"failed":"passed",problems)}return step("build","failed",[problem(`The project build failed.
|
|
10
|
+
${usefulTail(result.stdout,result.stderr)}`,"Fix the reported build errors and run zappie check again.",{rule:"build/failed"})])}async function scanProblems(cwd){return[...await devSourceProblems(cwd),...await outputProblems(cwd)]}async function hasBuildOutput(cwd){for(const directory of BUILD_OUTPUT){const entries=await readdir5(path10.join(cwd,directory)).catch(()=>[]);if(entries.length>0){return true}}return false}function usefulTail(stdout,stderr){const lines=`${stdout}
|
|
11
|
+
${stderr}`.split(/\r?\n/).map(line=>line.trimEnd()).filter(Boolean).slice(-12);return lines.length>0?lines.join("\n"):"The build exited without output."}import postcss3 from"postcss";import postcss from"postcss";var DEFAULT_CORNER_FILES=["app/**/checkout/**","app/**/{account,orders,order,sign-in,cart-notice,bag-drawer,closed,not-found}{,-*}.{tsx,jsx,ts,js,mdx,css}"];var ALLOW=/zappie-allow-radius:\s*\S/;var SIDE="(?:-(?:[trblse]|tl|tr|br|bl|ss|se|es|ee))?";var ROUNDED=new RegExp(`^-?rounded${SIDE}(?:-(.+))?$`);var ZERO=/^(?:none|0|\[0(?:px|rem|em|%)?\])$/;var FIX="Use one of the site's radius tokens, such as rounded-[var(--z-radius-md)], a rounded-<name> your @theme defines or var(--radius-<name>) in CSS, so this screen follows the brand. A true circle on an icon-only control can stay with zappie-allow-radius: <reason> on its line or the line above.";function globPattern(glob){let source="";let depth=0;for(let index=0;index<glob.length;index++){const character=glob[index];if(glob.startsWith("**/",index)){source+="(?:.*/)?";index+=2}else if(glob.startsWith("**",index)){source+=".*";index++}else if(character==="*"){source+="[^/]*"}else if(character==="?"){source+="[^/]"}else if(character==="{"){depth++;source+="(?:"}else if(character==="}"&&depth){depth--;source+=")"}else if(character===","&&depth){source+="|"}else{source+=character.replace(/[.+^$()|[\]\\]/g,"\\$&")}}return new RegExp(`^${source}$`)}function literalRadii(inputs,corners={}){const patterns=(corners.files??DEFAULT_CORNER_FILES).map(globPattern);const shared=({file})=>patterns.some(pattern=>pattern.test(file));const tokens=new Set([...inputs.sourceCss.map(({text})=>text).join("\n").matchAll(/--radius-([\w-]+)\s*:/g)].map(match=>match[1]));const problems=[];const report2=(file,line,what)=>problems.push(problem(`${what} sets a corner radius the site's theme doesn't control.`,FIX,{rule:"css/literal-radius",file,line}));const literal2=(tokensInList,token)=>{const match=ROUNDED.exec(withoutVariants(token).utility);if(!match){return false}const size=match[1];if(size===void 0){return true}if(ZERO.test(size)||/--|var\(/.test(size)||tokens.has(size)){return false}return!(/^(?:full|\[50%\])$/.test(size)&&square(tokensInList))};for(const entry2 of inputs.sourceCode.filter(shared)){const lines=entry2.text.split(/\r?\n/);lines.forEach((text,index)=>{if(ALLOW.test(text)||ALLOW.test(lines[index-1]??"")){return}for(const list3 of classLists(text.replace(/\$\{[^{}]*\}/g," "))){const tokensInList=list3.split(/\s+/);for(const token of tokensInList){if(literal2(tokensInList,token)){report2(entry2.file,index+1,token)}}}for(const match of text.matchAll(/borderRadius\s*:\s*(["'`]?)([^"'`,}]+)\1/g)){const value2=match[2].trim();if((match[1]||/^[\d.]+$/.test(value2))&&literalValue(value2)){report2(entry2.file,index+1,`borderRadius: ${value2}`)}}})}for(const entry2 of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry2.text)}catch{continue}const lines=entry2.text.split(/\r?\n/);const allowed=(line=0)=>ALLOW.test(lines[line-1]??"")||ALLOW.test(lines[line-2]??"");root.walkDecls(/^border(?:-[a-z]+)*-radius$/i,decl=>{const line=decl.source?.start?.line??0;if(literalValue(decl.value)&&!allowed(line)){report2(entry2.file,line,`${decl.prop}: ${decl.value}`)}});root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line??0;const list3=rule.params.split(/\s+/);for(const token of list3){if(literal2(list3,token)&&!allowed(line)){report2(entry2.file,line,`@apply ${token}`)}}})}return problems}function literalValue(value2){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value2)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value2)}function square(list3){const utilities=list3.map(token=>withoutVariants(token).utility);return utilities.some(utility=>/^size-/.test(utility)||utility==="aspect-square"||/^h-/.test(utility)&&utilities.includes(`w-${utility.slice(2)}`))}import path11 from"path";import postcss2 from"postcss";var ROOT_ROUTE_CSS="css/root-route-css";var ROOT_MODULES=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES=["",".tsx",".ts",".jsx",".js",".mjs","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var CSS_IMPORT=/^\s*(?:url\()?["']?([^"')\s]+)["']?\)?/;var CLASS=/\.(-?[_a-zA-Z][\w-]*)/g;var TOKEN=/[_a-zA-Z][\w-]*/g;var SHOWN=4;function rootRouteCss(inputs){const code=new Map(inputs.sourceCode.map(entry2=>[entry2.file,entry2]));const css=new Map(inputs.sourceCss.map(entry2=>[entry2.file,entry2]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known2=file=>code.has(file)||css.has(file);const graph=new Set;const sheets=new Set;const pending=[root];while(pending.length){const file=pending.pop();if(graph.has(file)){continue}graph.add(file);for(const[,specifier]of code.get(file).text.matchAll(STATIC_IMPORT)){const target=resolve(file,specifier,known2);if(target&&css.has(target)){sheets.add(target)}else if(target&&code.has(target)){pending.push(target)}}}for(const sheet of[...sheets]){cssImports(css.get(sheet),known2).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry2=>{let found=tokens.get(entry2.file);if(!found){found=new Set(entry2.text.match(TOKEN)??[]);tokens.set(entry2.file,found)}return found};const problems=[];for(const sheet of[...sheets].sort()){const groups=new Map;for(const[name,line]of classesOf(css.get(sheet))){const users=inputs.sourceCode.filter(entry2=>tokensOf(entry2).has(name)).map(entry2=>entry2.file);if(users.length===0||users.some(file=>graph.has(file))){continue}const key=users.sort().join("\n");const group=groups.get(key)??{classes:[]};group.classes.push(name);group.line??=line;groups.set(key,group)}for(const[key,{classes,line}]of groups){const users=key.split("\n");problems.push(problem(`${sheet} loads on every page through ${root}, but ${list2(classes.map(name=>`.${name}`))} ${classes.length===1?"is":"are"} drawn only by ${list2(users)}.`,`Move ${classes.length===1?"it":"them"} into a stylesheet that ${users.length===1?"module":"one of those modules"} imports, so ${classes.length===1?"it loads":"they load"} with that route or overlay and not on every page.`,{rule:ROOT_ROUTE_CSS,file:sheet,...line?{line}:{}}))}}return problems}function resolve(from,specifier,known2){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path11.posix.join(path11.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known2)}function cssImports(entry2,known2){const found=[];try{postcss2.parse(entry2.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry2.file,specifier,known2);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry2){const classes=new Map;try{postcss2.parse(entry2.text).walkRules(rule=>{const parent=rule.parent;if(parent?.type==="atrule"&&/keyframes$/i.test(parent.name)){return}for(const[,name]of rule.selector.matchAll(CLASS)){if(!classes.has(name)){classes.set(name,rule.source?.start?.line)}}})}catch{}return classes}function list2(names){const shown=names.slice(0,SHOWN);const rest=names.length-shown.length;if(rest>0){return`${shown.join(", ")} and ${rest} more`}return shown.length>1?`${shown.slice(0,-1).join(", ")} and ${shown.at(-1)}`:shown[0]}var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs,corners){const source=parseAll(inputs.sourceCss);const built=parseAll(inputs.builtCss);return[...source.problems,...built.problems,...important(source.parsed,inputs.sourceCode),...duplicateKeyframes(source.parsed,built.parsed),...duplicateSelectors(source.parsed),...arbitraryTokens(source.parsed,inputs.sourceCode),...unusedCustomProperties(source.parsed,built.parsed,inputs),...reducedMotion(source.parsed),...classPatches(source.parsed),...literalTokens(source.parsed),...rootRouteCss(inputs),...literalRadii(inputs,corners)]}function parseAll(files){const parsed=[];const problems=[];for(const entry2 of files){try{parsed.push({...entry2,root:postcss3.parse(entry2.text,{from:entry2.file}),lines:entry2.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry2.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry2.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry2 of css){entry2.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry2.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry2.file,line))}});entry2.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry2.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry2.file,line))}})}for(const entry2 of code){const lines=entry2.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list3 of classLists(text)){for(const token of list3.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry2.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value2=match[2]?.trim()??"";if(!value2){continue}const tokens=value2.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value2)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry2 of files){entry2.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry2.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value2=>value2.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value2){return value2.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first3,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first3?.file}${first3?.line?`:${first3.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first3=group[0];problems.push(problem(`@keyframes ${first3?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first3)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first3,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first3?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry2){return{rule,...entry2?{file:entry2.file}:{},...entry2?.line?{line:entry2.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry2 of source){entry2.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first3=seen.get(key);if(!first3){seen.set(key,{file:entry2.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first3.file}${first3.line?`:${first3.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry2.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry2 of source){entry2.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value2=>value2.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value2=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value2===candidate.value||value2===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry2 of code){scan(entry2.text,entry2.file)}for(const entry2 of source){entry2.root.walkAtRules("apply",rule=>{scan(rule.params,entry2.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry2 of source){entry2.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry2.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read4=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry2 of[...source,...built]){for(const match of entry2.text.matchAll(cssReads)){read4.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry2 of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry2.text.matchAll(scriptMentions)){read4.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read4.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry2 of source){entry2.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry2 of source){entry2.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry2.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry2 of source){entry2.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry2.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry2 of source){entry2.root.walkDecls(/^--/,decl=>{const value2=compact(decl.value);if(value2.includes("var(")||trivialValue.test(value2)||tokens.has(value2)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value2,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry2 of source){entry2.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry2.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal,site}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const corners=await cornerSettings(cwd);const problems=analyseCss(inputs,corners);signal?.throwIfAborted();const checked=advised(site,problems.map(found=>({problem:found,blocks:CSS_ERRORS.has(found.rule)||found.rule==="css/literal-radius"&&corners.fail===true})));return step("css",checked.failed?"failed":"passed",checked.problems)}async function cornerSettings(cwd){try{const value2=(await loadConfig(cwd)).value;const{files,fail}=value2?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile15}from"fs/promises";import path16 from"path";import{pathToFileURL}from"url";import{readFile as readFile11}from"fs/promises";import path12 from"path";var CLOSED_PAGE_RULE="readiness/closed-page";var WORKERS=["workers/app.ts","workers/app.js"];var ROOTS=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES2=["",".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT2=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var MARKS=/\b(?:siteWorker|markClosedPage)\s*[<(]/;var COMMENTS=/\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g;async function read(cwd,file){try{return(await readFile11(path12.join(cwd,file),"utf8")).replace(COMMENTS,"$1")}catch{return void 0}}async function first(cwd,files){for(const file of files){const text=await read(cwd,file);if(text!==void 0){return{file,text}}}return void 0}function local(from,specifier){if(specifier.startsWith("~/")){return path12.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path12.posix.join(path12.posix.dirname(from),specifier)}return void 0}var HOST_ADAPTERS=["siteHost","zappieHost"];function namesOf(text,exported){const names=[...exported];const pattern=new RegExp(`\\b(?:${exported.join("|")})\\s+as\\s+(\\w+)`,"g");for(const[,alias]of text.matchAll(pattern)){names.push(alias)}return names}function adapterCall(text){return`\\b(?:${namesOf(text,HOST_ADAPTERS).join("|")})\\s*\\([^()]*\\)`}function adapterNames(text){const bound=new RegExp(`\\b(?:const|let|var)\\s+(\\w+)\\s*(?::[^=;]+)?=\\s*${adapterCall(text)}`,"g");return[...text.matchAll(bound)].map(([,name])=>name)}function readsClosed(text,adapters){const closed=[adapterCall(text),...adapters.map(name=>`(?<![\\w$.])${name}`)];return namesOf(text,["siteClosed"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(text))||new RegExp(`(?:${closed.join("|")})\\s*\\.\\s*closed\\s*\\(`).test(text)}async function rootModules(cwd){const root=await first(cwd,ROOTS);const texts2=[];const seen=new Set;const pending=root?[root.file]:[];while(pending.length){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);const text=file===root?.file?root.text:await read(cwd,file);if(text===void 0){continue}texts2.push(text);for(const[,specifier]of text.matchAll(STATIC_IMPORT2)){const target=local(file,specifier);if(!target){continue}for(const suffix of SUFFIXES2){if(await read(cwd,target+suffix)!==void 0){pending.push(target+suffix);break}}}}return{file:root?.file,texts:texts2}}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const{file:rootFile,texts:texts2}=await rootModules(cwd);const adapters=texts2.flatMap(adapterNames);if(texts2.some(text=>readsClosed(text,adapters))){return[]}const file=rootFile??"app/root.tsx";return[problem(`${worker.file} marks a closed page, but ${file} never reads siteClosed(request) to draw one`,`In ${file}'s loader, call siteHost(context).closed(request) from @zappie/foundations/site/server, or siteClosed(request) from @zappie/sdk/site-closed, and return your closed page's data when it answers, as the starter's root does. Until then a switched-off store shows Zappie's closed page, or your full shop where the Worker calls markClosedPage itself.`,{rule:CLOSED_PAGE_RULE,file})]}import{readFile as readFile14,readdir as readdir8}from"fs/promises";import path15 from"path";import{readFile as readFile13,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path14 from"path";import{readFile as readFile12,readdir as readdir6}from"fs/promises";import path13 from"path";function parseModule(ts,file,text,deep){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,false,scriptKind(ts,file));const parsed={imports:[],reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set};const locals=new Map;const line=node=>source.getLineAndCharacterOfPosition(node.getStart(source)).line+1;const exported=(name,node,local2=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local2)}};for(const statement of source.statements){if(ts.isImportDeclaration(statement)){readImport(ts,statement,parsed)}else if(ts.isExportDeclaration(statement)){readExport(ts,statement,parsed,exported)}else if(ts.isExportAssignment(statement)){exported("default",statement,"")}else if(hasExport(ts,statement)){for(const[name,local2]of declaredNames(ts,statement)){exported(name,statement,local2)}}}const references=new Set;const visit=(node,parent)=>{if(ts.isIdentifier(node)){if(parent&&!namesOnly(ts,parent,node)){references.add(node.text)}return}if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword){const specifier=literal(ts,node.arguments[0]);if(specifier!==void 0){parsed.imports.push({specifier,names:"all"})}}else if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal)){const qualifier=node.qualifier;parsed.imports.push({specifier:node.argument.literal.text,names:qualifier&&ts.isIdentifier(qualifier)?new Set([qualifier.text]):"all"})}else if(deep&&ts.isCallExpression(node)){const callee=node.expression;if(ts.isIdentifier(callee)){parsed.calls.push({callee:callee.text,args:node.arguments.map(argument=>literal(ts,argument))})}}if(deep&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))){parsed.strings.push(node.text)}ts.forEachChild(node,child=>visit(child,node))};visit(source);for(const[name,local2]of locals){if(local2&&references.has(local2)){parsed.usedHere.add(name)}}return parsed}function scriptKind(ts,file){if(/\.[jt]sx$/.test(file)){return ts.ScriptKind.TSX}return/\.[cm]?js$/.test(file)?ts.ScriptKind.JS:ts.ScriptKind.TS}function literal(ts,node){return node&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))?node.text:void 0}function readImport(ts,statement,parsed){const specifier=literal(ts,statement.moduleSpecifier);if(specifier===void 0){return}const clause=statement.importClause;const names=new Set;let taken=names;if(clause?.name){names.add("default");parsed.bindings.set(clause.name.text,{specifier,name:"default"})}const bindings=clause?.namedBindings;if(bindings&&ts.isNamespaceImport(bindings)){taken="all"}else if(bindings){for(const element of bindings.elements){const name=(element.propertyName??element.name).text;names.add(name);parsed.bindings.set(element.name.text,{specifier,name})}}parsed.imports.push({specifier,names:taken})}function readExport(ts,statement,parsed,exported){const specifier=literal(ts,statement.moduleSpecifier);const clause=statement.exportClause;if(specifier===void 0){if(clause&&ts.isNamedExports(clause)){for(const element of clause.elements){exported(element.name.text,element,(element.propertyName??element.name).text)}}return}if(!clause){parsed.reexports.push({specifier,names:"star"})}else if(ts.isNamespaceExport(clause)){exported(clause.name.text,clause,"");parsed.imports.push({specifier,names:"all"})}else{const names=new Map;for(const element of clause.elements){names.set(element.name.text,(element.propertyName??element.name).text);exported(element.name.text,element,"")}parsed.reexports.push({specifier,names})}}function hasExport(ts,statement){return ts.canHaveModifiers(statement)&&(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)}function namesOnly(ts,parent,node){if(ts.isImportSpecifier(parent)||ts.isExportSpecifier(parent)||ts.isImportClause(parent)||ts.isNamespaceImport(parent)){return true}if(ts.isPropertyAccessExpression(parent)||ts.isQualifiedName(parent)){return(ts.isPropertyAccessExpression(parent)?parent.name:parent.right)===node}return(ts.isFunctionDeclaration(parent)||ts.isClassDeclaration(parent)||ts.isInterfaceDeclaration(parent)||ts.isTypeAliasDeclaration(parent)||ts.isEnumDeclaration(parent)||ts.isModuleDeclaration(parent)||ts.isVariableDeclaration(parent)||ts.isPropertyAssignment(parent)||ts.isPropertySignature(parent)||ts.isPropertyDeclaration(parent)||ts.isMethodDeclaration(parent)||ts.isMethodSignature(parent)||ts.isJsxAttribute(parent))&&parent.name===node}function declaredNames(ts,statement){const name=statement.name;const local2=name&&(ts.isIdentifier(name)||ts.isStringLiteral(name))?name.text:"";const isDefault=(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword);if(isDefault){return[["default",local2]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry2=>[entry2,entry2])}return local2?[[local2,local2]]:[]}function bindingNames(ts,name){if(ts.isIdentifier(name)){return[name.text]}return name.elements.flatMap(element=>ts.isOmittedExpression(element)?[]:bindingNames(ts,element.name))}var skippedDirectories=new Set(["node_modules","build","dist","public","vendor","coverage","test-results","playwright-report"]);var codeFile=/\.(?:[cm]?[jt]sx?)$/;var sourceFile=/\.(?:[cm]?[jt]sx?|css)$/;var probeExtensions=[".ts",".tsx",".js",".jsx",".mts",".mjs",".cts",".cjs"];var testDirectories=new Set(["test","tests","__tests__","__mocks__","e2e"]);var testName=/(?:\.(?:test|spec|bench)\.[cm]?[jt]sx?$)|(?:^(?:vitest|playwright)\.[^/]*$)/;var configFile=/^(?:vite|react-router)\.config\.[cm]?[jt]s$/;var routeExports=new Set(["default","loader","clientLoader","action","clientAction","meta","links","headers","handle","ErrorBoundary","HydrateFallback","Layout","shouldRevalidate","middleware","clientMiddleware","unstable_middleware","unstable_clientMiddleware"]);async function routeModuleFiles(project,ts,appDirectory2="app"){const app=path13.join(path13.resolve(project),appDirectory2);let files;try{files=await listFiles(app)}catch{return{routes:[]}}const known2=new Set(files);const root=probe(path13.join(app,"root"),known2);const routesFile=probe(path13.join(app,"routes"),known2);const config=routesFile?parseModule(ts,routesFile,await readFile12(routesFile,"utf8"),true):void 0;const routes=[...routeFiles(config,app,known2)].filter(file=>file!==root&&file!==routesFile);return{...root?{root}:{},...routesFile?{routesFile}:{},routes:routes.sort(),...config?{config}:{}}}async function findUnused(project,ts,appDirectory2="app"){const cwd=path13.resolve(project);const app=path13.join(cwd,appDirectory2);const files=await listFiles(cwd);const known2=new Set(files);const modules=new Map;const routesFile=probe(path13.join(app,"routes"),known2);const configs=files.filter(file=>path13.dirname(file)===cwd&&configFile.test(path13.basename(file)));for(const file of files){const deep=file===routesFile||configs.includes(file);const module={file,test:isTest(cwd,file)};if(codeFile.test(file)){module.parsed=parseModule(ts,file,await readFile12(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile12(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known2,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path13.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path13.join(app,"root"),known2);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known2)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry2=probe(path13.join(app,name),known2);if(entry2){quiet.add(entry2)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value2=>{const target=resolver.fromRoot(value2);return target?[target]:[]}));for(const file of named){quiet.add(file)}const productionRoots=[...routeModules,...quiet,...named,...files.filter(file=>!inApp(file)&&!modules.get(file)?.test)];const testRoots=files.filter(file=>modules.get(file)?.test);const edges=file=>[...modules.get(file)?.parsed?.imports??[],...modules.get(file)?.parsed?.reexports??[]].flatMap(({specifier})=>{const target=resolver.resolve(file,specifier);return target?[target]:[]});const production=reach(productionRoots,edges);const tested=reach(testRoots,edges);const used=usage([...production].filter(file=>!modules.get(file)?.test),modules,resolver.resolve);const testUsed=usage(testRoots,modules,resolver.resolve);const findings=[];for(const module of modules.values()){if(!candidate(module)){continue}const file=relative(cwd,module.file);if(!production.has(module.file)){findings.push({rule:tested.has(module.file)?"unused/test-only":"unused/file",file});continue}if(quiet.has(module.file)||kit.has(module.file)){continue}const isRoute=routeModules.has(module.file);for(const[name,line]of module.parsed?.exports??[]){if(isRoute&&routeExports.has(name)){continue}if(used.get(module.file)?.has(name)){continue}findings.push({rule:testUsed.get(module.file)?.has(name)?"unused/test-only":"unused/export",file,name,line,usedHere:module.parsed?.usedHere.has(name)??false})}}return findings.sort((left,right)=>left.file.localeCompare(right.file)||(left.line??0)-(right.line??0))}async function kitFiles(cwd){try{const manifest=JSON.parse(await readFile12(path13.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry2=>Object.keys(entry2?.files??{}).map(file=>path13.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir6(directory,{withFileTypes:true});for(const entry2 of entries){if(entry2.name.startsWith(".")){continue}const full=path13.join(directory,entry2.name);if(entry2.isDirectory()){if(!skippedDirectories.has(entry2.name)){await walk(full)}}else if(entry2.isFile()&&sourceFile.test(entry2.name)){found.push(full)}}};await walk(cwd);return found.sort()}function isTest(cwd,file){const parts=relative(cwd,file).split("/");return testName.test(parts.at(-1)??"")||parts.slice(0,-1).some(part=>testDirectories.has(part))}function cssModule(text){const imports=[];const plain=text.replace(/\/\*[\s\S]*?\*\//g,"");const pattern=/@(?:import|reference|plugin|config)\s+(?:url\(\s*)?["']([^"']+)["']/g;for(const match of plain.matchAll(pattern)){imports.push({specifier:match[1]??"",names:new Set})}return{imports,reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set}}function probe(base,known2){if(known2.has(base)){return base}for(const extension of probeExtensions){if(known2.has(base+extension)){return base+extension}}const compiled=/\.([cm]?)js(x?)$/.exec(base);if(compiled){const stem=base.slice(0,-compiled[0].length);for(const extension of[`.${compiled[1]}ts${compiled[2]}`,`.${compiled[1]}tsx`]){if(known2.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path13.join(base,`index${extension}`);if(known2.has(index)){return index}}return void 0}function routeFiles(parsed,app,known2){if(!parsed){return[]}const helper=local2=>{const binding=parsed.bindings.get(local2);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value2=>{const file=value2?probe(path13.resolve(app,value2),known2):void 0;if(file){files.add(file)}};for(const call of parsed.calls){const name=helper(call.callee);if(name==="route"){add2(call.args[1])}else if(name==="index"||name==="layout"){add2(call.args[0])}else if(name==="flatRoutes"){const directory=path13.join(app,"routes")+path13.sep;for(const file of known2){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value2 of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value2)){add2(value2)}}return files}async function createResolver(cwd,app,known2,ts){const aliases=[...await tsconfigPaths(cwd,ts),...await packageImports(cwd)];for(const prefix of["~/","@/"]){if(!aliases.some(({pattern})=>pattern.startsWith(prefix))){aliases.push({pattern:`${prefix}*`,targets:[path13.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path13.resolve(path13.dirname(from),bare),known2)}if(bare.startsWith("/")){return probe(path13.join(cwd,bare),known2)}for(const{pattern,targets}of aliases){const star=pattern.indexOf("*");const head=star<0?pattern:pattern.slice(0,star);const tail=star<0?"":pattern.slice(star+1);const matches2=star<0?bare===pattern:bare.startsWith(head)&&bare.endsWith(tail)&&bare.length>=head.length+tail.length;if(!matches2){continue}const middle=star<0?"":bare.slice(head.length,bare.length-tail.length);for(const target of targets){const file=probe(target.replace("*",middle),known2);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path13.join(cwd,value2),known2):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile12(path13.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value2])=>{const target=typeof value2==="string"?value2:value2&&typeof value2==="object"?value2.import??value2.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path13.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir6(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read4=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path13.resolve(path13.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path13.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path13.resolve(path13.dirname(file),parent);read4(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read4(path13.join(cwd,name),0)}return aliases}function reach(roots,edges){const seen=new Set;const pending=[...roots];while(pending.length>0){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);pending.push(...edges(file))}return seen}function usage(importers,modules,resolve2){const used=new Map;const visited=new Set;const mark=(file,names)=>{const parsed=modules.get(file)?.parsed;if(!parsed){return}const list3=names==="all"?[...parsed.exports.keys(),"*"]:names;for(const name of list3){const key=`${file}\0${name}`;if(visited.has(key)){continue}visited.add(key);let own=used.get(file);if(!own){own=new Set;used.set(file,own)}own.add(name);for(const{specifier,names:forwarded}of parsed.reexports){const target=resolve2(file,specifier);if(!target){continue}if(forwarded==="star"){if(name==="*"){mark(target,"all")}else if(!parsed.exports.has(name)){mark(target,new Set([name]))}}else if(name==="*"){mark(target,new Set(forwarded.values()))}else{const source=forwarded.get(name);if(source!==void 0){mark(target,new Set([source]))}}}}};for(const importer of importers){const parsed=modules.get(importer)?.parsed;for(const{specifier,names}of parsed?.imports??[]){const target=resolve2(importer,specifier);if(target){mark(target,names)}}for(const{specifier,names}of parsed?.reexports??[]){const target=resolve2(importer,specifier);if(target&&names!=="star"){mark(target,new Set(names.values()))}}}return used}async function checkUnused({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("unused","TypeScript isn't installed, so unused code wasn't checked.")}const app=await appDirectory(cwd);const entries=await readdir7(path14.join(cwd,app)).catch(()=>void 0);if(!entries){return skipped("unused",`No ${app} directory was found.`)}if(!entries.some(name=>/^(?:routes|root)\.[cm]?[jt]sx?$/.test(name))){return skipped("unused",`No ${app}/routes.ts or ${app}/root.tsx was found to start from.`)}const findings=await findUnused(cwd,ts,app);signal?.throwIfAborted();const fail=findings.length>0&&await failsOnUnused(cwd);const checked=advised(site,findings.map(finding=>({problem:fail?toProblem(finding):warning(toProblem(finding)),blocks:fail})));return step("unused",checked.failed?"failed":"passed",checked.problems)}function toProblem(finding){const details={rule:finding.rule,file:finding.file,...finding.line?{line:finding.line}:{}};const{name}=finding;if(name===void 0){return finding.rule==="unused/file"?problem("Nothing imports this file.","Delete it, or import it where it's meant to be used.",details):problem("Only tests import this file, so it never ships.","Delete it with its tests, or import it where it's meant to be used.",details)}return problem(finding.rule==="unused/export"?`No other file imports ${name}.`:`Only tests import ${name}. No shipped code uses it from here.`,exportFix(finding.rule,name,finding.usedHere),details)}function exportFix(rule,name,here){if(rule==="unused/test-only"){return here?"Remove the export and test it through the code in this file that uses it.":`Delete ${name} with its tests, or use it where it's meant to be used.`}if(here){return"Remove the export keyword. This file still uses it."}return name==="default"?"Remove the default export, or import it where it's meant to be used.":`Delete ${name}. Nothing in the site uses it.`}function loadTypeScript(cwd){for(const base of[path14.join(cwd,"package.json"),import.meta.url]){try{return createRequire(base)("typescript")}catch{continue}}return void 0}async function appDirectory(cwd){for(const name of["react-router.config.ts","react-router.config.js"]){try{const source=await readFile13(path14.join(cwd,name),"utf8");const match=/appDirectory\s*:\s*["'`]([^"'`]+)["'`]/.exec(source);return match?.[1]?.replace(/^\.\//,"").replace(/\/$/,"")??"app"}catch{continue}}return"app"}async function failsOnUnused(cwd){try{const value2=(await loadConfig(cwd)).value;return value2?.unused?.fail===true}catch{return false}}var RULES_RULES={invalid:"rules/invalid",enforcement:"rules/enforcement",unknownId:"rules/unknown-id",secret:"rules/secret-variable",itemAccess:"rules/item-access",notWired:"rules/not-wired",rootGate:"rules/root-gate"};var FILES=["app/rules.ts","app/rules.tsx","app/rules.js"];var NAME2=/^[A-Z][A-Z0-9_]*$/;var ISO_TIME=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;async function rulesKnowledge(env=process.env){const known2={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known2.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile14(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known2.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known2.items=new Set(catalogue.items)}}catch{}}return known2}async function read2(cwd,file){try{return await readFile14(path15.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry2 of object.properties){if((ts.isPropertyAssignment(entry2)||ts.isMethodDeclaration(entry2))&&entry2.name&&(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name))&&entry2.name.text===name){return entry2}if(ts.isShorthandPropertyAssignment(entry2)&&entry2.name.text===name){return entry2}}return void 0}function value(ts,object,name){const entry2=property(ts,object,name);return entry2&&ts.isPropertyAssignment(entry2)?entry2.initializer:void 0}function readIds(ts,node){if(!node){return void 0}if(ts.isArrayLiteralExpression(node)){const ids=node.elements.flatMap(element=>ts.isStringLiteralLike(element)?[element.text]:[]);return ids.length===node.elements.length?{ids}:{unknown:true}}if(ts.isStringLiteralLike(node)){return{ids:[node.text]}}if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="variable"&&node.arguments[0]&&ts.isStringLiteralLike(node.arguments[0])){return{variable:node.arguments[0].text}}return{unknown:true}}function readSecret(ts,gate){if(gate&&ts.isCallExpression(gate)&&gate.arguments[0]&&ts.isObjectLiteralExpression(gate.arguments[0])){const secret=value(ts,gate.arguments[0],"secret");return secret&&ts.isStringLiteralLike(secret)?secret.text:""}return void 0}function findRules(ts,source){let found;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="defineRules"&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=node.arguments[0]}ts.forEachChild(node,visit)};visit(source);return found}var describeIds=(ids,kind)=>!ids?[]:"variable"in ids?[`${kind} from ${ids.variable}`]:"ids"in ids?[`${ids.ids.length} ${kind}`]:[kind];async function pages(cwd,directory="app"){let entries;try{entries=await readdir8(path15.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry2 of entries){const file=path15.posix.join(directory,entry2.name);if(entry2.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry2.name)&&!/\.(test|spec)\./.test(entry2.name)){files.push(file)}}return files}async function rulesProblems(cwd,known2={}){let file;let text;for(const candidate of FILES){text=await read2(cwd,candidate);if(text!==void 0){file=candidate;break}}if(!file||text===void 0){return[]}const found=[];const add2=(blocks,message4,fix,rule,at=file)=>found.push({problem:problem(message4,fix,{rule,file:at}),blocks});const ts=loadTypeScript(cwd);if(!ts){add2(false,"TypeScript isn't installed, so app/rules.ts wasn't checked.","Install typescript.",RULES_RULES.invalid);return found}const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);const rules=findRules(ts,source);if(!rules){add2(true,`${file} doesn't export defineRules({ \u2026 })`,'Export the rules as `export default defineRules({ \u2026 })` from "@zappie/sdk/rules".',RULES_RULES.invalid);return found}const declared=[];const collections=value(ts,rules,"collections");if(collections&&ts.isArrayLiteralExpression(collections)){collections.elements.forEach((element,index)=>{if(!ts.isObjectLiteralExpression(element)){return}const categories=readIds(ts,value(ts,element,"categories"));const items=readIds(ts,value(ts,element,"items"));const secret=readSecret(ts,value(ts,element,"gate"));declared.push({label:`collections[${index}]`,...secret!==void 0?{secret}:{},...categories?{categories}:{},...items?{items}:{}});if(!categories&&!items){add2(true,`collections[${index}] names no categories and no items`,"Give it categories, items or both.",RULES_RULES.invalid)}})}const site=value(ts,rules,"site");if(site){const{file:root,texts:texts2}=await rootModules(cwd);const reads=texts2.some(code=>namesOf(code,["siteGate"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(code)));if(root&&!reads){add2(false,`${file} gates the whole site, and ${root}'s loader never reads siteGate, so a page the router renders for a shopper the gate holds can draw the shop`,`In ${root}'s loader, call siteGate(rules, request, env) from @zappie/sdk/rules/server and return the gate page's data, and nothing of the shop, while it isn't open. Decide it there, never from the path.`,RULES_RULES.rootGate,root)}}if(site&&ts.isObjectLiteralExpression(site)){const secret=readSecret(ts,value(ts,site,"gate"));const until=readIds(ts,value(ts,site,"until"));const time=until&&"ids"in until?until.ids[0]:void 0;if(time!==void 0&&!ISO_TIME.test(time)){add2(true,`site.until is "${time}", and the gate reads only an ISO 8601 date and time with its offset or Z, so it never lifts`,"Write it as 2026-12-15T18:00:00+01:00, or keep it in a site variable with variable(name).",RULES_RULES.invalid)}declared.push({label:"site",...secret!==void 0?{secret}:{},...until?{until}:{}})}for(const rule of declared){if(rule.secret!==void 0&&!NAME2.test(rule.secret)){add2(true,`${rule.label}'s gate secret must name a site variable, such as DROPS_PASSWORD, not hold the password`,"Put the password in a secret site variable and name the variable in secret.",RULES_RULES.invalid)}else if(rule.secret&&known2.variables&&!known2.variables.has(rule.secret)){add2(true,`${rule.label}'s gate reads ${rule.secret}, and the site has no variable by that name`,`Add ${rule.secret} as a secret site variable with the password, or name the variable the site has.`,RULES_RULES.secret)}for(const ids of[rule.categories,rule.items,rule.until]){if(ids&&"variable"in ids&&known2.variables&&!known2.variables.has(ids.variable)){add2(false,`${rule.label} reads ${ids.variable}, and the site has no variable by that name, so it gates nothing yet`,`Add ${ids.variable} as a site variable.`,RULES_RULES.secret)}}for(const[ids,kind]of[[rule.categories,"category"],[rule.items,"item"]]){const menus=ids&&"ids"in ids?ids.ids.filter(id=>/^(menu|mgrp)_/.test(id.trim())):[];if(menus.length){add2(true,`${rule.label} names ${menus.join(", ")}, a menu's ID, not ${kind==="item"?"an item's":"a category's"}`,`Copy the ${kind}'s ID from the dashboard. It works with or without its ${kind==="item"?"item_":"cat_"} prefix.`,RULES_RULES.invalid)}}for(const[ids,shop,kind]of[[rule.categories,known2.categories,"category"],[rule.items,known2.items,"item"]]){if(ids&&"ids"in ids&&shop){const prefix=kind==="category"?"cat_":"item_";const missing3=ids.ids.filter(id=>!shop.has(id)&&!shop.has(`${prefix}${id}`)&&!/^(var|opt|menu|mgrp)_/.test(id));if(missing3.length){add2(false,`${rule.label} names ${missing3.length===1?kind==="item"?"an item":"a category":kind==="category"?"categories":"items"} the shop doesn't have: ${missing3.join(", ")}. The rule ignores ${missing3.length===1?"it":"them"}.`,`Check the ID${missing3.length===1?"":"s"} against the dashboard, or remove ${missing3.length===1?"it":"them"}.`,RULES_RULES.unknownId)}}}const what=[...describeIds(rule.categories,"categories"),...describeIds(rule.items,"items")];add2(false,`${rule.label}${what.length?` (${what.join(", ")})`:""}: enforced by this site only. Someone who calls the API directly can still read and buy what it keeps back.`,null,RULES_RULES.enforcement)}for(const name of["visible","purchasable"]){if(property(ts,rules,name)){add2(false,`${name}(item, ctx): enforced by this site only, as code Zappie can't run in the API.`,null,RULES_RULES.enforcement)}}const worker=await read2(cwd,"workers/app.ts")??await read2(cwd,"workers/app.js");if(worker!==void 0&&!/\brules\b/.test(worker)){add2(true,`${file} declares rules, and workers/app.ts never passes them to siteWorker, so no gate is enforced`,'Pass them to siteWorker: rules: () => import("../app/rules").',RULES_RULES.notWired,"workers/app.ts")}for(const page of await pages(cwd)){const code=await read2(cwd,page);if(code&&/\b(useItem|useMenu)\s*\(/.test(code)&&!/\baccess\b/.test(code)){add2(false,`${page} renders items without reading their access, so a locked item looks like any other until add to bag refuses it`,"Read access from useItem (or useMenu().access(id)) and show its locked state.",RULES_RULES.itemAccess,page)}}return found}async function checkReadiness({cwd,signal,site:files}){signal?.throwIfAborted();const closedPage=await closedPageProblems(cwd);return outcome(files,[...await routeDiscovery(cwd),...closedPage.map(found=>({problem:found,blocks:true})),...await rulesProblems(cwd,await rulesKnowledge())])}async function routeDiscovery(cwd){const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return[{problem:problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"}),blocks:false}]}const file=path16.join(cwd,"react-router.config.ts");try{await readFile15(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return[]}}catch(error){return[{problem:problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}return[{problem:problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}function outcome(files,found){const checked=owned(files,found);return step("readiness",checked.failed?"failed":"passed",checked.problems)}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat as lstat2,readFile as readFile16,readdir as readdir9}from"fs/promises";import path17 from"path";import{promisify}from"util";var FIX2="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value2=>{const live=value2.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX2,severity:"error"}});if(!envFile){add(matches2,source,/pk_live_[A-Za-z0-9]{16,}/g,()=>({rule:"secrets/pk-live",message:"Warning: detected pk_live_\u2026 outside an .env file.",fix:"Move the publishable key to a server-provided environment variable.",severity:"warning"}))}add(matches2,source,/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,()=>({rule:"secrets/private-key",message:"Detected a PEM private key header.",fix:FIX2,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX2,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX2,severity:"error"}));const gitleaksDefaults=[[/\bghp_[A-Za-z0-9]{36}\b/g,"github-pat","GitHub personal access token"],[/\bgithub_pat_[A-Za-z0-9_]{82}\b/g,"github-fine-grained-pat","GitHub fine-grained access token"],[/\bglpat-[A-Za-z0-9_-]{20,}\b/g,"gitlab-pat","GitLab personal access token"],[/\bnpm_[A-Za-z0-9]{36}\b/g,"npm-token","npm access token"],[/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,"slack-token","Slack token"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"google-api-key","Google API key"],[/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g,"sendgrid-api-key","SendGrid API key"]];for(const[pattern,rule,label]of gitleaksDefaults){add(matches2,source,pattern,()=>({rule:`secrets/${rule}`,message:`Detected a ${label}.`,fix:FIX2,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value2=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value2);if(entropy(value2)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value2.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX2,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value2){const counts=new Map;for(const character of value2){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value2.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat2(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile16(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path17.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal,site}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const checked=owned(site,findings.map(({severity,...finding})=>({problem:severity==="warning"?{...finding,severity}:finding,blocks:severity==="error"})));return step("secrets",checked.failed?"failed":"passed",checked.problems)}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect2(path17.join(cwd,directory),files)}return[...new Set(files)].filter(file=>{const name=relative(cwd,file);return!lockfile.test(name)&&!inCliState(name)}).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path17.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect2(path17.join(cwd,directory),files)}try{for(const entry2 of await readdir9(cwd,{withFileTypes:true})){if(entry2.isFile()&&rootConfig(entry2.name)){files.push(path17.join(cwd,entry2.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect2(directory,files,accept=()=>true){try{for(const entry2 of await readdir9(directory,{withFileTypes:true})){if(entry2.isSymbolicLink()){continue}const file=path17.join(directory,entry2.name);if(entry2.isDirectory()){await collect2(file,files,accept)}else if(entry2.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import{readFile as readFile18}from"fs/promises";import path19 from"path";import{readFile as readFile17}from"fs/promises";import path18 from"path";var SEO_FILE_NAMES=["icon.png","icon.svg","favicon.ico","apple-icon.png","opengraph-image.png","opengraph-image.jpg","twitter-image.png"];var SEO_FILE_LIMIT=256*1024;var ICON_MIN=48;var APPLE_SIZE=180;var SHARE={width:1200,height:630};var PNG=[137,80,78,71,13,10,26,10];function pngSize(bytes){if(bytes.length<24||PNG.some((byte,index)=>bytes[index]!==byte)){return void 0}const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);return{width:view.getUint32(16),height:view.getUint32(20)}}function svgSize(text){const tag=/<svg\b[^>]*>/i.exec(text)?.[0];if(!tag){return void 0}const box=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];const parts=box?.trim().split(/[\s,]+/).map(Number);if(parts?.length===4&&parts.every(Number.isFinite)){return{width:parts[2],height:parts[3]}}const width=Number(/\bwidth\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);const height=Number(/\bheight\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);return width>0&&height>0?{width,height}:void 0}async function seoFiles(cwd,app){const found=new Map;for(const name of SEO_FILE_NAMES){try{found.set(name,await readFile17(path18.join(cwd,app,name)))}catch{continue}}return found}function seoFileProblems(app,files){const found=[];const add2=(name,message4,fix,blocks=true)=>found.push({problem:problem(message4,fix,{rule:blocks?"seo/icon":"seo/share-image",file:`${app}/${name}`}),blocks});for(const[name,bytes]of files){const file=`${app}/${name}`;if(bytes.length>SEO_FILE_LIMIT){add2(name,`${file} is ${Math.ceil(bytes.length/1024)} KB, and the build takes at most ${SEO_FILE_LIMIT/1024} KB`,`Make ${file} smaller than ${SEO_FILE_LIMIT/1024} KB.`);continue}if(name==="icon.png"||name==="apple-icon.png"){const least=name==="icon.png"?ICON_MIN:APPLE_SIZE;const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height} px, and an icon must be square`,`Save ${file} square, at least ${least} px on each side.`)}else if(size.width<least){add2(name,`${file} is ${size.width} px square, smaller than ${least} px`,`Save ${file} at least ${least} px on each side.`)}}else if(name==="icon.svg"){const text=bytes.toString("utf8");const size=svgSize(text);if(!/<svg\b/i.test(text)){add2(name,`${file} isn't an SVG`,`Save ${file} as an SVG image.`)}else if(size&&size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height}, and an icon must be square`,`Give ${file} a square viewBox, such as viewBox="0 0 64 64".`)}}else if(name==="favicon.ico"){const ico=bytes.length>=4&&bytes[0]===0&&bytes[1]===0&&bytes[2]===1&&bytes[3]===0;if(!ico&&!pngSize(bytes)){add2(name,`${file} is neither an ICO nor a PNG image`,`Save ${file} as an ICO file, or remove it to serve the 48 px icon at /favicon.ico.`)}}else if(name.endsWith(".png")){const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==SHARE.width||size.height!==SHARE.height){add2(name,`${file} is ${size.width} by ${size.height} px. Share previews crop an image that isn't ${SHARE.width} by ${SHARE.height} px`,`Save ${file} at ${SHARE.width} by ${SHARE.height} px.`,false)}}}return found}var HEX=/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;var PATTERN_SEGMENT=/^(?::[A-Za-z_][A-Za-z0-9_]*|[^:*]*)$/;function isRedirectPattern(from){if(!from.startsWith("/")||from.startsWith("//")){return false}if(from==="/_zappie"||from.startsWith("/_zappie/")){return false}const segments=from.slice(1).split("/");return segments.every((segment,index)=>{if(segment==="*"){return index===segments.length-1}return PATTERN_SEGMENT.test(segment)})}var isHttps=value2=>{try{return new URL(value2).protocol==="https:"}catch{return false}};function validateSeoSpec(spec){const problems=[];const{titleTemplate,homeTitle,description,shareImage,themeColor}=spec;if(titleTemplate!==void 0){if(!titleTemplate.includes("{page}")&&!titleTemplate.includes("{store}")){problems.push("titleTemplate needs {page} or {store}.")}if(titleTemplate.length>120){problems.push("titleTemplate is longer than 120 characters.")}}if(homeTitle!==void 0&&homeTitle.length>70){problems.push("homeTitle is longer than 70 characters.")}if(typeof description==="string"&&description.length>300){problems.push("description is longer than 300 characters.")}if(typeof shareImage==="string"&&!isHttps(shareImage)){problems.push("shareImage must be an https address.")}for(const[key,value2]of[["themeColor",themeColor],["icons.background",spec.icons?.background]]){if(value2!==void 0&&!HEX.test(value2)){problems.push(`${key} must be a hex colour, such as #121212.`)}}for(const path22 of Object.keys(spec.pageNames??{})){if(!path22.startsWith("/")){problems.push(`pageNames key ${path22} must start with /.`)}}if(Array.isArray(spec.noindex)){for(const path22 of spec.noindex){if(!path22.startsWith("/")){problems.push(`noindex path ${path22} must start with /.`)}}}for(const redirect of spec.redirects??[]){if(!isRedirectPattern(redirect.from)){problems.push(`Redirect from ${redirect.from} must start with one /, stay outside /_zappie, and use only :name segments and one trailing *.`)}if(!(redirect.to.startsWith("/")&&!redirect.to.startsWith("//")||isHttps(redirect.to))){problems.push(`Redirect to ${redirect.to} must be a path or an https address.`)}if(redirect.status!==void 0&&redirect.status!==301&&redirect.status!==308){problems.push(`Redirect from ${redirect.from} must use 301 or 308.`)}}return problems}var UNKNOWN=Symbol("unknown");var HOOK=Symbol("hook");function defineNames(ts,source){const names=new Set(["defineSeo"]);for(const statement of source.statements){const bindings=ts.isImportDeclaration(statement)&&statement.importClause?.namedBindings;if(bindings&&ts.isNamedImports(bindings)){for(const element of bindings.elements){if((element.propertyName??element.name).text==="defineSeo"){names.add(element.name.text)}}}}return names}function literalValue2(ts,node){if(ts.isParenthesizedExpression(node)||ts.isAsExpression(node)||ts.isSatisfiesExpression(node)){return literalValue2(ts,node.expression)}if(ts.isStringLiteralLike(node)){return node.text}if(ts.isNumericLiteral(node)){return Number(node.text)}if(node.kind===ts.SyntaxKind.TrueKeyword){return true}if(node.kind===ts.SyntaxKind.FalseKeyword){return false}if(ts.isArrowFunction(node)||ts.isFunctionExpression(node)||ts.isMethodDeclaration(node)){return HOOK}if(ts.isArrayLiteralExpression(node)){return node.elements.map(element=>ts.isSpreadElement(element)?UNKNOWN:literalValue2(ts,element))}if(ts.isObjectLiteralExpression(node)){const object={};for(const entry2 of node.properties){const name=propertyName(ts,entry2);if(name===void 0){return UNKNOWN}object[name]=ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN}return object}return UNKNOWN}function propertyName(ts,entry2){if(ts.isSpreadAssignment(entry2)||!entry2.name){return void 0}if(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name)||ts.isNumericLiteral(entry2.name)){return entry2.name.text}return void 0}function readSpec(ts,file,text){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS);const names=defineNames(ts,source);const keys=new Map;let found=false;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&names.has(node.expression.text)&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=true;for(const entry2 of node.arguments[0].properties){const name=propertyName(ts,entry2);if(name===void 0){continue}const line=source.getLineAndCharacterOfPosition(entry2.getStart(source)).line+1;keys.set(name,{value:ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN,line})}}ts.forEachChild(node,visit)};visit(source);const defaultExport=source.statements.some(statement=>ts.isExportAssignment(statement)||ts.isExportDeclaration(statement)&&!!statement.exportClause&&ts.isNamedExports(statement.exportClause)&&statement.exportClause.elements.some(element=>element.name.text==="default")||(ts.isFunctionDeclaration(statement)||ts.isClassDeclaration(statement))&&!!statement.modifiers?.some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword));const importsFiles=source.statements.some(statement=>ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)&&statement.moduleSpecifier.text==="virtual:zappie-seo-files");return{found,defaultExport,keys,importsFiles}}function known(value2){if(value2===UNKNOWN){return false}if(Array.isArray(value2)){return value2.every(known)}if(value2&&typeof value2==="object"){return Object.values(value2).every(known)}return true}function asSpecValue(value2){if(value2===HOOK){return()=>void 0}if(Array.isArray(value2)){return value2.map(asSpecValue)}if(value2&&typeof value2==="object"){return Object.fromEntries(Object.entries(value2).map(([key,entry2])=>[key,asSpecValue(entry2)]))}return value2}function keyOf(sentence){if(sentence.startsWith("Redirect ")){return"redirects"}return sentence.split(/[\s.]/)[0]??""}function specProblems(spec){const readable={};for(const[name,key]of spec.keys){if(known(key.value)){readable[name]=asSpecValue(key.value)}}let sentences;try{sentences=validateSeoSpec(readable)}catch{return[]}return sentences.map(message4=>{const line=spec.keys.get(keyOf(message4))?.line;return{message:message4,...line?{line}:{}}})}var SEO_RULES={report:"seo/report",invalid:"seo/invalid",orderFrom:"seo/order-from",childMeta:"seo/child-meta",routes:"seo/routes-missing",filesUnused:"seo/files-unused",plugin:"seo/plugin-missing",notAdopted:"seo/not-adopted"};var SEO_FILES=["seo.ts","seo.tsx","seo.js","seo.jsx"];var HOOK_FILES=["manifest","robots","sitemap"];var DEFAULT_TEMPLATE="{page} \xB7 {store}";var ORDER_FROM=/\border from\b/i;var VITE_CONFIGS=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"];async function read3(file){try{return await readFile18(file,"utf8")}catch{return void 0}}async function first2(cwd,files){for(const file of files){const text=await read3(path19.join(cwd,file));if(text!==void 0){return{file,text}}}return void 0}function sourceOf(ts,file,text){return ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS)}function texts(ts,source,node){const found=[];const visit=child=>{if(ts.isStringLiteralLike(child)||ts.isTemplateHead(child)||ts.isTemplateMiddle(child)||ts.isTemplateTail(child)||ts.isJsxText(child)){found.push({text:child.text,line:source.getLineAndCharacterOfPosition(child.getStart(source)).line+1})}ts.forEachChild(child,visit)};visit(node);return found}function seoExports(ts,source){const found=[];for(const statement of source.statements){const exported=ts.canHaveModifiers(statement)?ts.getModifiers(statement)?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword):false;if(!exported){continue}if(ts.isVariableStatement(statement)){for(const declaration of statement.declarationList.declarations){if(ts.isIdentifier(declaration.name)&&["meta","handle"].includes(declaration.name.text)){found.push(declaration)}}}else if(ts.isFunctionDeclaration(statement)&&statement.name?.text==="meta"){found.push(statement)}}return found}function orderFrom(ts,file,source,nodes){return nodes.flatMap(node=>texts(ts,source,node).filter(({text})=>ORDER_FROM.test(text)).map(({text,line})=>({problem:problem(`${file} says "${text.trim().slice(0,80)}" in search and sharing text`,`Describe the store, as "Shop {store} online." or "Order food from {store} online." do, or leave the description to the store's own and the dashboard's. Search results and shared links never say "Order from".`,{rule:SEO_RULES.orderFrom,file,line}),blocks:true})))}var describeValue=value2=>typeof value2==="string"?`"${value2}"`:"";function overDashboard(spec,key,fallback){const value2=spec?.keys.get(key)?.value;if(value2===HOOK){return`code hook: ${key}, which wins over the dashboard`}if(value2!==void 0){const shown=describeValue(value2);return`dashboard, else code${shown?` ${shown}`:`: ${key}`}`}return`dashboard, else ${fallback}`}function objectOf(spec,key){const value2=spec?.keys.get(key)?.value;return value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:void 0}function hookOf(spec,key){return spec?.keys.get(key)?.value===HOOK}function report(input){const{spec,files,hookFiles,app}=input;const lines=[];const add2=(field,text)=>lines.push(`${field}: ${text}`);const template=spec?.keys.get("titleTemplate")?.value;add2("title template",template!==void 0?`dashboard, else code ${describeValue(template)||"titleTemplate"}`:`dashboard, else default "${DEFAULT_TEMPLATE}"`);if(hookOf(spec,"title")){add2("title","code hook: title, which wins over the dashboard")}add2("home title",overDashboard(spec,"homeTitle","derived (store name)"));const pageNames=objectOf(spec,"pageNames");add2("page names",pageNames?`code: pageNames (${Object.keys(pageNames).join(", ")})`:spec?.keys.has("pageNames")?"code: pageNames":"derived (shop words and each page's own name)");if(input.pageOverrides.length){add2("page overrides",`handle.seo in ${input.pageOverrides.join(", ")}`)}add2("description",overDashboard(spec,"description",`derived (the store's description, else "Shop {store} online." or "Order food from {store} online.")`));const shareFile=["opengraph-image.png","opengraph-image.jpg"].filter(name=>files.has(name)).map(name=>`${app}/${name}`)[0];add2("share image",overDashboard(spec,"shareImage",shareFile?`file: ${shareFile}`:"derived (cover, then logo card)"));const icons=objectOf(spec,"icons");const iconFile=["icon.svg","icon.png"].find(name=>files.has(name));add2("favicon",iconFile?`file: ${app}/${iconFile}${files.has("favicon.ico")?` and ${app}/favicon.ico`:""}`:icons?.fromLogo===false?"derived: a monogram of the store's initial (icons.fromLogo is false)":`derived from logo (no ${app}/icon.png)`);add2("apple icon",files.has("apple-icon.png")?`file: ${app}/apple-icon.png`:icons?.fromLogo===false?"derived: a monogram of the store's initial":"derived from logo");add2("manifest",hookFiles.has("manifest")||hookOf(spec,"manifest")?`derived + code hook${hookFiles.has("manifest")?` (${app}/manifest.ts)`:""}`:"derived");add2("theme color",spec?.keys.has("themeColor")?`code ${describeValue(spec.keys.get("themeColor")?.value)||"themeColor"}`:icons?.background!==void 0?"code: icons.background":"none");add2("canonical",hookOf(spec,"canonical")?"code hook: canonical":"derived (origin and path, with ?branch= on a branch's own menu)");const ld=objectOf(spec,"jsonLd")??{};const ldHooks=Object.keys(ld).filter(key=>key!=="extra");add2("json-ld",input.jsonLd?`Organization, WebSite, LocalBusiness \xD7branch, Product, BreadcrumbList${ldHooks.length?` (code hooks: ${ldHooks.join(", ")})`:""}${"extra"in ld?" + code: extra":""}`:"none: the root's seoMeta gets no jsonLd builder");const noindex=spec?.keys.get("noindex")?.value;const robotsHook=hookOf(spec,"robots")||hookFiles.has("robots");add2("robots",["floor",Array.isArray(noindex)?`code: noindex ${noindex.filter(entry2=>typeof entry2==="string").join(" ")}`:noindex===HOOK?"code: noindex test":noindex===UNKNOWN?"code: noindex":"",robotsHook?"code hook: robots":""].filter(Boolean).join(" + "));const sitemap=spec?.keys.get("sitemap")?.value;add2("sitemap",sitemap===HOOK||hookFiles.has("sitemap")?"derived + code hook":sitemap!==void 0?"derived + code options":"derived");const redirects=spec?.keys.get("redirects")?.value;add2("redirects",`dashboard + ${Array.isArray(redirects)?redirects.length:redirects===void 0?0:"some"} code patterns`);const verification=objectOf(spec,"verification");add2("verification",verification&&Object.keys(verification).length?`dashboard + code (${Object.keys(verification).join(", ")})`:"dashboard");if(hookOf(spec,"openGraph")){add2("open graph","derived + code hook: openGraph")}return lines}async function checkSeo({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("seo","TypeScript isn't installed, so search and sharing weren't checked.")}const app=await appDirectory(cwd);const routes=await routeModuleFiles(cwd,ts,app);if(!routes.root&&!routes.routesFile){return skipped("seo",`No ${app}/root.tsx or ${app}/routes.ts was found, so search and sharing weren't checked.`)}const found=[];const seoFile=await first2(cwd,SEO_FILES.map(name=>`${app}/${name}`));const spec=seoFile?readSpec(ts,seoFile.file,seoFile.text):void 0;const files=await seoFiles(cwd,app);const hookFiles=new Set;const seoCode=seoFile?[seoFile]:[];for(const name of HOOK_FILES){const hook=await first2(cwd,["ts","js"].map(extension=>`${app}/${name}.${extension}`));if(hook){hookFiles.add(name);seoCode.push(hook)}}const{texts:rootTexts}=await rootModules(cwd);const rendersSeo=rootTexts.some(text=>/\bseoMeta\s*\(/.test(text));const jsonLd=rootTexts.some(text=>/\bseoJsonLd\b/.test(text));const adopted=rendersSeo||!!spec?.found||rootTexts.some(text=>/["']@zappie\/sdk\/seo(?:\/server)?["']/.test(text));for(const code of seoCode){const source=sourceOf(ts,code.file,code.text);found.push(...orderFrom(ts,code.file,source,[source]))}const pageOverrides=[];const modules=[...routes.root?[routes.root]:[],...routes.routes];for(const module of modules){const text=await read3(module);if(text===void 0){continue}const file=relative(cwd,module);const source=sourceOf(ts,file,text);const whole=/^(?:sitemap|robots)(?:[.[\]\-\w]*)\.[cm]?[jt]sx?$/.test(path19.basename(module));const exports=seoExports(ts,source);found.push(...orderFrom(ts,file,source,whole?[source]:exports));if(module===routes.root){continue}if(/\bhandle\b[\s\S]*\bseo\s*:/.test(text)&&exports.length){pageOverrides.push(relative(cwd,module).replace(`${app}/`,""))}const parsed=parseModule(ts,module,text,false);const metaLine=parsed.exports.get("meta");if(metaLine!==void 0&&rendersSeo){found.push({problem:problem(`${file} exports meta, which replaces the root's whole head on this page: its canonical, icons, share tags and JSON-LD`,'Remove the meta export and say what the page is through `export const handle = { seo: { page: "\u2026" } }`. The root\'s seoMeta reads it.',{rule:SEO_RULES.childMeta,file,line:metaLine}),blocks:true})}}if(!adopted){found.push({problem:problem(`${routes.root?relative(cwd,routes.root):`${app}/root.tsx`} doesn't render its head with seoMeta from @zappie/sdk/seo/server, so the site doesn't get Zappie's search and sharing defaults`,"Update @zappie/sdk to 0.36.0 or later, export defineSeo({ \u2026 }) from app/seo.ts, render the root's meta with seoMeta, and add ...seoRoutes() to app/routes.ts, as the starter does.",{rule:SEO_RULES.notAdopted}),blocks:false});return outcome2(site,found)}if(!spec){found.push(reportLine(`config: no ${app}/seo.ts, so every value comes from the store and the dashboard`))}else if(!spec.found||!spec.defaultExport){found.push(reportLine(`config: ${seoFile.file} ${spec.found?"has no default export":"doesn't call defineSeo({ \u2026 })"}, so it counts as no SEO config`))}for(const issue of spec?specProblems(spec):[]){found.push({problem:problem(issue.message.replace(/\.$/,""),"Fix the value in app/seo.ts. defineSeo throws on it, so every page of the site would fail.",{rule:SEO_RULES.invalid,file:seoFile.file,...issue.line?{line:issue.line}:{}}),blocks:true})}found.push(...seoFileProblems(app,files));if(routes.routesFile){const config=routes.config;const registered=config?.calls.some(call=>{const binding=config.bindings.get(call.callee);return binding?.name==="seoRoutes"&&binding.specifier.startsWith("@zappie/sdk/seo")});if(!registered){found.push({problem:problem(`${relative(cwd,routes.routesFile)} doesn't add ...seoRoutes(), so the tab icon, the home-screen icon and the manifest the head links to answer 404`,'Add ...seoRoutes("routes/seo-assets.ts") from @zappie/sdk/seo/server before the catch-all route, with a routes/seo-assets.ts that exports seoAssetLoader({ \u2026 }) as its loader.',{rule:SEO_RULES.routes,file:relative(cwd,routes.routesFile)}),blocks:true})}}const usesFiles=files.size>0||hookFiles.size>0;if(spec?.found&&usesFiles&&!spec.keys.has("files")){const names=[...[...files.keys()].map(name=>`${app}/${name}`),...[...hookFiles].map(name=>`${app}/${name}.ts`)];found.push({problem:problem(`${seoFile.file} doesn't pass files to defineSeo, so ${names.join(", ")} ${names.length===1?"is":"are"} never served`,'Import files from "virtual:zappie-seo-files" and pass defineSeo({ files, \u2026 }).',{rule:SEO_RULES.filesUnused,file:seoFile.file}),blocks:true})}if(usesFiles||spec?.importsFiles){const vite=await first2(cwd,VITE_CONFIGS);if(vite&&!/\bzappieSeoFiles\s*\(/.test(vite.text)){found.push({problem:problem(`${vite.file} doesn't add zappieSeoFiles(), so the build can't read the icon and share image files in ${app}/`,"Add zappieSeoFiles() from @zappie/sdk/vite to the Vite plugins, before reactRouter().",{rule:SEO_RULES.plugin,file:vite.file}),blocks:true})}}const lines=report({spec:spec?.found?spec:void 0,files:new Set(files.keys()),hookFiles,jsonLd:!rendersSeo||jsonLd,pageOverrides,app});found.push(...lines.map(reportLine));return outcome2(site,found)}function reportLine(line){return{problem:problem(line,null,{rule:SEO_RULES.report}),blocks:false}}function outcome2(site,found){const checked=owned(site,found);return step("seo",checked.failed?"failed":"passed",checked.problems)}import path20 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path20.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path21 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path21.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,seo:3e4,budgets:3e4,css:6e4,unused:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"seo",run:checkSeo},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss},{name:"unused",run:checkUnused}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list3,options,settleMs=SETTLE_MS){const{all,onProgress,site:_site,...rest}=options;const site=siteFilesFor(options);const stepOptions={...rest,...site?{site}:{}};const report2=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report2({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report2({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry2=>entry2.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value2=options.timeouts?.[name];return value2!==void 0&&Number.isFinite(value2)&&value2>0?value2:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_CORNER_FILES,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,SEO_RULES,SITE_CODE_FOLDERS,SITE_ENV,analyseCss,carriesSecrets,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkSeo,checkTests,checkTypes,checkUnused,devSourceProblems,developerMayChange,evaluateAudit,findUnused,inSiteCode,isTestFile,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand,zappieManages};
|