bivium 0.1.1 → 0.1.2
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 +15 -0
- package/README.md +2 -1
- package/cli.js +2 -2
- package/index.d.ts +7 -0
- package/index.js +1 -1
- package/package.json +1 -1
- package/{shared-zwrcbvc4.js → shared-95sv6mfg.js} +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.2 — 2026-10-27
|
|
4
|
+
|
|
5
|
+
**Features**
|
|
6
|
+
|
|
7
|
+
- `hermetic` (globs) lists files whose disk reads and non-literal
|
|
8
|
+
imports reach no file of the repository, such as a library's `fs`
|
|
9
|
+
calls on its caller's paths. They no longer count as unknown; an
|
|
10
|
+
unresolved import, a non-literal glob or `goto()`, and any
|
|
11
|
+
`@depends-on` or `@reads` still do.
|
|
12
|
+
|
|
13
|
+
**Fixes**
|
|
14
|
+
|
|
15
|
+
- `bivium check` no longer counts a test that only `@reads` an
|
|
16
|
+
unknown node as running on any change, which `plan` never does.
|
|
17
|
+
|
|
3
18
|
## 0.1.1 — 2026-10-26
|
|
4
19
|
|
|
5
20
|
**Fixes**
|
package/README.md
CHANGED
|
@@ -76,6 +76,7 @@ A file it can't lex cleanly is read by a regex extractor instead, which over-app
|
|
|
76
76
|
| `edges` | Generated file glob → its inputs: `{ "dist/*.css": "styles/**" }` |
|
|
77
77
|
| `self` | The selector's own files: a change to one runs everything. The config file is always one |
|
|
78
78
|
| `importOnly` | Files only an import reaches: deleting one never orphans a suite |
|
|
79
|
+
| `hermetic` | Files whose disk reads and non-literal imports reach no file of the repository: a library's `fs` calls on its caller's paths, a test that reads only the temporary files it writes. They add no unknown |
|
|
79
80
|
| `barrels` | Modules that may bind named imports. Default: every module made only of re-exports |
|
|
80
81
|
| `external` | Packages a dependency installs that your code imports without declaring |
|
|
81
82
|
| `extensions` | Suffixes tried after a specifier |
|
|
@@ -88,7 +89,7 @@ A file it can't lex cleanly is read by a regex extractor instead, which over-app
|
|
|
88
89
|
|
|
89
90
|
| Comment | Meaning |
|
|
90
91
|
|:---|:---|
|
|
91
|
-
| `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns. Transitive. A file that reads the disk without one is unknown |
|
|
92
|
+
| `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns. Transitive. A file that reads the disk without one is unknown, unless it's `hermetic` |
|
|
92
93
|
| `// @reads <glob> [glob…]` | Files read as text. Only a direct change to one counts, not a change to what it imports |
|
|
93
94
|
| `// @glob-registry` | This file's `import.meta.glob` is a lookup table and adds no edges: whatever loads an entry names it itself |
|
|
94
95
|
|
package/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{version,globToRegExp,sorted,createResolver,SCANNED,formatOf,extract,finish,affectedBy,formatSelection,computePlan,prepare}from"./shared-
|
|
2
|
+
import{version,globToRegExp,sorted,createResolver,SCANNED,formatOf,extract,finish,affectedBy,formatSelection,computePlan,prepare}from"./shared-95sv6mfg.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";var DISK_READ=/\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/,NON_LITERAL_IMPORT=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/,GLOB_CALL=/\bimport\.meta\.glob/,QUOTED_CAUSE=/"([^"]+)"/;function lineAt(source,index){let line=1;for(let i=source.indexOf(`
|
|
3
3
|
`);i!==-1&&i<index;i=source.indexOf(`
|
|
4
4
|
`,i+1))line++;return line}function lineOf(source,needle){let index=typeof needle==="string"?source.indexOf(needle):source.search(needle);return index===-1?void 0:lineAt(source,index)}function specifierLine(source,specifier){for(let quote of['"',"'","`"]){let line=lineOf(source,`${quote}${specifier}${quote}`);if(line!==void 0)return line}return lineOf(source,specifier)}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause==="reads the disk without @depends-on")return lineOf(source,DISK_READ);if(cause.startsWith("non-literal goto("))return lineOf(source,cause.slice(12,-1));let url=QUOTED_CAUSE.exec(cause)?.[1];return url===void 0?void 0:lineOf(source,url)}function textLine(source,text){return lineOf(source,text)}function annotationLine(source,tag,glob){let index=source.split(`
|
|
5
5
|
`).findIndex((line)=>line.includes(tag)&&line.includes(glob));return index===-1?void 0:index+1}import{readFile}from"node:fs/promises";import{join}from"node:path";async function sourceOf(root,file){try{return await readFile(join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function edgeAt(root,config,computed,node,via){let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(root,file):void 0;if(source===void 0)return via.kind==="glob"&&config.generated.some(({pattern})=>pattern.test(node))?"edges in the config":void 0;let extraction=extract(formatOf(file),source),at=(line)=>line===void 0?void 0:`${file}:${line}`;if(via.kind==="reads")return at(textLine(source,"@reads"));if(via.kind==="unknown")return;if(via.kind==="glob"){if(extraction.dependsOn.some((glob)=>globToRegExp(glob).test(via.from)))return at(textLine(source,"@depends-on"));if(extraction.globs.length>0)return at(textLine(source,"import.meta.glob"));return"edges in the config"}if(node.includes("#")){let name=node.slice(node.indexOf("#")+1),specifier=extraction.barrel?.names.get(name);return specifier===void 0?void 0:at(specifierLine(source,specifier))}let resolve=createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages}),target=fileOf(via.from);for(let{specifier}of extraction.imports){let resolved=resolve(file,specifier);if(resolved&&"files"in resolved&&resolved.files.includes(target))return at(specifierLine(source,specifier))}return at(textLine(source,target.slice(target.lastIndexOf("/")+1)))}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{let line=source===void 0?void 0:causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`}})}function walks(computed,suite,from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0}];let narrowings=plan.narrowings.get(suite);if(!narrowings)return[{seeds:plan.seeds,opaque:void 0}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),opaque:void 0},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque}))]}async function explain(root,config,computed,test,from){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let chain=shortestChain(computed,walks(computed,suite.name,from),test);if(!chain)return{kind:"unselected",suite:suite.name,from};let[links,unknown]=await Promise.all([Promise.all(chain.edges.map(async([node,via])=>({node,kind:via.kind,at:await edgeAt(root,config,computed,node,via)}))),chain.edges.at(-1)?.[1].kind==="unknown"?causesOf(root,computed,chain.edges.at(-1)?.[0]??test):[]]);return{kind:"chain",suite:suite.name,test,links,root:chain.root,cause:rootCause(computed,chain.root,from),unknown}}function shortestChain(computed,candidates,test){for(let walk of candidates){let parents=new Map;if(!affectedBy(computed.graph,walk.seeds,{opaque:walk.opaque,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function formatExplanation(explanation){if(explanation.kind==="full")return[`The ${explanation.suite} suite runs in full:`,...explanation.reasons.map((reason)=>` ${reason}`)].join(`
|
|
6
6
|
`);if(explanation.kind==="unselected")return explanation.from===void 0?"Not selected: no change reaches it.":`Not selected by a change to ${explanation.from}: no chain reaches it.`;let lines=[explanation.test],indent="";for(let[i,link]of explanation.links.entries()){let next=explanation.links[i+1]?.node??explanation.root;if(link.kind==="unknown"){lines.push(`${indent}└─ depends on every change:`);for(let{cause,at}of explanation.unknown)lines.push(`${indent} ✗ ${cause}${at?` ${at}`:""}`);indent+=" ",lines.push(`${indent}└─ ${next}`),indent+=" ";break}lines.push(`${indent}└─ ${link.kind.padEnd(6)} ${next}${link.at?` ${link.at}`:""}`),indent+=" "}return lines.push(`${indent}● ${explanation.cause}`),lines.join(`
|
|
7
|
-
`)}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",glob:"import.meta.glob"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){if((QUOTED.exec(cause)?.[1]??"").startsWith("."))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";return"declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias`"}if(cause==="non-literal dynamic import")return"spell the path as a string literal,
|
|
7
|
+
`)}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",glob:"import.meta.glob"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){if((QUOTED.exec(cause)?.[1]??"").startsWith("."))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";return"declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias`"}if(cause==="non-literal dynamic import")return"spell the path as a string literal, load the files with `import.meta.glob` and literal patterns, or list the file in `hermetic` if it only imports paths its caller passes";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause==="reads the disk without @depends-on")return"name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text; list the file in `hermetic` if it reads no file of the repository";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}async function findDeadGlobs(root,config,{graph,extractions,listed}){let skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let matches=listed.filter((file)=>pattern.test(file)),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)continue;found.push({node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"})}}let nodes=[...new Set(found.map(({node})=>node))],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]]));return found.map((dead)=>{let source=sources.get(dead.node);if(source===void 0)return dead;let line=dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob);return line===void 0?dead:{...dead,at:`${dead.node}:${line}`}})}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),isTest=(node)=>config.suites.some((suite)=>suite.isTest(node)),unknown=await Promise.all(nodes.map(async(node)=>({node,causes:(await causesOf(root,computed,node)).map((cause)=>({...cause,fix:fixFor(cause.cause)})),tests:sorted([...affectedBy(computed.graph,[node],{includeUnknown:!1,readers:!1})].filter(isTest))}))),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function pushUnknown(lines,{node,causes,tests}){lines.push(node);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function formatReport(report,max){let lines=[],widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;if(lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`),idle.length>0)lines.push(`${idle.length} more no test reaches.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${dead} dead ${dead===1?"glob":"globs"} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${stale} stale \`deadGlobs\` ${stale===1?"entry":"entries"}.`);return lines.join(`
|
|
8
8
|
`).trimStart()}var USAGE=`Usage:
|
|
9
9
|
bivium plan [base] [--json] [--github] print the tests a change can affect
|
|
10
10
|
bivium run [base] [--suite <name>] run a suite's selected tests
|
package/index.d.ts
CHANGED
|
@@ -41,6 +41,13 @@ export interface Config<Suite extends string = string> {
|
|
|
41
41
|
self?: Globs;
|
|
42
42
|
/** Files only an import reaches. Deleting one never orphans a suite: an importer left pointing at it doesn't resolve, so it runs anyway. */
|
|
43
43
|
importOnly?: Globs;
|
|
44
|
+
/**
|
|
45
|
+
* Files whose disk reads and non-literal imports reach no file of the
|
|
46
|
+
* repository: a library's `fs` calls on the paths its caller passes, a
|
|
47
|
+
* test that reads only the temporary files it writes. Those add no
|
|
48
|
+
* unknown; an `@depends-on` or `@reads` still declares what one does read.
|
|
49
|
+
*/
|
|
50
|
+
hermetic?: Globs;
|
|
44
51
|
/** Modules that may bind named imports as barrels. Default: every module made only of re-exports. */
|
|
45
52
|
barrels?: Globs;
|
|
46
53
|
/** Packages to treat as external though no `package.json` declares them: ones a dependency installs. Any other undeclared bare specifier is unknown. */
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineConfig2,plan2}from"./shared-
|
|
1
|
+
import{defineConfig2,plan2}from"./shared-95sv6mfg.js";export{defineConfig2 as defineConfig,plan2 as plan};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{readFile as readFile2,stat}from"node:fs/promises";import{join as join3,posix as posix3,resolve as resolve2}from"node:path";import{existsSync}from"node:fs";import{mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var version="0.1.
|
|
2
|
-
`);await writeFile(temp,JSON.stringify([header,table.list,rows])),await rename(temp,file),this.#dirty=!1}catch{await unlink(temp).catch(()=>{return})}}}class Strings{list=[];#ids=new Map;id(value){let id=this.#ids.get(value);if(id===void 0)id=this.list.length,this.list.push(value),this.#ids.set(value,id);return id}ids(values){return values.length===0?0:values.map((value)=>this.id(value))}}function encode(key,e,table){let imports=e.imports.map(({specifier,names})=>names?[table.id(specifier),...names.map((n)=>table.id(n))]:table.id(specifier)),barrel=e.barrel&&[[...e.barrel.names].flatMap(([name,from])=>[table.id(name),table.id(from)]),table.ids(e.barrel.stars)];return[key,imports.length===0?0:imports,table.ids(e.globs),table.ids(e.gotos),table.ids(e.dependsOn),table.ids(e.reads),table.ids(e.unknown),e.fallback===void 0?0:table.id(e.fallback),barrel??0]}function decode(row,strings){let str=(id)=>{let value=typeof id==="number"?strings[id]:void 0;if(typeof value!=="string")throw Error("bad string id");return value},list=(ids)=>{if(ids===0)return[];if(!Array.isArray(ids))throw Error("bad list");return ids.map(str)},refs=row[1]===0?[]:row[1];if(!Array.isArray(refs))throw Error("bad imports");let extraction={imports:refs.map((item)=>Array.isArray(item)?{specifier:str(item[0]),names:item.slice(1).map(str)}:{specifier:str(item)}),globs:list(row[2]),gotos:list(row[3]),dependsOn:list(row[4]),reads:list(row[5]),unknown:list(row[6])};if(row[7]!==0)extraction.fallback=str(row[7]);if(row[8]!==0){if(!Array.isArray(row[8]))throw Error("bad barrel");let[pairs,stars]=row[8];if(!Array.isArray(pairs))throw Error("bad barrel names");let names=new Map;for(let i=0;i<pairs.length;i+=2)names.set(str(pairs[i]),str(pairs[i+1]));extraction.barrel={names,stars:list(stars)}}return extraction}import{existsSync as existsSync2,readFileSync}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,relative,resolve}from"node:path";import{pathToFileURL}from"node:url";var GLOB_LITERAL=/[.+^$()|[\]\\]/g;function globToRegExp(glob){let source="";for(let i=0;i<glob.length;i++){let char=glob[i];if(char==="*"&&glob[i+1]==="*"){let slash=glob[i+2]==="/";source+=slash?"(?:.*/)?":".*",i+=slash?2:1}else if(char==="*")source+="[^/]*";else if(char==="?")source+="[^/]";else if(char==="{")source+="(?:";else if(char==="}")source+=")";else if(char===",")source+="|";else source+=char.replace(GLOB_LITERAL,"\\$&")}return new RegExp(`^${source}$`)}function matcher(globs=[]){let list=typeof globs==="string"?[globs]:globs;if(list.length===0)return()=>!1;let res=list.map(globToRegExp);return(path)=>res.some((re)=>re.test(path))}function defineConfig2(config){return config}var DEFAULT_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".svelte",".vue",".json"];function list(value,fallback){if(value===void 0)return[...fallback];return typeof value==="string"?[value]:[...value]}var LEADING_DOT_SLASH=/^\.\//,TRAILING_SLASHES=/\/+$/;function normalizeRoot(root){return root.replace(LEADING_DOT_SLASH,"").replace(TRAILING_SLASHES,"")||"."}function resolveConfig(config){let names=Object.keys(config.suites);if(names.length===0)throw Error("bivium config: no suites");let suites=Object.entries(config.suites).map(([name,suite])=>({name,isTest:matcher(suite.tests),run:suite.run,roots:list(suite.root,["."]).map(normalizeRoot),urls:Object.entries(suite.urls??{}).map(([key,target])=>({key,target})),isPage:matcher(suite.pages),isWiring:matcher(suite.wiring),isNonInput:matcher(suite.nonInputs),output:suite.output??`${name}-tests`})),narrowers=(config.narrowers??[]).map((narrower)=>{let unknown=narrower.suites?.find((name)=>!names.includes(name));if(unknown!==void 0)throw Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);return{name:narrower.name,match:matcher(narrower.match),opaque:matcher(narrower.opaque),suites:[...narrower.suites??names],narrow:async(context)=>checkResult(await narrower.narrow(context))}});return{suites,narrowers,roots:list(config.roots,["."]).map(normalizeRoot),isIgnored:matcher(config.ignore),alias:Object.entries(config.alias??{}).map(([key,path])=>[key,normalizeRoot(path)]).sort(([a],[b])=>b.length-a.length),generated:Object.entries(config.edges??{}).map(([glob,inputs])=>({pattern:globToRegExp(glob),inputs:list(inputs,[]).map(globToRegExp)})),isSelf:matcher(config.self),isImportOnly:matcher(config.importOnly),isBarrel:config.barrels?matcher(config.barrels):()=>!0,external:new Set(config.external),extensions:config.extensions??DEFAULT_EXTENSIONS,deadGlobs:config.deadGlobs??[],base:config.base,cache:config.cache}}function inRoot(file,root){return root==="."||file===root||file.startsWith(`${root}/`)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStrings(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function isGlobs(value){return typeof value==="string"||isStrings(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every((item)=>typeof item==="string")}function isGlobsRecord(value){return isRecord(value)&&Object.values(value).every(isGlobs)}function isString(value){return typeof value==="string"}function isCache(value){return typeof value==="boolean"||typeof value==="string"}function field(record,key,is,path,expected){let value=record[key];if(value===void 0||is(value))return value;throw Error(`bivium config: ${path}${key} must be ${expected}`)}var SUITE_KEYS=new Set(["tests","run","root","urls","pages","wiring","nonInputs","output"]),NARROWER_KEYS=new Set(["name","match","opaque","suites","narrow"]),DEAD_GLOB_KEYS=new Set(["file","glob","reason"]),CONFIG_KEYS=new Set(["suites","narrowers","roots","ignore","alias","edges","self","importOnly","barrels","external","extensions","deadGlobs","base","cache"]);function checkKeys(record,known,path){for(let key of Object.keys(record))if(!known.has(key))throw Error(`bivium config: unknown key ${path}${key}`)}function checkSuite(name,value){if(!isRecord(value))throw Error(`bivium config: suites.${name} must be an object`);let at=`suites.${name}.`;checkKeys(value,SUITE_KEYS,at);let tests=field(value,"tests",isGlobs,at,"a glob or a list of globs");if(tests===void 0||tests.length===0)throw Error(`bivium config: suite ${name} has no tests`);let globs="a glob or a list of globs";return{tests,run:field(value,"run",isString,at,"a command"),root:field(value,"root",isGlobs,at,"a path or a list of paths"),urls:field(value,"urls",isStringRecord,at,"a map of URL patterns"),pages:field(value,"pages",isGlobs,at,globs),wiring:field(value,"wiring",isGlobs,at,globs),nonInputs:field(value,"nonInputs",isGlobs,at,globs),output:field(value,"output",isString,at,"an output name")}}function isResult(value){if(!isRecord(value))return!1;if("all"in value)return typeof value.all==="string";return"seeds"in value&&isStrings(value.seeds)&&(!("note"in value)||typeof value.note==="string")}function checkResult(value){if(isResult(value))return value;throw Error("returned neither { seeds: string[] } nor { all: string }")}function checkNarrower(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,NARROWER_KEYS,`${at}.`);let name=field(value,"name",isString,`${at}.`,"a string"),match=field(value,"match",isGlobs,`${at}.`,"globs"),opaque=field(value,"opaque",isGlobs,`${at}.`,"globs"),suites=field(value,"suites",isStrings,`${at}.`,"suite names"),{narrow}=value;if(name===void 0||match===void 0||opaque===void 0)throw Error(`bivium config: ${at} needs a name, match and opaque`);if(typeof narrow!=="function")throw Error(`bivium config: ${at}.narrow must be a function`);return{name,match,opaque,suites,narrow:async(context)=>{let result=await Reflect.apply(narrow,value,[context]);return checkResult(result)}}}function checkDeadGlob(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,DEAD_GLOB_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),glob=field(value,"glob",isString,`${at}.`,"a glob"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&glob&&reason))throw Error(`bivium config: ${at} needs a file, glob and reason`);return{file,glob,reason}}function checkConfig(value){if(!isRecord(value))throw Error("bivium config: not an object");if(!isRecord(value.suites))throw Error("bivium config: suites must be an object");checkKeys(value,CONFIG_KEYS,"");let{narrowers,deadGlobs}=value;if(narrowers!==void 0&&!Array.isArray(narrowers))throw Error("bivium config: narrowers must be a list");if(deadGlobs!==void 0&&!Array.isArray(deadGlobs))throw Error("bivium config: deadGlobs must be a list");let suites={};for(let[name,suite]of Object.entries(value.suites))suites[name]=checkSuite(name,suite);let globs="a glob or a list of globs";return{suites,narrowers:narrowers?.map((narrower,i)=>checkNarrower(narrower,`narrowers[${i}]`)),roots:field(value,"roots",isGlobs,"","a path or a list of paths"),ignore:field(value,"ignore",isGlobs,"",globs),alias:field(value,"alias",isStringRecord,"","a map of paths"),edges:field(value,"edges",isGlobsRecord,"","a map of globs"),self:field(value,"self",isGlobs,"",globs),importOnly:field(value,"importOnly",isGlobs,"",globs),barrels:field(value,"barrels",isGlobs,"",globs),external:field(value,"external",isStrings,"","a list of packages"),extensions:field(value,"extensions",isStrings,"","a list"),deadGlobs:deadGlobs?.map((entry,i)=>checkDeadGlob(entry,`deadGlobs[${i}]`)),base:field(value,"base",isString,"","a ref"),cache:field(value,"cache",isCache,"","a directory or a boolean")}}var CONFIG_FILES=["bivium.config.ts","bivium.config.mts","bivium.config.mjs","bivium.config.js","bivium.config.json"];async function readConfig(file){if(file.endsWith(".json"))return JSON.parse(readFileSync(file,"utf-8"));let module=await import(pathToFileURL(file).href);return isRecord(module)?module.default:void 0}async function loadConfig(root,path){let file=path===void 0?CONFIG_FILES.map((name)=>join2(root,name)).find((f)=>existsSync2(f)):resolve(process.cwd(),path);if(!file||!existsSync2(file))throw Error(`bivium: no config found${path?` at ${path}`:` in ${root}`}`);let inside=relative(root,file);return{config:resolveConfig(checkConfig(await readConfig(file))),file:inside.startsWith("..")||isAbsolute2(inside)?file:inside}}import{spawn}from"node:child_process";function byCodeUnit(a,b){if(a===b)return 0;return a<b?-1:1}function sorted(values){return[...values].sort(byCodeUnit)}function git(cwd,...args){return new Promise((resolve,reject)=>{let child=spawn("git",args,{cwd}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.on("error",reject),child.on("close",(status)=>{resolve({status:status??1,stdout:Buffer.concat(chunks).toString("utf-8")})})})}async function gitOrThrow(cwd,...args){let result=await git(cwd,...args);if(result.status!==0)throw Error(`git ${args.join(" ")} failed`);return result.stdout}function lines(output){return output.split(`
|
|
1
|
+
import{readFile as readFile2,stat}from"node:fs/promises";import{join as join3,posix as posix3,resolve as resolve2}from"node:path";import{existsSync}from"node:fs";import{mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var version="0.1.2";var SCANNER_VERSION=1,MAGIC="bivium-extractions",FILE="extractions.json";function isHeader(value){return typeof value==="object"&&value!==null&&"magic"in value&&value.magic===MAGIC&&"bivium"in value&&value.bivium===version&&"scanner"in value&&value.scanner===SCANNER_VERSION&&"rows"in value&&typeof value.rows==="number"&&"strings"in value&&typeof value.strings==="number"}function cacheDir(root,cache){if(cache===!1)return;if(typeof cache==="string")return isAbsolute(cache)?cache:join(root,cache);let modules=join(root,"node_modules");return existsSync(modules)?join(modules,".cache","bivium"):join(root,".bivium","cache")}class ExtractionCache{#rows=new Map;#strings=[];#used=new Map;#dirty=!1;dir;constructor(dir){this.dir=dir}static async open(dir){let cache=new ExtractionCache(dir);if(!dir)return cache;let text=await readFile(join(dir,FILE),"utf-8").catch(()=>"");if(text)cache.#load(text);return cache}#load(text){try{let parsed=JSON.parse(text);if(!Array.isArray(parsed))return;let[header,strings,rows]=parsed;if(!isHeader(header)||!Array.isArray(strings)||!Array.isArray(rows)||header.strings!==strings.length||header.rows!==rows.length)return;this.#strings=strings;for(let row of rows)if(Array.isArray(row)&&typeof row[0]==="string")this.#rows.set(row[0],row)}catch{}}get size(){return this.#rows.size}get(oid,format){let key=`${format}:${oid}`,used=this.#used.get(key);if(used)return used;let row=this.#rows.get(key);if(!row)return;let extraction;try{extraction=decode(row,this.#strings)}catch{this.#rows.delete(key);return}return this.#used.set(key,extraction),extraction}set(oid,format,extraction){let key=`${format}:${oid}`;this.#used.set(key,extraction),this.#dirty=!0}async save(){if(!this.dir||!this.#dirty)return;let table=new Strings,rows=[];for(let[key,extraction]of this.#used)rows.push(encode(key,extraction,table));let stale=Math.floor(this.#used.size/2);for(let[key,row]of this.#rows){if(stale===0)break;if(this.#used.has(key))continue;try{rows.push(encode(key,decode(row,this.#strings),table)),stale--}catch{}}let header={magic:MAGIC,bivium:version,scanner:SCANNER_VERSION,rows:rows.length,strings:table.list.length},file=join(this.dir,FILE),temp=`${file}.${process.pid}.${Date.now()}.tmp`;try{await mkdir(this.dir,{recursive:!0});let ignore=join(this.dir,".gitignore");if(!existsSync(ignore))await writeFile(ignore,`*
|
|
2
|
+
`);await writeFile(temp,JSON.stringify([header,table.list,rows])),await rename(temp,file),this.#dirty=!1}catch{await unlink(temp).catch(()=>{return})}}}class Strings{list=[];#ids=new Map;id(value){let id=this.#ids.get(value);if(id===void 0)id=this.list.length,this.list.push(value),this.#ids.set(value,id);return id}ids(values){return values.length===0?0:values.map((value)=>this.id(value))}}function encode(key,e,table){let imports=e.imports.map(({specifier,names})=>names?[table.id(specifier),...names.map((n)=>table.id(n))]:table.id(specifier)),barrel=e.barrel&&[[...e.barrel.names].flatMap(([name,from])=>[table.id(name),table.id(from)]),table.ids(e.barrel.stars)];return[key,imports.length===0?0:imports,table.ids(e.globs),table.ids(e.gotos),table.ids(e.dependsOn),table.ids(e.reads),table.ids(e.unknown),e.fallback===void 0?0:table.id(e.fallback),barrel??0]}function decode(row,strings){let str=(id)=>{let value=typeof id==="number"?strings[id]:void 0;if(typeof value!=="string")throw Error("bad string id");return value},list=(ids)=>{if(ids===0)return[];if(!Array.isArray(ids))throw Error("bad list");return ids.map(str)},refs=row[1]===0?[]:row[1];if(!Array.isArray(refs))throw Error("bad imports");let extraction={imports:refs.map((item)=>Array.isArray(item)?{specifier:str(item[0]),names:item.slice(1).map(str)}:{specifier:str(item)}),globs:list(row[2]),gotos:list(row[3]),dependsOn:list(row[4]),reads:list(row[5]),unknown:list(row[6])};if(row[7]!==0)extraction.fallback=str(row[7]);if(row[8]!==0){if(!Array.isArray(row[8]))throw Error("bad barrel");let[pairs,stars]=row[8];if(!Array.isArray(pairs))throw Error("bad barrel names");let names=new Map;for(let i=0;i<pairs.length;i+=2)names.set(str(pairs[i]),str(pairs[i+1]));extraction.barrel={names,stars:list(stars)}}return extraction}import{existsSync as existsSync2,readFileSync}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,relative,resolve}from"node:path";import{pathToFileURL}from"node:url";var GLOB_LITERAL=/[.+^$()|[\]\\]/g;function globToRegExp(glob){let source="";for(let i=0;i<glob.length;i++){let char=glob[i];if(char==="*"&&glob[i+1]==="*"){let slash=glob[i+2]==="/";source+=slash?"(?:.*/)?":".*",i+=slash?2:1}else if(char==="*")source+="[^/]*";else if(char==="?")source+="[^/]";else if(char==="{")source+="(?:";else if(char==="}")source+=")";else if(char===",")source+="|";else source+=char.replace(GLOB_LITERAL,"\\$&")}return new RegExp(`^${source}$`)}function matcher(globs=[]){let list=typeof globs==="string"?[globs]:globs;if(list.length===0)return()=>!1;let res=list.map(globToRegExp);return(path)=>res.some((re)=>re.test(path))}function defineConfig2(config){return config}var DEFAULT_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".svelte",".vue",".json"];function list(value,fallback){if(value===void 0)return[...fallback];return typeof value==="string"?[value]:[...value]}var LEADING_DOT_SLASH=/^\.\//,TRAILING_SLASHES=/\/+$/;function normalizeRoot(root){return root.replace(LEADING_DOT_SLASH,"").replace(TRAILING_SLASHES,"")||"."}function resolveConfig(config){let names=Object.keys(config.suites);if(names.length===0)throw Error("bivium config: no suites");let suites=Object.entries(config.suites).map(([name,suite])=>({name,isTest:matcher(suite.tests),run:suite.run,roots:list(suite.root,["."]).map(normalizeRoot),urls:Object.entries(suite.urls??{}).map(([key,target])=>({key,target})),isPage:matcher(suite.pages),isWiring:matcher(suite.wiring),isNonInput:matcher(suite.nonInputs),output:suite.output??`${name}-tests`})),narrowers=(config.narrowers??[]).map((narrower)=>{let unknown=narrower.suites?.find((name)=>!names.includes(name));if(unknown!==void 0)throw Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);return{name:narrower.name,match:matcher(narrower.match),opaque:matcher(narrower.opaque),suites:[...narrower.suites??names],narrow:async(context)=>checkResult(await narrower.narrow(context))}});return{suites,narrowers,roots:list(config.roots,["."]).map(normalizeRoot),isIgnored:matcher(config.ignore),alias:Object.entries(config.alias??{}).map(([key,path])=>[key,normalizeRoot(path)]).sort(([a],[b])=>b.length-a.length),generated:Object.entries(config.edges??{}).map(([glob,inputs])=>({pattern:globToRegExp(glob),inputs:list(inputs,[]).map(globToRegExp)})),isSelf:matcher(config.self),isImportOnly:matcher(config.importOnly),isHermetic:matcher(config.hermetic),isBarrel:config.barrels?matcher(config.barrels):()=>!0,external:new Set(config.external),extensions:config.extensions??DEFAULT_EXTENSIONS,deadGlobs:config.deadGlobs??[],base:config.base,cache:config.cache}}function inRoot(file,root){return root==="."||file===root||file.startsWith(`${root}/`)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStrings(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function isGlobs(value){return typeof value==="string"||isStrings(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every((item)=>typeof item==="string")}function isGlobsRecord(value){return isRecord(value)&&Object.values(value).every(isGlobs)}function isString(value){return typeof value==="string"}function isCache(value){return typeof value==="boolean"||typeof value==="string"}function field(record,key,is,path,expected){let value=record[key];if(value===void 0||is(value))return value;throw Error(`bivium config: ${path}${key} must be ${expected}`)}var SUITE_KEYS=new Set(["tests","run","root","urls","pages","wiring","nonInputs","output"]),NARROWER_KEYS=new Set(["name","match","opaque","suites","narrow"]),DEAD_GLOB_KEYS=new Set(["file","glob","reason"]),CONFIG_KEYS=new Set(["suites","narrowers","roots","ignore","alias","edges","self","importOnly","hermetic","barrels","external","extensions","deadGlobs","base","cache"]);function checkKeys(record,known,path){for(let key of Object.keys(record))if(!known.has(key))throw Error(`bivium config: unknown key ${path}${key}`)}function checkSuite(name,value){if(!isRecord(value))throw Error(`bivium config: suites.${name} must be an object`);let at=`suites.${name}.`;checkKeys(value,SUITE_KEYS,at);let tests=field(value,"tests",isGlobs,at,"a glob or a list of globs");if(tests===void 0||tests.length===0)throw Error(`bivium config: suite ${name} has no tests`);let globs="a glob or a list of globs";return{tests,run:field(value,"run",isString,at,"a command"),root:field(value,"root",isGlobs,at,"a path or a list of paths"),urls:field(value,"urls",isStringRecord,at,"a map of URL patterns"),pages:field(value,"pages",isGlobs,at,globs),wiring:field(value,"wiring",isGlobs,at,globs),nonInputs:field(value,"nonInputs",isGlobs,at,globs),output:field(value,"output",isString,at,"an output name")}}function isResult(value){if(!isRecord(value))return!1;if("all"in value)return typeof value.all==="string";return"seeds"in value&&isStrings(value.seeds)&&(!("note"in value)||typeof value.note==="string")}function checkResult(value){if(isResult(value))return value;throw Error("returned neither { seeds: string[] } nor { all: string }")}function checkNarrower(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,NARROWER_KEYS,`${at}.`);let name=field(value,"name",isString,`${at}.`,"a string"),match=field(value,"match",isGlobs,`${at}.`,"globs"),opaque=field(value,"opaque",isGlobs,`${at}.`,"globs"),suites=field(value,"suites",isStrings,`${at}.`,"suite names"),{narrow}=value;if(name===void 0||match===void 0||opaque===void 0)throw Error(`bivium config: ${at} needs a name, match and opaque`);if(typeof narrow!=="function")throw Error(`bivium config: ${at}.narrow must be a function`);return{name,match,opaque,suites,narrow:async(context)=>{let result=await Reflect.apply(narrow,value,[context]);return checkResult(result)}}}function checkDeadGlob(value,at){if(!isRecord(value))throw Error(`bivium config: ${at} must be an object`);checkKeys(value,DEAD_GLOB_KEYS,`${at}.`);let file=field(value,"file",isString,`${at}.`,"a path"),glob=field(value,"glob",isString,`${at}.`,"a glob"),reason=field(value,"reason",isString,`${at}.`,"a string");if(!(file&&glob&&reason))throw Error(`bivium config: ${at} needs a file, glob and reason`);return{file,glob,reason}}function checkConfig(value){if(!isRecord(value))throw Error("bivium config: not an object");if(!isRecord(value.suites))throw Error("bivium config: suites must be an object");checkKeys(value,CONFIG_KEYS,"");let{narrowers,deadGlobs}=value;if(narrowers!==void 0&&!Array.isArray(narrowers))throw Error("bivium config: narrowers must be a list");if(deadGlobs!==void 0&&!Array.isArray(deadGlobs))throw Error("bivium config: deadGlobs must be a list");let suites={};for(let[name,suite]of Object.entries(value.suites))suites[name]=checkSuite(name,suite);let globs="a glob or a list of globs";return{suites,narrowers:narrowers?.map((narrower,i)=>checkNarrower(narrower,`narrowers[${i}]`)),roots:field(value,"roots",isGlobs,"","a path or a list of paths"),ignore:field(value,"ignore",isGlobs,"",globs),alias:field(value,"alias",isStringRecord,"","a map of paths"),edges:field(value,"edges",isGlobsRecord,"","a map of globs"),self:field(value,"self",isGlobs,"",globs),importOnly:field(value,"importOnly",isGlobs,"",globs),hermetic:field(value,"hermetic",isGlobs,"",globs),barrels:field(value,"barrels",isGlobs,"",globs),external:field(value,"external",isStrings,"","a list of packages"),extensions:field(value,"extensions",isStrings,"","a list"),deadGlobs:deadGlobs?.map((entry,i)=>checkDeadGlob(entry,`deadGlobs[${i}]`)),base:field(value,"base",isString,"","a ref"),cache:field(value,"cache",isCache,"","a directory or a boolean")}}var CONFIG_FILES=["bivium.config.ts","bivium.config.mts","bivium.config.mjs","bivium.config.js","bivium.config.json"];async function readConfig(file){if(file.endsWith(".json"))return JSON.parse(readFileSync(file,"utf-8"));let module=await import(pathToFileURL(file).href);return isRecord(module)?module.default:void 0}async function loadConfig(root,path){let file=path===void 0?CONFIG_FILES.map((name)=>join2(root,name)).find((f)=>existsSync2(f)):resolve(process.cwd(),path);if(!file||!existsSync2(file))throw Error(`bivium: no config found${path?` at ${path}`:` in ${root}`}`);let inside=relative(root,file);return{config:resolveConfig(checkConfig(await readConfig(file))),file:inside.startsWith("..")||isAbsolute2(inside)?file:inside}}import{spawn}from"node:child_process";function byCodeUnit(a,b){if(a===b)return 0;return a<b?-1:1}function sorted(values){return[...values].sort(byCodeUnit)}function git(cwd,...args){return new Promise((resolve,reject)=>{let child=spawn("git",args,{cwd}),chunks=[];child.stdout.on("data",(chunk)=>chunks.push(chunk)),child.on("error",reject),child.on("close",(status)=>{resolve({status:status??1,stdout:Buffer.concat(chunks).toString("utf-8")})})})}async function gitOrThrow(cwd,...args){let result=await git(cwd,...args);if(result.status!==0)throw Error(`git ${args.join(" ")} failed`);return result.stdout}function lines(output){return output.split(`
|
|
3
3
|
`).filter(Boolean)}var INDEX_ENTRY=/^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;async function readRevision(cwd,base,roots,{blobs=!1}={}){let diffArgs=["--name-only","--no-renames","--merge-base",base],[listing,mergeBase,diff,staged]=await Promise.all([gitOrThrow(cwd,"ls-files","-s","-v","-o","--exclude-standard"),gitOrThrow(cwd,"merge-base",base,"HEAD").then((out)=>out.trim()),gitOrThrow(cwd,"diff",...diffArgs),blobs?gitOrThrow(cwd,"diff","--cached",...diffArgs):""]),entries=lines(listing),untracked=[];for(let line of entries)if(line.startsWith("? "))untracked.push(line.slice(2));let changed=[...new Set([...lines(diff),...untracked])],dirty=new Set([...changed,...lines(staged)]),underRoots=(path)=>roots.some((root)=>inRoot(path,root)),files=new Set,tracked=new Set,present=new Set,oids=new Map;for(let line of entries){let entry=INDEX_ENTRY.exec(line);if(!entry){if(line.startsWith("? ")&&underRoots(line.slice(2)))files.add(line.slice(2));continue}let[,tag,mode,oid,stage,path]=entry;if(tracked.add(path),mode==="160000"||!underRoots(path))continue;if(files.add(path),dirty.has(path)||stage!=="0"||tag!=="H")continue;if(mode!=="100644"&&mode!=="100755")continue;if(present.add(path),blobs)oids.set(path,oid)}return{files:sorted(files),listed:[...tracked,...untracked],changed,mergeBase,blobs:oids,present}}async function showAt(cwd,ref,path){let result=await git(cwd,"show",`${ref}:${path}`);return result.status===0?result.stdout:void 0}async function defaultBase(cwd){let head=await git(cwd,"symbolic-ref","--short","refs/remotes/origin/HEAD");if(head.status===0&&head.stdout.trim())return head.stdout.trim();let refs=["origin/main","origin/master","main","master"],found=await Promise.all(refs.map((ref)=>git(cwd,"rev-parse","--verify","--quiet",ref))),branch=refs.find((_,i)=>found[i].status===0);if(branch)return branch;throw Error("bivium: no base given and no default branch found")}var COMMENTS=/\/\/.*$|\/\*[\s\S]*?\*\//gm,AS=/\s+as\s+/,TYPE_PREFIX=/^type\s+/,NAMED_EXPORT=/export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g,STAR_EXPORT=/export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g,BARREL_FILE=/\.[cm]?[jt]sx?$/,ONLY_SEPARATORS=/^[\s;]*$/,STARTS_WITH_EXPORT=/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;function parseBarrel(path,source){return BARREL_FILE.test(path)?parseReExports(source):void 0}function parseReExports(source){if(!STARTS_WITH_EXPORT.test(source))return;let code=source.replace(COMMENTS,""),barrel={names:new Map,stars:[]},rest=code.replace(NAMED_EXPORT,(_,list,from)=>{for(let part of list.split(",")){let name=part.trim().replace(TYPE_PREFIX,"").split(AS).pop();if(name)barrel.names.set(name,from)}return""});if(rest=rest.replace(STAR_EXPORT,(_,name,from)=>{if(name)barrel.names.set(name,from);else barrel.stars.push(from);return""}),barrel.names.size+barrel.stars.length===0)return;return ONLY_SEPARATORS.test(rest)?barrel:void 0}import{builtinModules}from"node:module";import{posix}from"node:path";var QUERY=/[?#].*$/,URL_REF=/^[a-z]+:|^\/\//,LIST_SEPARATOR=/[\s,]+(?![^{]*\})/,DEPENDS_ON=/^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm,READS=/^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm,GLOB_REGISTRY=/^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m,AS2=/\s+as\s+/,TYPE_PREFIX2=/^type\s+/,NAMED_CLAUSE=/\{([^}]*)\}/,DEFAULT_OR_NAMESPACE=/^\s*[\w$*]/;function namedBindings(clause){let named=NAMED_CLAUSE.exec(clause);if(!named||DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE,"")))return;return named[1].split(",").map((part)=>part.trim().replace(TYPE_PREFIX2,"").split(AS2)[0].trim()).filter(Boolean)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isStringRecord2(value){return isRecord2(value)&&Object.values(value).every((item)=>typeof item==="string")}function toPackageJson(value){if(!isRecord2(value))return{};let json={};if(typeof value.name==="string")json.name=value.name;if(value.exports!==void 0)json.exports=value.exports;if(typeof value.main==="string")json.main=value.main;let{sideEffects}=value;if(typeof sideEffects==="boolean"||Array.isArray(sideEffects)&&sideEffects.every((glob)=>typeof glob==="string"))json.sideEffects=sideEffects;for(let field of DEP_FIELDS){let deps=value[field];if(isStringRecord2(deps))json[field]=deps}return json}var BUILTINS=new Set(builtinModules),RUNTIME_BUILTIN=/^(?:node:|bun(?:$|:))/,JS_EXTENSION=/\.([cm]?)js(x?)$/,NODE_PREFIX=/^node:/,DEP_FIELDS=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function packageName(specifier){let parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function builtin(specifier){if(RUNTIME_BUILTIN.test(specifier)){let name=specifier.replace(NODE_PREFIX,"");return specifier.startsWith("bun")?specifier:`node:${name.split("/")[0]}`}let name=specifier.split("/")[0];return BUILTINS.has(specifier)||BUILTINS.has(name)?`node:${name}`:void 0}function targets(value,out=[]){if(typeof value==="string")out.push(value);else if(Array.isArray(value))for(let item of value)targets(item,out);else if(value&&typeof value==="object")for(let item of Object.values(value))targets(item,out);return out}function subpathMap(exports){if(typeof exports==="string"||Array.isArray(exports))return{".":exports};if(!isRecord2(exports))return;return Object.keys(exports).some((key)=>key.startsWith("."))?exports:{".":exports}}function exportTargets(exports,subpath){let map=subpathMap(exports);if(!map)return;if(subpath in map&&!subpath.includes("*"))return targets(map[subpath]);let best;for(let key of Object.keys(map)){let star=key.indexOf("*");if(star===-1)continue;let prefix=key.slice(0,star),suffix=key.slice(star+1);if(subpath.length>=key.length-1&&subpath.startsWith(prefix)&&subpath.endsWith(suffix)&&(!best||prefix.length>best.key.indexOf("*")||prefix.length===best.key.indexOf("*")&&key.length>best.key.length))best={key,match:subpath.slice(prefix.length,subpath.length-suffix.length)}}if(!best)return;let{match}=best;return targets(map[best.key]).map((target)=>target.replaceAll("*",match))}function byDepth(packages){return[...packages].sort(([a],[b])=>b.length-a.length)}function owner(packages,file){return byDepth(packages).find(([dir])=>dir==="."||file.startsWith(`${dir}/`))}function aliased(target,rest){if(target===".")return rest||".";return rest?`${target}/${rest}`:target}function createResolver({files,config,packages}){let generated=(path)=>config.generated.some(({pattern})=>pattern.test(path)),{extensions}=config,exists=(path)=>files.has(path),suffixed=new Map;for(let file of files)for(let i=0;i<extensions.length;i++){let ext=extensions[i];if(!file.endsWith(ext))continue;let base=file.slice(0,file.length-ext.length),list=suffixed.get(base);if(list)list.push([i,file]);else suffixed.set(base,[[i,file]])}for(let list of suffixed.values())if(list.length>1)list.sort(([a],[b])=>a-b);let deepestFirst=byDepth(packages),local=new Map;for(let[dir,json]of deepestFirst)if(json.name&&!local.has(json.name))local.set(json.name,dir);let declared=new Map,declaredFor=(from)=>{let dir=owner(packages,from)?.[0]??".",names=declared.get(dir);if(!names){names=new Set;for(let[pkgDir,json]of deepestFirst){if(pkgDir!=="."&&dir!==pkgDir&&!dir.startsWith(`${pkgDir}/`))continue;for(let field of DEP_FIELDS)for(let name of Object.keys(json[field]??{}))names.add(name)}declared.set(dir,names)}return names},probe=(base)=>{if(generated(base))return[base];let found=[];if(exists(base))found.push(base);for(let[,file]of suffixed.get(base)??[])found.push(file);let js=found.length===0&&JS_EXTENSION.exec(base);if(js){let ts=`${base.slice(0,js.index)}.${js[1]}ts${js[2]}`;if(exists(ts))found.push(ts)}for(let[,file]of suffixed.get(`${base}/index`)??[])found.push(file);return found},inPackage=(dir,path)=>dir==="."?path:posix.join(dir,path),resolveLocal=(dir,json,subpath)=>{if(json.exports!==void 0)return(exportTargets(json.exports,subpath)??[]).map((target)=>inPackage(dir,posix.normalize(target))).filter((path)=>generated(path)||exists(path));if(subpath===".")return probe(inPackage(dir,posix.normalize(json.main??"index")));return probe(inPackage(dir,subpath.slice(2)))},resolve=(from,fromDir,specifier)=>{let bare=specifier.replace(QUERY,"");if(bare==="")return;if(bare.startsWith(".")){let found=probe(posix.join(fromDir,bare));return found.length>0?{files:found}:void 0}for(let[key,target]of config.alias){if(bare!==key&&!bare.startsWith(`${key}/`))continue;let found=probe(aliased(target,bare.slice(key.length+1)));if(found.length>0)return{files:found}}let name=packageName(bare),dir=local.get(name);if(dir!==void 0){let subpath=`.${bare.slice(name.length)}`,found=resolveLocal(dir,packages.get(dir)??{},subpath);return found.length>0?{files:found}:void 0}let node=builtin(bare);if(node)return{pkg:node};if(declaredFor(from).has(name)||config.external.has(name))return{pkg:name};return},cache=new Map,lastFrom,lastDir="",inDir=new Map;return(from,specifier)=>{if(from!==lastFrom)lastFrom=from,lastDir=posix.dirname(from),inDir=cache.get(lastDir)??new Map,cache.set(lastDir,inDir);if(inDir.has(specifier))return inDir.get(specifier);let resolved=resolve(from,lastDir,specifier);return inDir.set(specifier,resolved),resolved}}import{posix as posix2}from"node:path";function createLexed(){return{imports:[],globs:[],gotos:[],dependsOn:[],reads:[],registry:!1,nonLiteralImport:!1,nonLiteralGlob:!1,readsDisk:!1}}class LexError extends Error{}var TS={jsx:!1,tsx:!1},JS={jsx:!0,tsx:!1},TSX={jsx:!0,tsx:!0},JS_FILE=/\.[cm]?jsx?$/;function dialectOf(path){if(path.endsWith(".tsx"))return TSX;if(JS_FILE.test(path))return JS;return TS}var T_START=0,T_PUNCT=1,T_OPERAND=2,T_IDENT=3,T_DOT=4,T_CLOSE_PAREN=5,T_CLOSE_KW=6,T_CLOSE_BLOCK=7,T_ARROW=8,T_SEMI=9,T_LBRACE=10,M_PAREN=0,M_PAREN_KW=1,M_BRACKET=2,M_BLOCK=3,M_EXPR=4,M_TEMPLATE=5,DISK=new Set(["fs","node:fs","fs/promises","node:fs/promises","child_process","node:child_process"]),VI_CALLS=new Set(["mock","doMock","unmock","importActual","importMock"]),CALL_IMPORT=0,CALL_PROPERTY=1,CALL_MOCK=2,CALL_ACTUAL=3,src="",end=0,out=createLexed(),dialect=TS,nextAt=-1,nextImport=-1,LS=String.fromCharCode(8232),PS=String.fromCharCode(8233),oddLines=!1,templateOpen=!1;function fail(message,at){throw new LexError(`${message} at ${at}`)}function openFile(source,sink){src=source,out=sink,nextAt=-1,nextImport=-1,oddLines=source.includes("\r")||source.includes(LS)||source.includes(PS)}function lexRange(start,stop,language=TS){dialect=language,end=stop;let i=start;if(src.charCodeAt(i)===65279)i++;if(src.charCodeAt(i)===35&&src.charCodeAt(i+1)===33)i=lineEnd(i);code(i,!1)}function lexExpression(start,stop){return dialect=TS,end=stop,code(start,!0)}function isUnicodeSpace(c){return c===160||c===65279||c===5760||c>=8192&&c<=8202||c===8232||c===8233||c===8239||c===8287||c===12288}var IDENT=new Uint8Array(128);for(let c=0;c<128;c++)if(c>=97&&c<=122||c>=65&&c<=90||c===36||c===95)IDENT[c]=3;else if(c>=48&&c<=57)IDENT[c]=2;function isIdentStart(c){return c<128?(IDENT[c]&1)!==0:c>=128&&!isUnicodeSpace(c)}function isIdentPart(c){return c<128?IDENT[c]!==0:c>=128&&!isUnicodeSpace(c)}function identEnd(start){let i=start,s=src,n=end;while(i<n){let c=s.charCodeAt(i);if(c<128?IDENT[c]===0:isUnicodeSpace(c))break;i++}return i}function isWord(i,word){return i+word.length<=end&&src.startsWith(word,i)&&!isIdentPart(src.charCodeAt(i+word.length))}function lineEnd(start){let i=start;if(oddLines){while(i<end){let c=src.charCodeAt(i);if(c===10||c===13||c===8232||c===8233)return i;i++}return end}let e=src.indexOf(`
|
|
4
4
|
`,i);return e===-1||e>end?end:e}function skipTrivia(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(c===32||c>=9&&c<=13||c>=128&&isUnicodeSpace(c))i++;else if(c===47&&src.charCodeAt(i+1)===47)i=lineEnd(i+2);else if(c===47&&src.charCodeAt(i+1)===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)return end;i=e+2}else break}return i}function stringEnd(i){let quote=src.charCodeAt(i),j=i+1;while(j<end){let c=src.charCodeAt(j);if(c===quote)return j+1;if(c===92){j+=src.charCodeAt(j+1)===13&&src.charCodeAt(j+2)===10?3:2;continue}if(c===10||c===13)return-1;j++}return-1}function template(start){let j=start;while(j<end){let c=src.charCodeAt(j);if(c===96)return templateOpen=!1,j+1;if(c===92){j+=2;continue}if(c===36&&src.charCodeAt(j+1)===123)return templateOpen=!0,j+2;j++}return fail("unterminated template",j)}function regex(i){let j=i+1,inClass=!1;for(;;){if(j>=end)fail("unterminated regex",i);let c=src.charCodeAt(j);if(c===92){j+=2;continue}if(c===10||c===13)fail("unterminated regex",i);if(inClass){if(c===93)inClass=!1}else if(c===47)break;else if(c===91)inClass=!0;j++}return identEnd(j+1)}function isOneOf(start,stop,words){if(stop-start!==words[0].length)return!1;let c=src.charCodeAt(start);for(let word of words)if(word.charCodeAt(0)===c&&src.startsWith(word,start))return!0;return!1}var EXPRESSION_KEYWORDS=[],PAREN_KEYWORDS=[],BLOCK_KEYWORDS=[];function byLength(table,words){for(let word of words)table[word.length]=[...table[word.length]??[],word]}byLength(EXPRESSION_KEYWORDS,["in","do","new","case","else","void","throw","yield","await","return","typeof","delete","default","instanceof"]);byLength(PAREN_KEYWORDS,["if","for","with","while"]);byLength(BLOCK_KEYWORDS,["do","try","else","finally"]);function isKeyword(table,start,stop){let words=table[stop-start];return words!==void 0&&isOneOf(start,stop,words)}function isExpressionKeyword(start,stop){return isKeyword(EXPRESSION_KEYWORDS,start,stop)}function isParenKeyword(start,stop){return isKeyword(PAREN_KEYWORDS,start,stop)}function isBlockKeyword(start,stop){return isKeyword(BLOCK_KEYWORDS,start,stop)}function isWordAt(start,stop,word){return stop-start===word.length&&src.startsWith(word,start)}function code(start,brace){let i=start,s=src,n=end,stack=[],last=T_START,wordStart=0,wordEnd=0,wordIsProperty=!1;while(i<n){let c=s.charCodeAt(i);if(c<128?(IDENT[c]&1)!==0:!isUnicodeSpace(c)){let j=i+1;while(j<n){let d=s.charCodeAt(j);if(d<128?IDENT[d]===0:isUnicodeSpace(d))break;j++}let property=last===T_DOT;switch(j-i){case 2:if(c===118&&src.charCodeAt(i+1)===105)vi(j);break;case 3:if(c===66&&src.startsWith("Bun",i))bun(j);break;case 4:if(c===103&&property&&src.startsWith("goto",i))goto(j);break;case 6:if(!property){if(c===105&&src.startsWith("import",i))importAt(j);else if(c===101&&src.startsWith("export",i))exportAt(j)}break;case 7:if(c===114&&src.startsWith("require",i))requireAt(j,property);break}last=T_IDENT,wordStart=i,wordEnd=j,wordIsProperty=property,i=j;continue}switch(c){case 32:case 9:case 10:case 11:case 12:case 13:i++;continue;case 47:{let next=src.charCodeAt(i+1);if(next===47){let e=lineEnd(i+2);comment(i,e,!1),i=e}else if(next===42){let e=src.indexOf("*/",i+2);if(e===-1||e+2>end)fail("unterminated comment",i);comment(i,e+2,!0),i=e+2}else if(last===T_OPERAND||last===T_CLOSE_PAREN||last===T_IDENT&&(wordIsProperty||!isExpressionKeyword(wordStart,wordEnd)))i++,last=T_PUNCT;else i=regex(i),last=T_OPERAND;continue}case 39:case 34:{let e=stringEnd(i);if(e===-1)fail("unterminated string",i);i=e,last=T_OPERAND;continue}case 96:if(i=template(i+1),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue;case 123:{let block=last===T_START||last===T_SEMI||last===T_LBRACE||last===T_CLOSE_PAREN||last===T_CLOSE_KW||last===T_CLOSE_BLOCK||last===T_ARROW||last===T_IDENT&&!wordIsProperty&&isBlockKeyword(wordStart,wordEnd);stack.push(block?M_BLOCK:M_EXPR),last=T_LBRACE,i++;continue}case 125:{if(stack.length===0){if(brace)return i+1;fail("unbalanced }",i)}let open=stack.pop();if(open===M_TEMPLATE){if(i=template(i+1),templateOpen)stack.push(M_TEMPLATE),last=T_PUNCT;else last=T_OPERAND;continue}if(open===M_BLOCK)last=T_CLOSE_BLOCK;else if(open===M_EXPR)last=T_OPERAND;else fail("unbalanced }",i);i++;continue}case 40:stack.push(last===T_IDENT&&!wordIsProperty&&isParenKeyword(wordStart,wordEnd)?M_PAREN_KW:M_PAREN),last=T_PUNCT,i++;continue;case 41:{let open=stack.pop();if(open===M_PAREN)last=T_CLOSE_PAREN;else if(open===M_PAREN_KW)last=T_CLOSE_KW;else fail("unbalanced )",i);i++;continue}case 91:stack.push(M_BRACKET),last=T_PUNCT,i++;continue;case 93:if(stack.pop()!==M_BRACKET)fail("unbalanced ]",i);last=T_OPERAND,i++;continue;case 59:last=T_SEMI,i++;continue;case 46:if(src.charCodeAt(i+1)===46&&src.charCodeAt(i+2)===46)last=T_PUNCT,i+=3;else if(isDigit(src.charCodeAt(i+1)))i=numberEnd(i+1),last=T_OPERAND;else last=T_DOT,i++;continue;case 61:if(src.charCodeAt(i+1)===62)last=T_ARROW,i+=2;else last=T_PUNCT,i++;continue;case 43:case 45:if(src.charCodeAt(i+1)===c)last=last===T_OPERAND||last===T_IDENT||last===T_CLOSE_PAREN?T_OPERAND:T_PUNCT,i+=2;else last=T_PUNCT,i++;continue;case 33:last=(last===T_OPERAND||last===T_IDENT&&(wordIsProperty||!isExpressionKeyword(wordStart,wordEnd))||last===T_CLOSE_PAREN)&&src.charCodeAt(i+1)!==61?T_OPERAND:T_PUNCT,i++;continue;case 60:if(src.charCodeAt(i+1)===60||src.charCodeAt(i+1)===61)last=T_PUNCT,i+=2;else if(dialect.jsx&&!(last===T_OPERAND||last===T_CLOSE_PAREN||last===T_IDENT&&(wordIsProperty||!isExpressionKeyword(wordStart,wordEnd)))&&isJsxStart(i))i=jsxElement(i),last=T_OPERAND;else last=T_PUNCT,i++;continue;case 35:if(isIdentStart(src.charCodeAt(i+1)))i=identEnd(i+1),last=T_OPERAND;else last=T_PUNCT,i++;continue;default:if(isDigit(c)){i=numberEnd(i+1),last=T_OPERAND;continue}if(c<128)last=T_PUNCT;i++;continue}}if(brace)fail("unterminated expression",i);if(stack.length>0)fail(stack[stack.length-1]===M_TEMPLATE?"unterminated template":"unbalanced brackets",i);return i}function isDigit(c){return c>=48&&c<=57}function numberEnd(start){let i=start;while(i<end){let c=src.charCodeAt(i);if(isIdentPart(c)||c===46)i++;else break}return i}function comment(start,stop,block){if(nextAt<start)nextAt=indexOrEnd("@",start);while(nextAt<stop){if(src.startsWith("@depends-on",nextAt)||src.startsWith("@reads",nextAt)||src.startsWith("@glob-registry",nextAt)){annotations(start,stop),nextAt=indexOrEnd("@",stop);break}nextAt=indexOrEnd("@",nextAt+1)}if(block&&src.charCodeAt(start+2)===42){if(nextImport<start)nextImport=indexOrEnd("import",start);while(nextImport<stop)jsdocImport(start,nextImport,stop),nextImport=indexOrEnd("import",nextImport+6)}}function indexOrEnd(text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}var BLANK=/^[ \t]*$/;function annotations(start,stop){let lineStart=src.lastIndexOf(`
|
|
5
5
|
`,start-1)+1,prefix=src.slice(lineStart,start),text=(BLANK.test(prefix)?prefix:"x")+src.slice(start,stop);for(let[,list]of text.matchAll(DEPENDS_ON))out.dependsOn.push(...list.split(LIST_SEPARATOR).filter(Boolean));for(let[,list]of text.matchAll(READS))out.reads.push(...list.split(LIST_SEPARATOR).filter(Boolean));if(GLOB_REGISTRY.test(text))out.registry=!0}var JSDOC_IMPORT_TYPE=/import\s*\(\s*(["'`])([^"'`\n]+)\1\s*\)/y,JSDOC_IMPORT_TAG=/@import\s+([^;"'`]*?)\s*from\s*(["'])([^"'\n]+)\2/y,JSDOC_LINE_STAR=/\n\s*\*/g;function inTagType(start,at){let depth=0,outer=-1;for(let i=start;i<at;i++){let c=src.charCodeAt(i);if(c===123){if(depth++===0)outer=i}else if(c===125&&depth>0)depth--}if(depth===0)return!1;let p=outer-1;while(p>start&&isSpace(src.charCodeAt(p)))p--;while(p>start&&isIdentPart(src.charCodeAt(p)))p--;return src.charCodeAt(p)===64&&p+1<outer}function jsdocImport(start,at,stop){if(src.charCodeAt(at-1)===64){JSDOC_IMPORT_TAG.lastIndex=at-1;let tag=JSDOC_IMPORT_TAG.exec(src);if(tag&&JSDOC_IMPORT_TAG.lastIndex<=stop){let clause=tag[1].replace(JSDOC_LINE_STAR,`
|
|
6
|
-
`),names=clause.includes("{")?namedBindings(clause):void 0;out.imports.push(names?{specifier:tag[3],names}:{specifier:tag[3]})}return}if(isIdentPart(src.charCodeAt(at-1))||src.charCodeAt(at-1)===46)return;if(!inTagType(start,at))return;JSDOC_IMPORT_TYPE.lastIndex=at;let type=JSDOC_IMPORT_TYPE.exec(src);if(type&&JSDOC_IMPORT_TYPE.lastIndex<=stop)out.imports.push({specifier:type[2]})}function record(specifier,names,disk){if(specifier==="")return;if(out.imports.push(names?{specifier,names}:{specifier}),disk&&DISK.has(specifier))out.readsDisk=!0}function isSpace(c){return c===32||c>=9&&c<=13}function isQuote(c){return c===39||c===34}function importAt(j){let k=skipTrivia(j),c=src.charCodeAt(k);if(c===40)call(k,CALL_IMPORT);else if(c===46)meta(k);else if(isQuote(c)){let e=stringEnd(k);if(e!==-1)record(src.slice(k+1,e-1),void 0,!0)}else declaration(k)}function declaration(k){let clauseStart=k;if(src.startsWith("type",k)&&isSpace(src.charCodeAt(k+4))){clauseStart=k+5;while(clauseStart<end&&isSpace(src.charCodeAt(clauseStart)))clauseStart++}let p=k;for(let steps=0;steps<256;steps++){if(p=skipTrivia(p),p>=end)return;let c=src.charCodeAt(p);if(isIdentStart(c)){let q=identEnd(p+1);if(q-p===4&&src.startsWith("from",p)){let r=skipTrivia(q);if(isQuote(src.charCodeAt(r))){let e=stringEnd(r);if(e!==-1)record(src.slice(r+1,e-1),clauseNames(clauseStart,p),!0);return}}p=q}else if(c===123){if(p=braceEnd(p),p===-1)return}else if(c===42||c===44)p++;else return}}function clauseNames(start,stop){let clause=src.slice(start,stop);if(!clause.includes("{"))return;return namedBindings(clause.replace(COMMENTS2,""))}var COMMENTS2=/\/\/.*$|\/\*[\s\S]*?\*\//gm;function braceEnd(open){let p=open,depth=0;while(p<end){let c=src.charCodeAt(p);if(c===123)depth++,p++;else if(c===125){if(p++,--depth===0)return p}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1}else if(c===47&&src.charCodeAt(p+1)===47)p=lineEnd(p+2);else if(c===47&&src.charCodeAt(p+1)===42){let e=src.indexOf("*/",p+2);if(e===-1)return-1;p=e+2}else if(c===59||c===40||c===96)return-1;else p++}return-1}function exportAt(j){let p=skipTrivia(j);if(isWord(p,"type")){let q=skipTrivia(p+4),c=src.charCodeAt(q);if(c===123||c===42)p=q}let clauseStart=p,c=src.charCodeAt(p),q;if(c===123){if(q=braceEnd(p),q===-1)return}else if(c===42){if(q=skipTrivia(p+1),isWord(q,"as")){q=skipTrivia(q+2);let n=src.charCodeAt(q);if(isQuote(n))q=stringEnd(q);else if(isIdentStart(n))q=identEnd(q+1);else return;if(q===-1)return}}else return;if(q=skipTrivia(q),!isWord(q,"from"))return;let r=skipTrivia(q+4);if(!isQuote(src.charCodeAt(r)))return;let e=stringEnd(r);if(e===-1)return;record(src.slice(r+1,e-1),clauseNames(clauseStart,q),!0)}function call(k,kind){let a=skipTrivia(k+1),c=src.charCodeAt(a);if(c===41)return;let e;if(isQuote(c))e=stringEnd(a);else if(c===96){if(e=template(a+1),templateOpen)e=-1}else e=-1;let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)record(src.slice(a+1,e-1),void 0,kind===CALL_IMPORT||kind===CALL_PROPERTY||kind===CALL_ACTUAL);else if(kind!==CALL_PROPERTY&&!isSignature(k,a))out.nonLiteralImport=!0}function isSignature(k,a){if(isIdentStart(src.charCodeAt(a))){let p=skipTrivia(identEnd(a+1)),c=src.charCodeAt(p);if(c===58||c===63&&src.charCodeAt(skipTrivia(p+1))===58)return!0}let close=parenEnd(k);return close!==-1&&src.charCodeAt(skipTrivia(close))===123}function parenEnd(k){let depth=0,p=k;while(p<end){let c=src.charCodeAt(p);if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125){if(--depth===0)return p+1}else if(isQuote(c)||c===96){if(p=c===96?templateEnd(p):stringEnd(p),p===-1)return-1;continue}else if(c===47&&(src.charCodeAt(p+1)===47||src.charCodeAt(p+1)===42)){p=skipTrivia(p);continue}p++}return-1}function requireAt(j,property){let k=skipTrivia(j);if(src.charCodeAt(k)===40)call(k,property?CALL_PROPERTY:CALL_IMPORT)}function vi(j){let p=skipTrivia(j);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q),name=src.slice(q,r);if(!VI_CALLS.has(name))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralImport=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)call(s,name==="importActual"?CALL_ACTUAL:CALL_MOCK)}function meta(k){let m=skipTrivia(k+1);if(!isWord(m,"meta"))return;let p=skipTrivia(m+4);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q);if(!isWordAt(q,r,"glob")&&!isWordAt(q,r,"globEager"))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralGlob=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)globArgument(s)}function genericEnd(start){let p=start,depth=0;while(p<end&&p-start<4096){let c=src.charCodeAt(p);if(c===60)depth++;else if(c===62&&src.charCodeAt(p-1)!==61){if(--depth===0)return p+1}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1;continue}else if(c===96){if(p=template(p+1),templateOpen)return-1;continue}else if(c===59&&depth===0)return-1;p++}return-1}function literalEnd(a){let c=src.charCodeAt(a);if(isQuote(c))return stringEnd(a);if(c===96){let e=template(a+1);return templateOpen?-1:e}return-1}function globArgument(k){let a=skipTrivia(k+1),patterns=[],e;if(src.charCodeAt(a)===91){a=skipTrivia(a+1);for(;;){if(src.charCodeAt(a)===93){e=a+1;break}let f=literalEnd(a);if(f===-1){e=-1;break}patterns.push(src.slice(a+1,f-1)),a=skipTrivia(f);let c=src.charCodeAt(a);if(c===44)a=skipTrivia(a+1);else if(c!==93){e=-1;break}}}else if(e=literalEnd(a),e!==-1)patterns.push(src.slice(a+1,e-1));let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)out.globs.push(...patterns);else out.nonLiteralGlob=!0}function goto(j){let k=skipTrivia(j);if(src.charCodeAt(k)!==40)return;let a=skipTrivia(k+1),p=a,depth=0;while(p<end){let c=src.charCodeAt(p);if((c===44||c===41)&&depth===0)break;if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125)depth--;else if(isQuote(c)||c===96){let e=c===96?templateEnd(p):stringEnd(p);if(e===-1)return;p=e;continue}p++}out.gotos.push(src.slice(a,p).trim())}function templateEnd(p){let q=template(p+1);while(templateOpen){let depth=1;while(q<end&&depth>0){let c=src.charCodeAt(q);if(c===123)depth++;else if(c===125)depth--;else if(isQuote(c)){if(q=stringEnd(q),q===-1)return-1;continue}else if(c===96){if(q=templateEnd(q),q===-1)return-1;continue}q++}if(depth>0)return-1;q=template(q)}return q}function bun(j){if(src.charCodeAt(j)!==46)return;if(src.startsWith("file",j+1)||src.startsWith("Glob",j+1)||src.startsWith("spawn",j+1))out.readsDisk=!0}function isJsxStart(i){let c=src.charCodeAt(i+1);if(c===62)return!0;if(!isIdentStart(c))return!1;if(!dialect.tsx)return!0;let p=skipTrivia(identEnd(i+2));return src.charCodeAt(p)!==44&&!isWord(p,"extends")}function jsxNameEnd(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(isIdentPart(c)||c===45||c===46||c===58)p++;else break}return p}function jsxElement(i){let p=i+1;if(src.charCodeAt(p)===62)return jsxChildren(p+1);p=jsxNameEnd(p);for(;;){if(p=skipTrivia(p),p>=end)fail("unterminated JSX",i);let c=src.charCodeAt(p);if(c===47&&src.charCodeAt(p+1)===62)return p+2;if(c===62)return jsxChildren(p+1);if(c===123){p=code(p+1,!0);continue}if(!isIdentStart(c))fail(`bad JSX attribute in <> at ${i}:`,p);if(p=skipTrivia(jsxNameEnd(p)),src.charCodeAt(p)!==61)continue;p=skipTrivia(p+1);let v=src.charCodeAt(p);if(isQuote(v)){let e=src.indexOf(src[p],p+1);if(e===-1||e>=end)fail("unterminated JSX attribute",p);p=e+1}else if(v===123)p=code(p+1,!0);else if(v===60)p=jsxElement(p);else fail("bad JSX attribute",p)}}function jsxChildren(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(c===60){if(src.charCodeAt(p+1)===47){let e=src.indexOf(">",p);if(e===-1||e>=end)break;return e+1}p=jsxElement(p)}else if(c===123)p=code(p+1,!0);else p++}return fail("unterminated JSX",p)}function hostOf(path){let dot=path.lastIndexOf("."),ext=path.slice(dot+1);return ext==="svelte"||ext==="vue"||ext==="astro"||ext==="html"?ext:void 0}var TAG_REF=/^<(?:script|link|iframe)\b[^>]*\b(?:src|href)=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+))/,GENERICS=/\sgenerics=(["'])/,LANG_JSX=/\slang=["']?(?:jsx|tsx)\b/,LOWERCASE=/[a-z]/,FENCE_OPEN=/^\s*---[ \t]*\r?\n/,FENCE_CLOSE=/^---[ \t]*$/m;function isTag(src,i,name){for(let k=0;k<name.length;k++)if((src.charCodeAt(i+1+k)|32)!==name.charCodeAt(k))return!1;let c=src.charCodeAt(i+1+name.length);return c===62||c===47||c===32||c>=9&&c<=13}function tagEnd(src,i){let j=i+1;while(j<src.length){let c=src.charCodeAt(j);if(c===62)return j+1;if(c===34||c===39){let e=src.indexOf(src[j],j+1);if(e===-1)break;j=e+1}else j++}throw new LexError(`unterminated tag at ${i}`)}function closeTag(src,from,name){let lower=src.indexOf(`</${name}`,from);if(lower!==-1)return lower;let any=src.slice(from).search(new RegExp(`</${name}`,"i"));if(any===-1)throw new LexError(`unterminated <${name}> at ${from}`);return from+any}function indexOrEnd2(src,text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}function lexHost(src,out,host){let n=src.length,i=0;if(host==="astro")i=frontmatter(src);let nextTag=-1,nextBrace=host==="svelte"?-1:n;while(i<n){if(nextTag<i)nextTag=indexOrEnd2(src,"<",i);if(nextBrace<i)nextBrace=indexOrEnd2(src,"{",i);if(i=Math.min(nextTag,nextBrace),i>=n)break;if(src.charCodeAt(i)===123){let j=i+1,sigil=src.charCodeAt(j);if(sigil===35||sigil===58||sigil===64||sigil===47&&LOWERCASE.test(src[j+1]??""))j++;i=lexExpression(j,n);continue}if(src.startsWith("<!--",i)){let e=src.indexOf("-->",i+4);if(e===-1)throw new LexError(`unterminated comment at ${i}`);i=e+3}else if(isTag(src,i,"script")){let open=tagEnd(src,i),tag=src.slice(i,open);if(host==="html"||host==="vue")ref(tag,out);let generics=tag.match(GENERICS);if(generics?.index!==void 0){let start=i+generics.index+generics[0].length,stop=src.indexOf(generics[1],start);if(stop!==-1&&stop<open)lexRange(start,stop,TS)}let close=closeTag(src,open,"script"),dialect=LANG_JSX.test(tag)?TSX:TS;lexRange(open,close,dialect),i=close+8}else if(isTag(src,i,"style"))i=closeTag(src,tagEnd(src,i),"style")+7;else if(host==="html"&&(isTag(src,i,"link")||isTag(src,i,"iframe"))){let open=tagEnd(src,i);ref(src.slice(i,open),out),i=open}else i++}}function ref(tag,out){let match=TAG_REF.exec(tag),value=match&&(match[1]??match[2]??match[3]);if(value&&!URL_REF.test(value))out.imports.push({specifier:value.startsWith(".")?value:`./${value}`})}function frontmatter(src){let start=FENCE_OPEN.exec(src);if(!start)return 0;let from=start[0].length,close=src.slice(from).search(FENCE_CLOSE);if(close===-1)throw new LexError("unterminated frontmatter");return lexRange(from,from+close,TS),from+close+3}var COMMENTS3=/\/\/.*$|\/\*[\s\S]*?\*\//gm,QUOTED=/["']([^"']+)["']/g,STATIC_IMPORT=/(?:^|[\n;>])\s*(?:import|export)\s+(?:type\s+)?([^;"'`]*?)\s*from\s*["']([^"'\n]+)["']/g,SIDE_EFFECT_IMPORT=/(?:^|[\n;>])\s*import\s*["']([^"'\n]+)["']/g,CALL_WITH_LITERAL=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*(["'`])([^"'`$\n]+)\1\s*[,)]/g,NON_LITERAL_CALL=/(?<![.\w])(?:import|require)\(\s*(?!["'`])[^)\s]/,TEMPLATE_CALL=/(?<![.\w])(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*`[^`]*\$\{/,GLOB_CALL=/\bimport\.meta\.glob(?:<(?:[^<>]|<[^<>]*>)*>)?\(\s*(\[[^\]]*\]|["'][^"']*["'])/g,GLOB_CALL_ANY=/\bimport\.meta\.glob[<(]/g,GOTO=/\.goto\(\s*([^,)]*)/g,HTML_REF=/<(?:script|link|iframe)\b[^>]*\b(?:src|href)=["']([^"']+)["']/g,READS_DISK=/\b(?:from|import|require|importActual)\s*\(?\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;function extractRegex(source,html){let result={imports:[],globs:[],gotos:[],dependsOn:[],reads:[],unknown:[]};if(html){for(let[,ref]of source.matchAll(HTML_REF))if(!URL_REF.test(ref))result.imports.push({specifier:ref.startsWith(".")?ref:`./${ref}`})}for(let[,clause,specifier]of source.matchAll(STATIC_IMPORT)){let names=namedBindings(clause.replace(COMMENTS3,""));result.imports.push(names?{specifier,names}:{specifier})}for(let[,specifier]of source.matchAll(SIDE_EFFECT_IMPORT))result.imports.push({specifier});let calls=source.includes("import(")||source.includes("require(")||source.includes("vi.");for(let[,,specifier]of calls?source.matchAll(CALL_WITH_LITERAL):[])result.imports.push({specifier});if(calls&&(NON_LITERAL_CALL.test(source)||TEMPLATE_CALL.test(source)))result.unknown.push("non-literal dynamic import");let globbing=source.includes("import.meta.glob"),globs=globbing?[...source.matchAll(GLOB_CALL)]:[];if(globbing&&globs.length!==[...source.matchAll(GLOB_CALL_ANY)].length)result.unknown.push("non-literal glob import");for(let[,argument]of GLOB_REGISTRY.test(source)?[]:globs)for(let[,glob]of argument.matchAll(QUOTED)){if(glob.startsWith("!"))continue;result.globs.push(glob.replace(QUERY,""))}if(source.includes(".goto("))for(let[,argument]of source.matchAll(GOTO))result.gotos.push(argument.trim());if(result.dependsOn=[...source.includes("@depends-on")?source.matchAll(DEPENDS_ON):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.reads=[...source.includes("@reads")?source.matchAll(READS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),(source.includes("fs")||source.includes("child_process")||source.includes("Bun."))&&READS_DISK.test(source)&&result.dependsOn.length+result.reads.length===0)result.unknown.push("reads the disk without @depends-on");return result}var SCANNED=/\.(?:svelte|vue|astro|html|[cm]?[jt]sx?)$/;function formatOf(path){let host=hostOf(path);if(host)return host;let dialect=dialectOf(path);if(dialect===TSX)return"tsx";return dialect===JS?"js":"ts"}function extract(format,source){let lexed=createLexed(),extraction;try{if(openFile(source,lexed),isHost(format))lexHost(source,lexed,format);else lexRange(0,source.length,DIALECTS[format]);extraction=fromLexed(lexed)}catch(error){let fallback=error instanceof LexError?error.message:`lexer error: ${error}`;extraction={...extractRegex(source,format==="html"),fallback}}if(!isHost(format)){let barrel=parseReExports(source);if(barrel)extraction.barrel=barrel}return extraction}function finish(path,extraction,{gotos=!1}={}){let{globs}=extraction,dir=globs.length>0?posix2.dirname(path):"",result={imports:extraction.imports,globs:globs.map((glob)=>posix2.join(dir,glob)),gotos:gotos?extraction.gotos:[],dependsOn:extraction.dependsOn,reads:extraction.reads,unknown:extraction.unknown};if(extraction.fallback!==void 0)result.fallback=extraction.fallback;return result}var DIALECTS={ts:TS,tsx:TSX,js:JS},isHost=(format)=>format!=="ts"&&format!=="tsx"&&format!=="js";function fromLexed(lexed){let unknown=[];if(lexed.nonLiteralImport)unknown.push("non-literal dynamic import");if(lexed.nonLiteralGlob)unknown.push("non-literal glob import");let globs=[];for(let glob of lexed.registry?[]:lexed.globs){if(glob.startsWith("!"))continue;globs.push(glob.replace(QUERY,""))}if(lexed.readsDisk&&lexed.dependsOn.length+lexed.reads.length===0)unknown.push("reads the disk without @depends-on");return{imports:lexed.imports,globs,gotos:lexed.gotos,dependsOn:lexed.dependsOn,reads:lexed.reads,unknown}}var STRING_LITERAL=/^["'`]([^"'`$]*)["'`]$/,STATIC_PATH_TEMPLATE=/^`([^`$?#]*)[?#][^`]*`$/;function gotoUrl(argument){return STRING_LITERAL.exec(argument)?.[1]??STATIC_PATH_TEMPLATE.exec(argument)?.[1]}var leaf=()=>({files:new Set,patterns:[],reads:[],unknown:[]}),LEADING_DOT_SLASH2=/^\.\//;function sideEffectful(owning){let sideEffects=owning?.[1].sideEffects;if(sideEffects===!1)return()=>!1;if(!Array.isArray(sideEffects))return()=>!0;let dir=owning?.[0]??".";return matcher(sideEffects.map((glob)=>{if(!glob.includes("/"))return`**/${glob}`;let path=glob.replace(LEADING_DOT_SLASH2,"");return dir==="."?path:`${dir}/${path}`}))}function gotoSuite(config,path){return config.suites.find((suite)=>suite.urls.length>0&&suite.roots.some((root)=>inRoot(path,root)))}function mapUrl(suite,url){for(let{key,target}of suite.urls){let star=key.indexOf("*");if(star===-1){if(url===key)return target;continue}let prefix=key.slice(0,star),suffix=key.slice(star+1);if(url.startsWith(prefix)&&url.endsWith(suffix)){let match=url.slice(prefix.length,url.length-suffix.length);return target.replaceAll("*",match)}}return}function graphFrom(files,extractions,{config,packages}){let graph=new Map,paths=[...files],exists=new Set(paths),resolve=createResolver({files:exists,config,packages}),scans=new Map,barrels=new Map;for(let path of paths){let extraction=extractions.get(path);if(!extraction)continue;let gotos=gotoSuite(config,path)!==void 0;if(scans.set(path,finish(path,extraction,{gotos})),extraction.barrel&&config.isBarrel(path))barrels.set(path,extraction.barrel)}let named=new Map,effects=new Map,nameUnknown=new Map;for(let[path,barrel]of barrels){let effectful=sideEffectful(owner(packages,path));if(effectful(path))continue;let resolveTarget=(specifier)=>{let resolved=resolve(path,specifier);return resolved&&"files"in resolved?resolved.files:void 0},always=[];for(let specifier of[...barrel.names.values(),...barrel.stars])for(let file of resolveTarget(specifier)??[])if(effectful(file)&&!always.includes(file))always.push(file);let names=new Map;for(let[name,specifier]of barrel.names){let targets=resolveTarget(specifier);if(!targets)nameUnknown.set(`${path}#${name}`,[`unresolved "${specifier}"`]);names.set(name,targets??[])}named.set(path,names),effects.set(path,always)}let external=new Set;for(let path of paths){let found=scans.get(path);if(!found){graph.set(path,leaf());continue}let deps=leaf();for(let{specifier,names}of found.imports){let resolved=resolve(path,specifier);if(resolved===void 0)deps.unknown.push(`unresolved "${specifier}"`);else if("pkg"in resolved)deps.files.add(`pkg:${resolved.pkg}`),external.add(`pkg:${resolved.pkg}`);else for(let file of resolved.files){let barrel=names&&named.get(file);if(!barrel||!names){deps.files.add(file);continue}for(let name of names)deps.files.add(barrel.has(name)?`${file}#${name}`:file)}}deps.unknown.push(...found.unknown);for(let glob of found.globs)deps.patterns.push(globToRegExp(glob));let suite=found.gotos.length>0?gotoSuite(config,path):void 0;if(suite)for(let argument of found.gotos){let url=gotoUrl(argument);if(url===void 0)deps.unknown.push(`non-literal goto(${argument})`);else if(url!=="about:blank"){let page=mapUrl(suite,url.replace(QUERY,""));if(page===void 0)deps.unknown.push(`goto("${url}")`);else if(exists.has(page))deps.files.add(page);else deps.unknown.push(`missing fixture "${url}"`)}}for(let glob of found.dependsOn)deps.patterns.push(globToRegExp(glob));for(let glob of found.reads)deps.reads.push(globToRegExp(glob));let names=named.get(path);if(names)deps.barrel=names;graph.set(path,deps)}for(let[path,names]of named)for(let[name,targets]of names){let id=`${path}#${name}`;graph.set(id,{...leaf(),files:new Set([...targets,...effects.get(path)??[]]),unknown:nameUnknown.get(id)??[]})}for(let id of external)graph.set(id,leaf());for(let deps of[...graph.values()])for(let file of deps.files)if(!graph.has(file)&&isGenerated(config,file))graph.set(file,leaf());for(let[path,deps]of graph)for(let{pattern,inputs}of config.generated)if(pattern.test(path))deps.patterns.push(...inputs);return graph}function isGenerated(config,path){return config.generated.some(({pattern})=>pattern.test(path))}function changedBarrelNames(before,after){let names=new Set([...before.keys(),...after.keys()]),key=(files)=>files?.join("\x00");return[...names].filter((name)=>key(before.get(name))!==key(after.get(name)))}function baseBarrelNames(path,source,{config,packages},graph){let barrel=source===void 0?void 0:parseBarrel(path,source);if(!barrel)return;let resolve=createResolver({files:new Set(graph.keys()),config,packages}),names=new Map;for(let[name,specifier]of barrel.names){let resolved=resolve(path,specifier);names.set(name,resolved&&"files"in resolved?resolved.files:[])}return names}var indexes=new WeakMap;function reverseIndex(graph){let cached=indexes.get(graph);if(cached)return cached;let index={dependents:new Map,globbers:[],readers:[],unknown:[]};for(let[path,deps]of graph){for(let file of deps.files){let list=index.dependents.get(file);list?list.push(path):index.dependents.set(file,[path])}if(deps.patterns.length>0)index.globbers.push([path,deps.patterns]);if(deps.reads.length>0)index.readers.push([path,deps.reads]);if(deps.unknown.length>0)index.unknown.push(path)}return indexes.set(graph,index),index}function importersOf(graph,node){return reverseIndex(graph).dependents.get(node)??[]}function affectedBy(graph,changed,{includeUnknown=!0,opaque,parents}={}){let{dependents,globbers,readers,unknown}=reverseIndex(graph),affected=new Set,queue=[],visit=(path,via)=>{if(affected.has(path)||opaque?.(path))return;if(affected.add(path),queue.push(path),via&&parents)parents.set(path,via)},changedPaths=[...changed];for(let path of changedPaths)visit(path);for(let[reader,patterns]of readers){let read=changedPaths.find((path)=>patterns.some((re)=>re.test(path)));if(read!==void 0)visit(reader,{from:read,kind:"reads"})}let first=queue[0];if(includeUnknown&&first!==void 0)for(let path of unknown)visit(path,{from:first,kind:"unknown"});for(let at=0;at<queue.length;at++){let path=queue[at];for(let dependent of dependents.get(path)??[])visit(dependent,{from:path,kind:"import"});for(let[globber,patterns]of globbers)if(!affected.has(globber)&&patterns.some((re)=>re.test(path)))visit(globber,{from:path,kind:"glob"})}return affected}function formatSelection(selection){return selection.mode==="some"?selection.files.join(" "):selection.mode}function select(affected,tests){let files=tests.filter((file)=>affected.has(file));if(files.length===0)return{mode:"none"};if(files.length===tests.length)return{mode:"all"};return{mode:"some",files}}function classify(graph,changed,config){let reasons=[],full=new Set,runAll=()=>{for(let suite of config.suites)full.add(suite.name)},relevant=[];for(let file of changed){let read=graph.has(file);if(!read&&config.isIgnored(file))continue;let wired=config.suites.filter((suite)=>suite.isWiring(file));if(config.isSelf(file))reasons.push(`${file}: test selector changed`),runAll();else if(wired.length>0)for(let suite of wired)reasons.push(`${file}: wires the ${suite.name} suite`),full.add(suite.name);else if(read||config.roots.some((root)=>inRoot(file,root)))relevant.push(file);else reasons.push(`${file}: outside the dependency graph`),runAll()}return{relevant,reasons,full}}function narrowedWalk(graph,seeds,coarse,narrowings){let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched)),fine=affectedBy(graph,seeds.filter((seed)=>!matched.has(seed)));for(let narrowing of narrowings){let walk=affectedBy(graph,[...narrowing.matched,...narrowing.seeds],{opaque:narrowing.narrower.opaque});for(let node of walk)fine.add(node)}return new Set([...fine].filter((node)=>coarse.has(node)))}function planTests(graph,changed,config,{barrelNames=[],narrowed=[]}={}){let{relevant,reasons,full}=classify(graph,changed,config),seeds=[...relevant,...barrelNames],affected=affectedBy(graph,seeds),nodes=[...graph.keys()],tests=new Map(config.suites.map((suite)=>[suite.name,nodes.filter(suite.isTest)]));for(let suite of config.suites){let suiteTests=tests.get(suite.name)??[];for(let file of relevant){if(!suite.roots.some((root)=>inRoot(file,root)))continue;let reach=affectedBy(graph,[file],{includeUnknown:!1});if(suiteTests.some((test)=>reach.has(test)))continue;let deleted=!graph.has(file);if(deleted&&suite.isTest(file))continue;if(deleted&&config.isImportOnly(file))continue;if(suite.isNonInput(file))continue;if([...reach].some(suite.isPage))continue;reasons.push(`${file}: no ${suite.name} test imports it`),full.add(suite.name)}}let narrowings=new Map;for(let{narrower,result}of narrowed){let matched=relevant.filter(narrower.match);if(matched.length===0)continue;if("all"in result){reasons.push(`${narrower.name}: ${result.all}`);for(let name of narrower.suites)full.add(name);continue}for(let name of narrower.suites){let list=narrowings.get(name)??[];list.push({matched,narrower,seeds:result.seeds}),narrowings.set(name,list)}}let suites={};for(let suite of config.suites)suites[suite.name]=full.has(suite.name)?{mode:"all"}:select(narrowings.has(suite.name)?narrowedWalk(graph,seeds,affected,narrowings.get(suite.name)??[]):affected,tests.get(suite.name)??[]);return{suites,reasons,full:[...full],seeds,narrowings}}function hasCode(error,codes){return error instanceof Error&&"code"in error&&typeof error.code==="string"&&codes.includes(error.code)}async function readIfFile(path){try{return await readFile2(path,"utf-8")}catch(error){if(hasCode(error,["ENOENT","EISDIR"]))return;throw error}}function collectPackages(rootJson,sources){let packages=new Map,parse=(text)=>{try{return toPackageJson(JSON.parse(text))}catch{return{}}};if(rootJson!==void 0)packages.set(".",parse(rootJson));for(let[path,text]of sources){if(path==="package.json"||!path.endsWith("/package.json"))continue;packages.set(posix3.dirname(path),parse(text))}return packages}async function isFile(path){try{return(await stat(path)).isFile()}catch(error){if(hasCode(error,["ENOENT","ENOTDIR"]))return!1;throw error}}async function extractRevision(root,revision,cache){let extractions=new Map,texts=new Map,missing=new Set,pending=[],cached=0,read=async(file)=>{let text=await readIfFile(join3(root,file));if(text===void 0)missing.add(file);return text};for(let file of revision.files)if(SCANNED.test(file)){let format=formatOf(file),oid=revision.blobs.get(file),hit=oid===void 0?void 0:cache.get(oid,format);if(hit){extractions.set(file,hit),cached++;continue}pending.push(read(file).then((source)=>{if(source===void 0)return;let extraction=extract(format,source);if(extractions.set(file,extraction),oid!==void 0)cache.set(oid,format,extraction)}))}else if(file.endsWith("/package.json"))pending.push(read(file).then((source)=>{if(source!==void 0)texts.set(file,source)}));else if(!revision.present.has(file))pending.push(isFile(join3(root,file)).then((found)=>{if(!found)missing.add(file)}));await Promise.all(pending);let files=revision.files.filter((file)=>!missing.has(file)),manifests=new Map;for(let file of files){let text=texts.get(file);if(text!==void 0)manifests.set(file,text)}return{files,extractions,manifests,extracted:{cached,read:extractions.size-cached}}}function graphView(graph,config){let nodes=[...graph.keys()];return{nodes:()=>nodes,importers:(node)=>importersOf(graph,node),dependents:(from)=>affectedBy(graph,from,{includeUnknown:!1}),tests:(name)=>{let suite=config.suites.find((candidate)=>candidate.name===name);if(!suite)throw Error(`bivium: no suite "${name}"`);return nodes.filter(suite.isTest)}}}function messageOf(error){return error instanceof Error?error.message:String(error)}async function runNarrowers(root,revision,graph,config,suites){let{relevant}=classify(graph,revision.changed,config),wanted=config.narrowers.filter((narrower)=>relevant.some(narrower.match)&&(suites===void 0||narrower.suites.some((name)=>suites.includes(name))));if(wanted.length===0)return[];let view=graphView(graph,config),base={commit:revision.mergeBase,read:(path)=>showAt(root,revision.mergeBase,path)},head={commit:void 0,read:(path)=>readIfFile(join3(root,path))};return Promise.all(wanted.map(async(narrower)=>{let changed=relevant.filter(narrower.match);try{let result=await narrower.narrow({root,base,head,changed,graph:view});return{narrower,result}}catch(error){return{narrower,result:{all:`failed: ${messageOf(error)}`}}}}))}async function computePlan(root,base,config,{cache:cacheOption=config.cache,suites}={}){let dir=cacheDir(root,cacheOption),[revision,rootJson,cache]=await Promise.all([readRevision(root,base,config.roots,{blobs:dir!==void 0}),readFile2(join3(root,"package.json"),"utf-8").catch(()=>{return}),ExtractionCache.open(dir)]),{files,extractions,manifests,extracted}=await extractRevision(root,revision,cache),basePending=new Map(revision.changed.filter((file)=>config.isBarrel(file)&&extractions.get(file)?.barrel).map((file)=>[file,showAt(root,revision.mergeBase,file)])),packages=collectPackages(rootJson,manifests),graph=graphFrom(files,extractions,{config,packages}),saved=cache.save(),barrelNames=(await Promise.all([...basePending].map(async([file,pending])=>{let head=graph.get(file)?.barrel;if(!head)return[];let before=baseBarrelNames(file,await pending,{config,packages},graph);return(before?changedBarrelNames(before,head):[...head.keys()]).map((name)=>`${file}#${name}`)}))).flat(),narrowed=await runNarrowers(root,revision,graph,config,suites),planned=planTests(graph,revision.changed,config,{barrelNames,narrowed});return await saved,{plan:planned,graph,changed:revision.changed,mergeBase:revision.mergeBase,barrelNames,narrowed,packages,extractions,listed:revision.listed,fallbacks:new Map([...extractions].flatMap(([file,extraction])=>extraction.fallback===void 0?[]:[[file,extraction.fallback]])),extracted}}async function prepare({cwd=process.cwd(),base,config,configFile}){let root=resolve2(cwd),resolved;if(config)resolved=resolveConfig(checkConfig(config));else{let loaded=await loadConfig(root,configFile),isSelf=loaded.config.isSelf;resolved={...loaded.config,isSelf:(path)=>path===loaded.file||isSelf(path)}}return{root,base:base??resolved.base??await defaultBase(root),config:resolved}}async function plan2(options={}){let{root,base,config}=await prepare(options),computed=await computePlan(root,base,config,{...options.cache!==void 0&&{cache:options.cache}});return{suites:computed.plan.suites,reasons:computed.plan.reasons,base,mergeBase:computed.mergeBase,changed:computed.changed,narrowed:computed.narrowed.map(({narrower,result})=>({name:narrower.name,result}))}}
|
|
6
|
+
`),names=clause.includes("{")?namedBindings(clause):void 0;out.imports.push(names?{specifier:tag[3],names}:{specifier:tag[3]})}return}if(isIdentPart(src.charCodeAt(at-1))||src.charCodeAt(at-1)===46)return;if(!inTagType(start,at))return;JSDOC_IMPORT_TYPE.lastIndex=at;let type=JSDOC_IMPORT_TYPE.exec(src);if(type&&JSDOC_IMPORT_TYPE.lastIndex<=stop)out.imports.push({specifier:type[2]})}function record(specifier,names,disk){if(specifier==="")return;if(out.imports.push(names?{specifier,names}:{specifier}),disk&&DISK.has(specifier))out.readsDisk=!0}function isSpace(c){return c===32||c>=9&&c<=13}function isQuote(c){return c===39||c===34}function importAt(j){let k=skipTrivia(j),c=src.charCodeAt(k);if(c===40)call(k,CALL_IMPORT);else if(c===46)meta(k);else if(isQuote(c)){let e=stringEnd(k);if(e!==-1)record(src.slice(k+1,e-1),void 0,!0)}else declaration(k)}function declaration(k){let clauseStart=k;if(src.startsWith("type",k)&&isSpace(src.charCodeAt(k+4))){clauseStart=k+5;while(clauseStart<end&&isSpace(src.charCodeAt(clauseStart)))clauseStart++}let p=k;for(let steps=0;steps<256;steps++){if(p=skipTrivia(p),p>=end)return;let c=src.charCodeAt(p);if(isIdentStart(c)){let q=identEnd(p+1);if(q-p===4&&src.startsWith("from",p)){let r=skipTrivia(q);if(isQuote(src.charCodeAt(r))){let e=stringEnd(r);if(e!==-1)record(src.slice(r+1,e-1),clauseNames(clauseStart,p),!0);return}}p=q}else if(c===123){if(p=braceEnd(p),p===-1)return}else if(c===42||c===44)p++;else return}}function clauseNames(start,stop){let clause=src.slice(start,stop);if(!clause.includes("{"))return;return namedBindings(clause.replace(COMMENTS2,""))}var COMMENTS2=/\/\/.*$|\/\*[\s\S]*?\*\//gm;function braceEnd(open){let p=open,depth=0;while(p<end){let c=src.charCodeAt(p);if(c===123)depth++,p++;else if(c===125){if(p++,--depth===0)return p}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1}else if(c===47&&src.charCodeAt(p+1)===47)p=lineEnd(p+2);else if(c===47&&src.charCodeAt(p+1)===42){let e=src.indexOf("*/",p+2);if(e===-1)return-1;p=e+2}else if(c===59||c===40||c===96)return-1;else p++}return-1}function exportAt(j){let p=skipTrivia(j);if(isWord(p,"type")){let q=skipTrivia(p+4),c=src.charCodeAt(q);if(c===123||c===42)p=q}let clauseStart=p,c=src.charCodeAt(p),q;if(c===123){if(q=braceEnd(p),q===-1)return}else if(c===42){if(q=skipTrivia(p+1),isWord(q,"as")){q=skipTrivia(q+2);let n=src.charCodeAt(q);if(isQuote(n))q=stringEnd(q);else if(isIdentStart(n))q=identEnd(q+1);else return;if(q===-1)return}}else return;if(q=skipTrivia(q),!isWord(q,"from"))return;let r=skipTrivia(q+4);if(!isQuote(src.charCodeAt(r)))return;let e=stringEnd(r);if(e===-1)return;record(src.slice(r+1,e-1),clauseNames(clauseStart,q),!0)}function call(k,kind){let a=skipTrivia(k+1),c=src.charCodeAt(a);if(c===41)return;let e;if(isQuote(c))e=stringEnd(a);else if(c===96){if(e=template(a+1),templateOpen)e=-1}else e=-1;let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)record(src.slice(a+1,e-1),void 0,kind===CALL_IMPORT||kind===CALL_PROPERTY||kind===CALL_ACTUAL);else if(kind!==CALL_PROPERTY&&!isSignature(k,a))out.nonLiteralImport=!0}function isSignature(k,a){if(isIdentStart(src.charCodeAt(a))){let p=skipTrivia(identEnd(a+1)),c=src.charCodeAt(p);if(c===58||c===63&&src.charCodeAt(skipTrivia(p+1))===58)return!0}let close=parenEnd(k);return close!==-1&&src.charCodeAt(skipTrivia(close))===123}function parenEnd(k){let depth=0,p=k;while(p<end){let c=src.charCodeAt(p);if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125){if(--depth===0)return p+1}else if(isQuote(c)||c===96){if(p=c===96?templateEnd(p):stringEnd(p),p===-1)return-1;continue}else if(c===47&&(src.charCodeAt(p+1)===47||src.charCodeAt(p+1)===42)){p=skipTrivia(p);continue}p++}return-1}function requireAt(j,property){let k=skipTrivia(j);if(src.charCodeAt(k)===40)call(k,property?CALL_PROPERTY:CALL_IMPORT)}function vi(j){let p=skipTrivia(j);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q),name=src.slice(q,r);if(!VI_CALLS.has(name))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralImport=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)call(s,name==="importActual"?CALL_ACTUAL:CALL_MOCK)}function meta(k){let m=skipTrivia(k+1);if(!isWord(m,"meta"))return;let p=skipTrivia(m+4);if(src.charCodeAt(p)!==46)return;let q=skipTrivia(p+1),r=identEnd(q);if(!isWordAt(q,r,"glob")&&!isWordAt(q,r,"globEager"))return;let s=skipTrivia(r);if(src.charCodeAt(s)===60){if(s=genericEnd(s),s===-1){out.nonLiteralGlob=!0;return}s=skipTrivia(s)}if(src.charCodeAt(s)===40)globArgument(s)}function genericEnd(start){let p=start,depth=0;while(p<end&&p-start<4096){let c=src.charCodeAt(p);if(c===60)depth++;else if(c===62&&src.charCodeAt(p-1)!==61){if(--depth===0)return p+1}else if(isQuote(c)){if(p=stringEnd(p),p===-1)return-1;continue}else if(c===96){if(p=template(p+1),templateOpen)return-1;continue}else if(c===59&&depth===0)return-1;p++}return-1}function literalEnd(a){let c=src.charCodeAt(a);if(isQuote(c))return stringEnd(a);if(c===96){let e=template(a+1);return templateOpen?-1:e}return-1}function globArgument(k){let a=skipTrivia(k+1),patterns=[],e;if(src.charCodeAt(a)===91){a=skipTrivia(a+1);for(;;){if(src.charCodeAt(a)===93){e=a+1;break}let f=literalEnd(a);if(f===-1){e=-1;break}patterns.push(src.slice(a+1,f-1)),a=skipTrivia(f);let c=src.charCodeAt(a);if(c===44)a=skipTrivia(a+1);else if(c!==93){e=-1;break}}}else if(e=literalEnd(a),e!==-1)patterns.push(src.slice(a+1,e-1));let next=e===-1?-1:src.charCodeAt(skipTrivia(e));if(next===44||next===41)out.globs.push(...patterns);else out.nonLiteralGlob=!0}function goto(j){let k=skipTrivia(j);if(src.charCodeAt(k)!==40)return;let a=skipTrivia(k+1),p=a,depth=0;while(p<end){let c=src.charCodeAt(p);if((c===44||c===41)&&depth===0)break;if(c===40||c===91||c===123)depth++;else if(c===41||c===93||c===125)depth--;else if(isQuote(c)||c===96){let e=c===96?templateEnd(p):stringEnd(p);if(e===-1)return;p=e;continue}p++}out.gotos.push(src.slice(a,p).trim())}function templateEnd(p){let q=template(p+1);while(templateOpen){let depth=1;while(q<end&&depth>0){let c=src.charCodeAt(q);if(c===123)depth++;else if(c===125)depth--;else if(isQuote(c)){if(q=stringEnd(q),q===-1)return-1;continue}else if(c===96){if(q=templateEnd(q),q===-1)return-1;continue}q++}if(depth>0)return-1;q=template(q)}return q}function bun(j){if(src.charCodeAt(j)!==46)return;if(src.startsWith("file",j+1)||src.startsWith("Glob",j+1)||src.startsWith("spawn",j+1))out.readsDisk=!0}function isJsxStart(i){let c=src.charCodeAt(i+1);if(c===62)return!0;if(!isIdentStart(c))return!1;if(!dialect.tsx)return!0;let p=skipTrivia(identEnd(i+2));return src.charCodeAt(p)!==44&&!isWord(p,"extends")}function jsxNameEnd(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(isIdentPart(c)||c===45||c===46||c===58)p++;else break}return p}function jsxElement(i){let p=i+1;if(src.charCodeAt(p)===62)return jsxChildren(p+1);p=jsxNameEnd(p);for(;;){if(p=skipTrivia(p),p>=end)fail("unterminated JSX",i);let c=src.charCodeAt(p);if(c===47&&src.charCodeAt(p+1)===62)return p+2;if(c===62)return jsxChildren(p+1);if(c===123){p=code(p+1,!0);continue}if(!isIdentStart(c))fail(`bad JSX attribute in <> at ${i}:`,p);if(p=skipTrivia(jsxNameEnd(p)),src.charCodeAt(p)!==61)continue;p=skipTrivia(p+1);let v=src.charCodeAt(p);if(isQuote(v)){let e=src.indexOf(src[p],p+1);if(e===-1||e>=end)fail("unterminated JSX attribute",p);p=e+1}else if(v===123)p=code(p+1,!0);else if(v===60)p=jsxElement(p);else fail("bad JSX attribute",p)}}function jsxChildren(start){let p=start;while(p<end){let c=src.charCodeAt(p);if(c===60){if(src.charCodeAt(p+1)===47){let e=src.indexOf(">",p);if(e===-1||e>=end)break;return e+1}p=jsxElement(p)}else if(c===123)p=code(p+1,!0);else p++}return fail("unterminated JSX",p)}function hostOf(path){let dot=path.lastIndexOf("."),ext=path.slice(dot+1);return ext==="svelte"||ext==="vue"||ext==="astro"||ext==="html"?ext:void 0}var TAG_REF=/^<(?:script|link|iframe)\b[^>]*\b(?:src|href)=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+))/,GENERICS=/\sgenerics=(["'])/,LANG_JSX=/\slang=["']?(?:jsx|tsx)\b/,LOWERCASE=/[a-z]/,FENCE_OPEN=/^\s*---[ \t]*\r?\n/,FENCE_CLOSE=/^---[ \t]*$/m;function isTag(src,i,name){for(let k=0;k<name.length;k++)if((src.charCodeAt(i+1+k)|32)!==name.charCodeAt(k))return!1;let c=src.charCodeAt(i+1+name.length);return c===62||c===47||c===32||c>=9&&c<=13}function tagEnd(src,i){let j=i+1;while(j<src.length){let c=src.charCodeAt(j);if(c===62)return j+1;if(c===34||c===39){let e=src.indexOf(src[j],j+1);if(e===-1)break;j=e+1}else j++}throw new LexError(`unterminated tag at ${i}`)}function closeTag(src,from,name){let lower=src.indexOf(`</${name}`,from);if(lower!==-1)return lower;let any=src.slice(from).search(new RegExp(`</${name}`,"i"));if(any===-1)throw new LexError(`unterminated <${name}> at ${from}`);return from+any}function indexOrEnd2(src,text,from){let at=src.indexOf(text,from);return at===-1?src.length:at}function lexHost(src,out,host){let n=src.length,i=0;if(host==="astro")i=frontmatter(src);let nextTag=-1,nextBrace=host==="svelte"?-1:n;while(i<n){if(nextTag<i)nextTag=indexOrEnd2(src,"<",i);if(nextBrace<i)nextBrace=indexOrEnd2(src,"{",i);if(i=Math.min(nextTag,nextBrace),i>=n)break;if(src.charCodeAt(i)===123){let j=i+1,sigil=src.charCodeAt(j);if(sigil===35||sigil===58||sigil===64||sigil===47&&LOWERCASE.test(src[j+1]??""))j++;i=lexExpression(j,n);continue}if(src.startsWith("<!--",i)){let e=src.indexOf("-->",i+4);if(e===-1)throw new LexError(`unterminated comment at ${i}`);i=e+3}else if(isTag(src,i,"script")){let open=tagEnd(src,i),tag=src.slice(i,open);if(host==="html"||host==="vue")ref(tag,out);let generics=tag.match(GENERICS);if(generics?.index!==void 0){let start=i+generics.index+generics[0].length,stop=src.indexOf(generics[1],start);if(stop!==-1&&stop<open)lexRange(start,stop,TS)}let close=closeTag(src,open,"script"),dialect=LANG_JSX.test(tag)?TSX:TS;lexRange(open,close,dialect),i=close+8}else if(isTag(src,i,"style"))i=closeTag(src,tagEnd(src,i),"style")+7;else if(host==="html"&&(isTag(src,i,"link")||isTag(src,i,"iframe"))){let open=tagEnd(src,i);ref(src.slice(i,open),out),i=open}else i++}}function ref(tag,out){let match=TAG_REF.exec(tag),value=match&&(match[1]??match[2]??match[3]);if(value&&!URL_REF.test(value))out.imports.push({specifier:value.startsWith(".")?value:`./${value}`})}function frontmatter(src){let start=FENCE_OPEN.exec(src);if(!start)return 0;let from=start[0].length,close=src.slice(from).search(FENCE_CLOSE);if(close===-1)throw new LexError("unterminated frontmatter");return lexRange(from,from+close,TS),from+close+3}var COMMENTS3=/\/\/.*$|\/\*[\s\S]*?\*\//gm,QUOTED=/["']([^"']+)["']/g,STATIC_IMPORT=/(?:^|[\n;>])\s*(?:import|export)\s+(?:type\s+)?([^;"'`]*?)\s*from\s*["']([^"'\n]+)["']/g,SIDE_EFFECT_IMPORT=/(?:^|[\n;>])\s*import\s*["']([^"'\n]+)["']/g,CALL_WITH_LITERAL=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*(["'`])([^"'`$\n]+)\1\s*[,)]/g,NON_LITERAL_CALL=/(?<![.\w])(?:import|require)\(\s*(?!["'`])[^)\s]/,TEMPLATE_CALL=/(?<![.\w])(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\(\s*`[^`]*\$\{/,GLOB_CALL=/\bimport\.meta\.glob(?:<(?:[^<>]|<[^<>]*>)*>)?\(\s*(\[[^\]]*\]|["'][^"']*["'])/g,GLOB_CALL_ANY=/\bimport\.meta\.glob[<(]/g,GOTO=/\.goto\(\s*([^,)]*)/g,HTML_REF=/<(?:script|link|iframe)\b[^>]*\b(?:src|href)=["']([^"']+)["']/g,READS_DISK=/\b(?:from|import|require|importActual)\s*\(?\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;function extractRegex(source,html){let result={imports:[],globs:[],gotos:[],dependsOn:[],reads:[],unknown:[]};if(html){for(let[,ref]of source.matchAll(HTML_REF))if(!URL_REF.test(ref))result.imports.push({specifier:ref.startsWith(".")?ref:`./${ref}`})}for(let[,clause,specifier]of source.matchAll(STATIC_IMPORT)){let names=namedBindings(clause.replace(COMMENTS3,""));result.imports.push(names?{specifier,names}:{specifier})}for(let[,specifier]of source.matchAll(SIDE_EFFECT_IMPORT))result.imports.push({specifier});let calls=source.includes("import(")||source.includes("require(")||source.includes("vi.");for(let[,,specifier]of calls?source.matchAll(CALL_WITH_LITERAL):[])result.imports.push({specifier});if(calls&&(NON_LITERAL_CALL.test(source)||TEMPLATE_CALL.test(source)))result.unknown.push("non-literal dynamic import");let globbing=source.includes("import.meta.glob"),globs=globbing?[...source.matchAll(GLOB_CALL)]:[];if(globbing&&globs.length!==[...source.matchAll(GLOB_CALL_ANY)].length)result.unknown.push("non-literal glob import");for(let[,argument]of GLOB_REGISTRY.test(source)?[]:globs)for(let[,glob]of argument.matchAll(QUOTED)){if(glob.startsWith("!"))continue;result.globs.push(glob.replace(QUERY,""))}if(source.includes(".goto("))for(let[,argument]of source.matchAll(GOTO))result.gotos.push(argument.trim());if(result.dependsOn=[...source.includes("@depends-on")?source.matchAll(DEPENDS_ON):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),result.reads=[...source.includes("@reads")?source.matchAll(READS):[]].flatMap(([,list])=>list.split(LIST_SEPARATOR).filter(Boolean)),(source.includes("fs")||source.includes("child_process")||source.includes("Bun."))&&READS_DISK.test(source)&&result.dependsOn.length+result.reads.length===0)result.unknown.push("reads the disk without @depends-on");return result}var SCANNED=/\.(?:svelte|vue|astro|html|[cm]?[jt]sx?)$/;function formatOf(path){let host=hostOf(path);if(host)return host;let dialect=dialectOf(path);if(dialect===TSX)return"tsx";return dialect===JS?"js":"ts"}function extract(format,source){let lexed=createLexed(),extraction;try{if(openFile(source,lexed),isHost(format))lexHost(source,lexed,format);else lexRange(0,source.length,DIALECTS[format]);extraction=fromLexed(lexed)}catch(error){let fallback=error instanceof LexError?error.message:`lexer error: ${error}`;extraction={...extractRegex(source,format==="html"),fallback}}if(!isHost(format)){let barrel=parseReExports(source);if(barrel)extraction.barrel=barrel}return extraction}function finish(path,extraction,{gotos=!1}={}){let{globs}=extraction,dir=globs.length>0?posix2.dirname(path):"",result={imports:extraction.imports,globs:globs.map((glob)=>posix2.join(dir,glob)),gotos:gotos?extraction.gotos:[],dependsOn:extraction.dependsOn,reads:extraction.reads,unknown:extraction.unknown};if(extraction.fallback!==void 0)result.fallback=extraction.fallback;return result}var DIALECTS={ts:TS,tsx:TSX,js:JS},isHost=(format)=>format!=="ts"&&format!=="tsx"&&format!=="js";function fromLexed(lexed){let unknown=[];if(lexed.nonLiteralImport)unknown.push("non-literal dynamic import");if(lexed.nonLiteralGlob)unknown.push("non-literal glob import");let globs=[];for(let glob of lexed.registry?[]:lexed.globs){if(glob.startsWith("!"))continue;globs.push(glob.replace(QUERY,""))}if(lexed.readsDisk&&lexed.dependsOn.length+lexed.reads.length===0)unknown.push("reads the disk without @depends-on");return{imports:lexed.imports,globs,gotos:lexed.gotos,dependsOn:lexed.dependsOn,reads:lexed.reads,unknown}}var STRING_LITERAL=/^["'`]([^"'`$]*)["'`]$/,STATIC_PATH_TEMPLATE=/^`([^`$?#]*)[?#][^`]*`$/;function gotoUrl(argument){return STRING_LITERAL.exec(argument)?.[1]??STATIC_PATH_TEMPLATE.exec(argument)?.[1]}var leaf=()=>({files:new Set,patterns:[],reads:[],unknown:[]}),LEADING_DOT_SLASH2=/^\.\//,HERMETIC_CAUSES=new Set(["reads the disk without @depends-on","non-literal dynamic import"]);function sideEffectful(owning){let sideEffects=owning?.[1].sideEffects;if(sideEffects===!1)return()=>!1;if(!Array.isArray(sideEffects))return()=>!0;let dir=owning?.[0]??".";return matcher(sideEffects.map((glob)=>{if(!glob.includes("/"))return`**/${glob}`;let path=glob.replace(LEADING_DOT_SLASH2,"");return dir==="."?path:`${dir}/${path}`}))}function gotoSuite(config,path){return config.suites.find((suite)=>suite.urls.length>0&&suite.roots.some((root)=>inRoot(path,root)))}function mapUrl(suite,url){for(let{key,target}of suite.urls){let star=key.indexOf("*");if(star===-1){if(url===key)return target;continue}let prefix=key.slice(0,star),suffix=key.slice(star+1);if(url.startsWith(prefix)&&url.endsWith(suffix)){let match=url.slice(prefix.length,url.length-suffix.length);return target.replaceAll("*",match)}}return}function graphFrom(files,extractions,{config,packages}){let graph=new Map,paths=[...files],exists=new Set(paths),resolve=createResolver({files:exists,config,packages}),scans=new Map,barrels=new Map;for(let path of paths){let extraction=extractions.get(path);if(!extraction)continue;let gotos=gotoSuite(config,path)!==void 0;if(scans.set(path,finish(path,extraction,{gotos})),extraction.barrel&&config.isBarrel(path))barrels.set(path,extraction.barrel)}let named=new Map,effects=new Map,nameUnknown=new Map;for(let[path,barrel]of barrels){let effectful=sideEffectful(owner(packages,path));if(effectful(path))continue;let resolveTarget=(specifier)=>{let resolved=resolve(path,specifier);return resolved&&"files"in resolved?resolved.files:void 0},always=[];for(let specifier of[...barrel.names.values(),...barrel.stars])for(let file of resolveTarget(specifier)??[])if(effectful(file)&&!always.includes(file))always.push(file);let names=new Map;for(let[name,specifier]of barrel.names){let targets=resolveTarget(specifier);if(!targets)nameUnknown.set(`${path}#${name}`,[`unresolved "${specifier}"`]);names.set(name,targets??[])}named.set(path,names),effects.set(path,always)}let external=new Set;for(let path of paths){let found=scans.get(path);if(!found){graph.set(path,leaf());continue}let deps=leaf();for(let{specifier,names}of found.imports){let resolved=resolve(path,specifier);if(resolved===void 0)deps.unknown.push(`unresolved "${specifier}"`);else if("pkg"in resolved)deps.files.add(`pkg:${resolved.pkg}`),external.add(`pkg:${resolved.pkg}`);else for(let file of resolved.files){let barrel=names&&named.get(file);if(!barrel||!names){deps.files.add(file);continue}for(let name of names)deps.files.add(barrel.has(name)?`${file}#${name}`:file)}}deps.unknown.push(...config.isHermetic(path)?found.unknown.filter((cause)=>!HERMETIC_CAUSES.has(cause)):found.unknown);for(let glob of found.globs)deps.patterns.push(globToRegExp(glob));let suite=found.gotos.length>0?gotoSuite(config,path):void 0;if(suite)for(let argument of found.gotos){let url=gotoUrl(argument);if(url===void 0)deps.unknown.push(`non-literal goto(${argument})`);else if(url!=="about:blank"){let page=mapUrl(suite,url.replace(QUERY,""));if(page===void 0)deps.unknown.push(`goto("${url}")`);else if(exists.has(page))deps.files.add(page);else deps.unknown.push(`missing fixture "${url}"`)}}for(let glob of found.dependsOn)deps.patterns.push(globToRegExp(glob));for(let glob of found.reads)deps.reads.push(globToRegExp(glob));let names=named.get(path);if(names)deps.barrel=names;graph.set(path,deps)}for(let[path,names]of named)for(let[name,targets]of names){let id=`${path}#${name}`;graph.set(id,{...leaf(),files:new Set([...targets,...effects.get(path)??[]]),unknown:nameUnknown.get(id)??[]})}for(let id of external)graph.set(id,leaf());for(let deps of[...graph.values()])for(let file of deps.files)if(!graph.has(file)&&isGenerated(config,file))graph.set(file,leaf());for(let[path,deps]of graph)for(let{pattern,inputs}of config.generated)if(pattern.test(path))deps.patterns.push(...inputs);return graph}function isGenerated(config,path){return config.generated.some(({pattern})=>pattern.test(path))}function changedBarrelNames(before,after){let names=new Set([...before.keys(),...after.keys()]),key=(files)=>files?.join("\x00");return[...names].filter((name)=>key(before.get(name))!==key(after.get(name)))}function baseBarrelNames(path,source,{config,packages},graph){let barrel=source===void 0?void 0:parseBarrel(path,source);if(!barrel)return;let resolve=createResolver({files:new Set(graph.keys()),config,packages}),names=new Map;for(let[name,specifier]of barrel.names){let resolved=resolve(path,specifier);names.set(name,resolved&&"files"in resolved?resolved.files:[])}return names}var indexes=new WeakMap;function reverseIndex(graph){let cached=indexes.get(graph);if(cached)return cached;let index={dependents:new Map,globbers:[],readers:[],unknown:[]};for(let[path,deps]of graph){for(let file of deps.files){let list=index.dependents.get(file);list?list.push(path):index.dependents.set(file,[path])}if(deps.patterns.length>0)index.globbers.push([path,deps.patterns]);if(deps.reads.length>0)index.readers.push([path,deps.reads]);if(deps.unknown.length>0)index.unknown.push(path)}return indexes.set(graph,index),index}function importersOf(graph,node){return reverseIndex(graph).dependents.get(node)??[]}function affectedBy(graph,changed,{includeUnknown=!0,readers:seedReaders=!0,opaque,parents}={}){let{dependents,globbers,readers,unknown}=reverseIndex(graph),affected=new Set,queue=[],visit=(path,via)=>{if(affected.has(path)||opaque?.(path))return;if(affected.add(path),queue.push(path),via&&parents)parents.set(path,via)},changedPaths=[...changed];for(let path of changedPaths)visit(path);for(let[reader,patterns]of seedReaders?readers:[]){let read=changedPaths.find((path)=>patterns.some((re)=>re.test(path)));if(read!==void 0)visit(reader,{from:read,kind:"reads"})}let first=queue[0];if(includeUnknown&&first!==void 0)for(let path of unknown)visit(path,{from:first,kind:"unknown"});for(let at=0;at<queue.length;at++){let path=queue[at];for(let dependent of dependents.get(path)??[])visit(dependent,{from:path,kind:"import"});for(let[globber,patterns]of globbers)if(!affected.has(globber)&&patterns.some((re)=>re.test(path)))visit(globber,{from:path,kind:"glob"})}return affected}function formatSelection(selection){return selection.mode==="some"?selection.files.join(" "):selection.mode}function select(affected,tests){let files=tests.filter((file)=>affected.has(file));if(files.length===0)return{mode:"none"};if(files.length===tests.length)return{mode:"all"};return{mode:"some",files}}function classify(graph,changed,config){let reasons=[],full=new Set,runAll=()=>{for(let suite of config.suites)full.add(suite.name)},relevant=[];for(let file of changed){let read=graph.has(file);if(!read&&config.isIgnored(file))continue;let wired=config.suites.filter((suite)=>suite.isWiring(file));if(config.isSelf(file))reasons.push(`${file}: test selector changed`),runAll();else if(wired.length>0)for(let suite of wired)reasons.push(`${file}: wires the ${suite.name} suite`),full.add(suite.name);else if(read||config.roots.some((root)=>inRoot(file,root)))relevant.push(file);else reasons.push(`${file}: outside the dependency graph`),runAll()}return{relevant,reasons,full}}function narrowedWalk(graph,seeds,coarse,narrowings){let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched)),fine=affectedBy(graph,seeds.filter((seed)=>!matched.has(seed)));for(let narrowing of narrowings){let walk=affectedBy(graph,[...narrowing.matched,...narrowing.seeds],{opaque:narrowing.narrower.opaque});for(let node of walk)fine.add(node)}return new Set([...fine].filter((node)=>coarse.has(node)))}function planTests(graph,changed,config,{barrelNames=[],narrowed=[]}={}){let{relevant,reasons,full}=classify(graph,changed,config),seeds=[...relevant,...barrelNames],affected=affectedBy(graph,seeds),nodes=[...graph.keys()],tests=new Map(config.suites.map((suite)=>[suite.name,nodes.filter(suite.isTest)]));for(let suite of config.suites){let suiteTests=tests.get(suite.name)??[];for(let file of relevant){if(!suite.roots.some((root)=>inRoot(file,root)))continue;let reach=affectedBy(graph,[file],{includeUnknown:!1});if(suiteTests.some((test)=>reach.has(test)))continue;let deleted=!graph.has(file);if(deleted&&suite.isTest(file))continue;if(deleted&&config.isImportOnly(file))continue;if(suite.isNonInput(file))continue;if([...reach].some(suite.isPage))continue;reasons.push(`${file}: no ${suite.name} test imports it`),full.add(suite.name)}}let narrowings=new Map;for(let{narrower,result}of narrowed){let matched=relevant.filter(narrower.match);if(matched.length===0)continue;if("all"in result){reasons.push(`${narrower.name}: ${result.all}`);for(let name of narrower.suites)full.add(name);continue}for(let name of narrower.suites){let list=narrowings.get(name)??[];list.push({matched,narrower,seeds:result.seeds}),narrowings.set(name,list)}}let suites={};for(let suite of config.suites)suites[suite.name]=full.has(suite.name)?{mode:"all"}:select(narrowings.has(suite.name)?narrowedWalk(graph,seeds,affected,narrowings.get(suite.name)??[]):affected,tests.get(suite.name)??[]);return{suites,reasons,full:[...full],seeds,narrowings}}function hasCode(error,codes){return error instanceof Error&&"code"in error&&typeof error.code==="string"&&codes.includes(error.code)}async function readIfFile(path){try{return await readFile2(path,"utf-8")}catch(error){if(hasCode(error,["ENOENT","EISDIR"]))return;throw error}}function collectPackages(rootJson,sources){let packages=new Map,parse=(text)=>{try{return toPackageJson(JSON.parse(text))}catch{return{}}};if(rootJson!==void 0)packages.set(".",parse(rootJson));for(let[path,text]of sources){if(path==="package.json"||!path.endsWith("/package.json"))continue;packages.set(posix3.dirname(path),parse(text))}return packages}async function isFile(path){try{return(await stat(path)).isFile()}catch(error){if(hasCode(error,["ENOENT","ENOTDIR"]))return!1;throw error}}async function extractRevision(root,revision,cache){let extractions=new Map,texts=new Map,missing=new Set,pending=[],cached=0,read=async(file)=>{let text=await readIfFile(join3(root,file));if(text===void 0)missing.add(file);return text};for(let file of revision.files)if(SCANNED.test(file)){let format=formatOf(file),oid=revision.blobs.get(file),hit=oid===void 0?void 0:cache.get(oid,format);if(hit){extractions.set(file,hit),cached++;continue}pending.push(read(file).then((source)=>{if(source===void 0)return;let extraction=extract(format,source);if(extractions.set(file,extraction),oid!==void 0)cache.set(oid,format,extraction)}))}else if(file.endsWith("/package.json"))pending.push(read(file).then((source)=>{if(source!==void 0)texts.set(file,source)}));else if(!revision.present.has(file))pending.push(isFile(join3(root,file)).then((found)=>{if(!found)missing.add(file)}));await Promise.all(pending);let files=revision.files.filter((file)=>!missing.has(file)),manifests=new Map;for(let file of files){let text=texts.get(file);if(text!==void 0)manifests.set(file,text)}return{files,extractions,manifests,extracted:{cached,read:extractions.size-cached}}}function graphView(graph,config){let nodes=[...graph.keys()];return{nodes:()=>nodes,importers:(node)=>importersOf(graph,node),dependents:(from)=>affectedBy(graph,from,{includeUnknown:!1}),tests:(name)=>{let suite=config.suites.find((candidate)=>candidate.name===name);if(!suite)throw Error(`bivium: no suite "${name}"`);return nodes.filter(suite.isTest)}}}function messageOf(error){return error instanceof Error?error.message:String(error)}async function runNarrowers(root,revision,graph,config,suites){let{relevant}=classify(graph,revision.changed,config),wanted=config.narrowers.filter((narrower)=>relevant.some(narrower.match)&&(suites===void 0||narrower.suites.some((name)=>suites.includes(name))));if(wanted.length===0)return[];let view=graphView(graph,config),base={commit:revision.mergeBase,read:(path)=>showAt(root,revision.mergeBase,path)},head={commit:void 0,read:(path)=>readIfFile(join3(root,path))};return Promise.all(wanted.map(async(narrower)=>{let changed=relevant.filter(narrower.match);try{let result=await narrower.narrow({root,base,head,changed,graph:view});return{narrower,result}}catch(error){return{narrower,result:{all:`failed: ${messageOf(error)}`}}}}))}async function computePlan(root,base,config,{cache:cacheOption=config.cache,suites}={}){let dir=cacheDir(root,cacheOption),[revision,rootJson,cache]=await Promise.all([readRevision(root,base,config.roots,{blobs:dir!==void 0}),readFile2(join3(root,"package.json"),"utf-8").catch(()=>{return}),ExtractionCache.open(dir)]),{files,extractions,manifests,extracted}=await extractRevision(root,revision,cache),basePending=new Map(revision.changed.filter((file)=>config.isBarrel(file)&&extractions.get(file)?.barrel).map((file)=>[file,showAt(root,revision.mergeBase,file)])),packages=collectPackages(rootJson,manifests),graph=graphFrom(files,extractions,{config,packages}),saved=cache.save(),barrelNames=(await Promise.all([...basePending].map(async([file,pending])=>{let head=graph.get(file)?.barrel;if(!head)return[];let before=baseBarrelNames(file,await pending,{config,packages},graph);return(before?changedBarrelNames(before,head):[...head.keys()]).map((name)=>`${file}#${name}`)}))).flat(),narrowed=await runNarrowers(root,revision,graph,config,suites),planned=planTests(graph,revision.changed,config,{barrelNames,narrowed});return await saved,{plan:planned,graph,changed:revision.changed,mergeBase:revision.mergeBase,barrelNames,narrowed,packages,extractions,listed:revision.listed,fallbacks:new Map([...extractions].flatMap(([file,extraction])=>extraction.fallback===void 0?[]:[[file,extraction.fallback]])),extracted}}async function prepare({cwd=process.cwd(),base,config,configFile}){let root=resolve2(cwd),resolved;if(config)resolved=resolveConfig(checkConfig(config));else{let loaded=await loadConfig(root,configFile),isSelf=loaded.config.isSelf;resolved={...loaded.config,isSelf:(path)=>path===loaded.file||isSelf(path)}}return{root,base:base??resolved.base??await defaultBase(root),config:resolved}}async function plan2(options={}){let{root,base,config}=await prepare(options),computed=await computePlan(root,base,config,{...options.cache!==void 0&&{cache:options.cache}});return{suites:computed.plan.suites,reasons:computed.plan.reasons,base,mergeBase:computed.mergeBase,changed:computed.changed,narrowed:computed.narrowed.map(({narrower,result})=>({name:narrower.name,result}))}}
|
|
7
7
|
export{version,globToRegExp,defineConfig2,sorted,createResolver,SCANNED,formatOf,extract,finish,affectedBy,formatSelection,computePlan,prepare,plan2};
|