@variance-authority/core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +192 -0
- package/README.md +51 -9
- package/dist/attribute/closure.d.ts +105 -0
- package/dist/attribute/closure.js +180 -0
- package/dist/attribute/closure.js.map +1 -0
- package/dist/attribute/composition.d.ts +5 -3
- package/dist/attribute/composition.js.map +1 -1
- package/dist/attribute/divergence.js +7 -1
- package/dist/attribute/divergence.js.map +1 -1
- package/dist/attribute/index.d.ts +5 -1
- package/dist/attribute/index.js +3 -1
- package/dist/attribute/index.js.map +1 -1
- package/dist/attribute/lexicon.d.ts +88 -0
- package/dist/attribute/lexicon.js +150 -0
- package/dist/attribute/lexicon.js.map +1 -0
- package/dist/attribute/source.d.ts +19 -2
- package/dist/attribute/source.js +12 -0
- package/dist/attribute/source.js.map +1 -1
- package/dist/compare/derive.d.ts +17 -0
- package/dist/compare/derive.js.map +1 -1
- package/dist/compare/diff/index.d.ts +25 -1
- package/dist/compare/diff/index.js +8 -5
- package/dist/compare/diff/index.js.map +1 -1
- package/dist/compare/explain.d.ts +1 -1
- package/dist/compare/explain.js +15 -8
- package/dist/compare/explain.js.map +1 -1
- package/dist/compare/index.d.ts +2 -2
- package/dist/compare/index.js +1 -1
- package/dist/compare/index.js.map +1 -1
- package/dist/compare/observability.d.ts +25 -1
- package/dist/compare/observability.js +54 -0
- package/dist/compare/observability.js.map +1 -1
- package/dist/compare/parting.d.ts +24 -2
- package/dist/compare/parting.js +14 -9
- package/dist/compare/parting.js.map +1 -1
- package/dist/compare/slice.d.ts +15 -2
- package/dist/compare/slice.js +6 -2
- package/dist/compare/slice.js.map +1 -1
- package/dist/format/capture.d.ts +15 -0
- package/dist/format/capture.js +30 -1
- package/dist/format/capture.js.map +1 -1
- package/dist/format/document.d.ts +65 -5
- package/dist/format/document.js +34 -0
- package/dist/format/document.js.map +1 -1
- package/dist/format/hash.d.ts +26 -0
- package/dist/format/hash.js +41 -0
- package/dist/format/hash.js.map +1 -1
- package/dist/format/index.d.ts +4 -3
- package/dist/format/index.js +3 -2
- package/dist/format/index.js.map +1 -1
- package/dist/format/sha256.d.ts +10 -2
- package/dist/format/sha256.js +42 -9
- package/dist/format/sha256.js.map +1 -1
- package/dist/format/stabilize.d.ts +15 -0
- package/dist/format/stabilize.js +22 -1
- package/dist/format/stabilize.js.map +1 -1
- package/dist/index.d.ts +3 -11
- package/dist/index.js +3 -11
- package/dist/index.js.map +1 -1
- package/dist/relate/graph.d.ts +26 -6
- package/dist/relate/graph.js +14 -7
- package/dist/relate/graph.js.map +1 -1
- package/dist/relate/index.d.ts +2 -2
- package/dist/relate/index.js +1 -1
- package/dist/relate/index.js.map +1 -1
- package/dist/relate/merkle.d.ts +8 -5
- package/dist/relate/merkle.js +8 -6
- package/dist/relate/merkle.js.map +1 -1
- package/dist/relate/reach.d.ts +19 -5
- package/dist/relate/reach.js +10 -8
- package/dist/relate/reach.js.map +1 -1
- package/dist/relate/records.d.ts +29 -4
- package/dist/relate/records.js +60 -7
- package/dist/relate/records.js.map +1 -1
- package/dist/segment/index.d.ts +123 -0
- package/dist/segment/index.js +265 -0
- package/dist/segment/index.js.map +1 -0
- package/dist/share/index.d.ts +148 -0
- package/dist/share/index.js +190 -0
- package/dist/share/index.js.map +1 -0
- package/package.json +10 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stabilize.js","sourceRoot":"","sources":["../../src/format/stabilize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAe,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,WAAW,EAAa,MAAM,WAAW,CAAC;AA0DnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,cAAc,GAAiB;IAC1C,EAAE,EAAE,iBAAiB;IACrB,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,QAAQ;IACf,OAAO,EAAE,YAAY;IACrB,OAAO,EAAE,0EAA0E;IACnF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,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7F,CAAC","sourcesContent":["import { digestValue, type Digest } from './hash.js';\nimport { tierReaches, type Tier } from './tier.js';\nimport type { Intervention, PageGlobals, ScreenshotOptions, SettleTarget } from './intervention.js';\n\n/**\n * Interventions as separate, nameable tricks — not a fixed set of switches.\n *\n * A subject that is still changing cannot be compared, so every system of this\n * kind reaches into the page: it holds animations, waits for fonts, hides a\n * caret, suppresses scrollbars. Written as one struct of booleans that becomes a\n * closed vocabulary: adding a trick edits a type every caller depends on, and a\n * project with a need nobody anticipated has to fork.\n *\n * So each is a value. It carries an id, the tier that can actually observe what\n * it fixes, what it costs, and how it is applied — and a *recipe* is any list of\n * them. Two tricks may express the same intent through different mechanisms and\n * remain separate values, because they produce different images and choosing\n * between them is the caller's business.\n *\n * ## What this buys\n *\n * A recipe can be filtered by tier, so the structure-and-style rung waits for\n * nothing; composed from another project's tricks alongside these; digested, so\n * a baseline made under one recipe is `incomparable` with a run made under\n * another rather than `changed`; and checked for tricks that fight each other.\n *\n * ## Where the damage lands\n *\n * Ordered by increasing cost, earliest sufficient option first:\n *\n * - **Outside the subject** — injected CSS, browser screenshot options. Nothing\n * in the product imports it and deleting the tool deletes the intervention.\n * - **Runtime substitution** — wrapping `Promise`, replacing a suspense\n * boundary. Buys the same knowledge without touching a component and is\n * deliberately not shipped here: it moves the damage from design into\n * semantics, where a difference caused by the patch cannot be told apart from\n * a difference caused by the code. Expressible as a trick if a project decides\n * the trade is worth it — that is the point of an open set.\n * - **A contract the subject implements** — a readiness marker. Real design\n * damage, and reserved for what the outside genuinely cannot know.\n *\n * ## Why this is in `format` and not in the raster package\n *\n * It was in `@variance-authority/raster` until 2026-08-06, on the reading that\n * holding a page still is something you do before you photograph it. That\n * reading was wrong in a way that cost correctness: an animation in flight is a\n * *computed style value*, so it reaches the cheap representation too — and the\n * allowlist excludes `animation-*` and `transition-*` precisely because it\n * assumed a snapshot is taken with animation already disabled. Nothing disabled\n * it. See {@link COLLECT_RECIPE} and ADR-0028.\n *\n * So a recipe is a render input on every tier, `EnvironmentInputs` carries its\n * digest, and the vocabulary belongs beside the key it is part of.\n */\n\n// Re-exported from here because this is where a reader arrives looking for the\n// vocabulary; [`intervention.ts`](./intervention.js) holds the declaration.\nexport type { Intervention, ScreenshotOptions, SettleTarget, Trick } from './intervention.js';\n\n/**\n * Hand animations to the browser rather than emulating the hold in CSS.\n *\n * A browser disabling animations for a screenshot fast-forwards a finite\n * animation to completion — the state a user comes to rest on — and cancels an\n * infinite one to its initial frame, replaying it afterwards. That is the\n * behaviour worth having, and CSS cannot express it.\n */\nexport const holdAnimations: Intervention = {\n id: 'hold-animations',\n trick: 'hold',\n needs: 'layout',\n governs: 'animations',\n because: 'animations settled by the browser: finite fast-forwarded, infinite reset',\n screenshot: { animations: 'disabled' },\n};\n\n/**\n * The same intent without a browser that can do it, and it is not equivalent.\n *\n * Pins every animation at its first frame, so a fade-in is captured at the\n * moment it is invisible. `animation: none` is avoided deliberately — removing\n * an animation drops whatever layout its keyframes contribute, which changes the\n * page rather than stopping it.\n */\nexport const pinAnimations: Intervention = {\n id: 'pin-animations',\n trick: 'hold',\n needs: 'layout',\n governs: 'animations',\n because: 'animations pinned at their first frame, which is not where a user sees them',\n css:\n '*,*::before,*::after{' +\n 'animation-play-state:paused !important;' +\n 'animation-delay:-0.0001s !important;' +\n 'transition-duration:0s !important;' +\n 'transition-delay:0s !important;' +\n 'scroll-behavior:auto !important}',\n};\n\nexport const hideCaret: Intervention = {\n id: 'hide-caret',\n trick: 'support',\n // A caret paints and does not lay out, so a tier that never rasterizes cannot\n // see it and must not pay to hide it.\n needs: 'raster',\n governs: 'caret',\n because: 'text caret hidden, because it blinks on its own schedule',\n screenshot: { caret: 'hide' },\n};\n\nexport const hideScrollbars: Intervention = {\n id: 'hide-scrollbars',\n trick: 'support',\n needs: 'layout',\n governs: 'scrollbars',\n because: 'scrollbars hidden, removing a platform and preference difference — and their width',\n css: '*{scrollbar-width:none !important}\\n*::-webkit-scrollbar{display:none !important}',\n};\n\n/**\n * Drop the pixels of images the page itself called decorative, keeping their boxes.\n *\n * The other half of blanking, and it lives here because of what it needs to\n * know. A driver rewriting responses (`@variance-authority/playwright`'s\n * `blank` rules) can decide by URL and by intrinsic size, which answers \"every\n * illustration over 40,000 pixels\" and answers it before the bytes are even\n * fetched. It cannot answer `role=\"presentation\"`, because a request carries no\n * idea which element wanted it — that fact exists only in the document, so the\n * trick that uses it is a stylesheet.\n *\n * `visibility:hidden` rather than `display:none`, and the distinction is the\n * entire design: a hidden element still occupies exactly the box it would have,\n * so a page whose column height comes from an image's intrinsic size is\n * unchanged. `display:none` would collapse it and report a layout regression\n * this tool caused.\n *\n * **Opt-in, and it belongs in no default recipe.** Every other trick here\n * removes something that is not part of the assertion — a caret, a scrollbar, an\n * animation mid-flight. This one removes page content, which is a judgement\n * about what a suite is for, and a default that quietly stopped watching every\n * `alt=\"\"` image would hide real regressions under a green run.\n */\nexport const hidePresentationalImages: Intervention = {\n id: 'hide-presentational-images',\n trick: 'support',\n // `layout` rather than `raster`, and the difference is whether it runs at all.\n // A raster-tier trick is filtered out of every *collection* — `tierOfProfile`\n // never returns `raster` — so it would only reach a page through a renderer\n // option, which is not where an operator configures their suite. A collection\n // sheet is in force when the document is serialized, so hiding it here is what\n // makes the pixels absent from the render.\n needs: 'layout',\n governs: 'presentational-images',\n because:\n 'images the page marked decorative hidden, keeping their boxes — real changes inside them ' +\n 'are not reported',\n css:\n 'img[role=\"presentation\"],img[alt=\"\"],[role=\"presentation\"] img,[role=\"none\"] img' +\n '{visibility:hidden !important}',\n};\n\nexport const waitForFonts: Intervention = {\n id: 'wait-for-fonts',\n trick: 'wait',\n needs: 'layout',\n governs: 'fonts',\n because: 'waited for web fonts, whose advances change every metric on the page',\n // Written without a module-scope helper on purpose: a settle closure is\n // shipped to a page as source text, so anything it names by identifier is a\n // `ReferenceError` on the far side. Types are erased and therefore free.\n settle: async (target) => {\n await target.evaluate(async () => {\n const view = globalThis as unknown as PageGlobals;\n await view.document.fonts?.ready;\n });\n },\n};\n\nexport const waitForImages: Intervention = {\n id: 'wait-for-images',\n trick: 'wait',\n needs: 'layout',\n governs: 'images',\n because:\n 'waited for images to decode, since their intrinsic size participates in layout, and asked ' +\n 'for the ones the browser had deferred',\n settle: async (target) => {\n await target.evaluate(async () => {\n const view = globalThis as unknown as PageGlobals;\n const pending = Array.from(view.document.images).filter((image) => !image.complete);\n\n const arrived = Promise.all(\n pending.map(\n (image) =>\n new Promise<void>((resolve) => {\n image.addEventListener('load', () => resolve(), { once: true });\n image.addEventListener('error', () => resolve(), { once: true });\n }),\n ),\n );\n\n // Asked for, after the listeners are attached and before anything is\n // awaited. A `loading=\"lazy\"` image outside the viewport has not been\n // requested and will not be until something scrolls, so waiting on it is\n // waiting for a decision the browser has already taken the other way.\n //\n // This is the same act as pinning an animation, not a different kind of\n // thing: what the page shows stops depending on where the viewport\n // happens to be. It matters most for the readings that need it most — a\n // full-page capture of a long page is exactly the case where most of the\n // images are deferred, and photographing it without them yields a picture\n // full of empty boxes whose contents change with the browser's loading\n // heuristics rather than with the product.\n const asServed = pending.map((image) => image.loading);\n for (const image of pending) image.loading = 'eager';\n\n // Bounded, and it throws when the bound is reached.\n //\n // A response can stall: a CDN that never answers, an image endpoint that\n // deadlocks under its own concurrency, an image the browser deferred and\n // will not request from where the page is scrolled. None of those fire\n // `load` and none fire `error`, so an unbounded wait turns one stuck\n // request into a run that never ends and never says why — not a wrong\n // answer, no answer.\n //\n // Giving up quietly would be worse than the hang in a subtler way: it\n // photographs a page with holes in it and reports the holes as a change,\n // inventing a regression out of the network this trick exists to hold\n // still. Refused instead, naming what it was still waiting for, because\n // \"these two never answered\" is a finding about the application.\n //\n // The bound is written twice — once as the delay, once in the sentence —\n // because a settle closure is shipped to the page as source text and a\n // constant it named would be a `ReferenceError` on the far side.\n // Held so the loser can be cancelled. A timer left to fire after the\n // images arrived rejects a promise nothing is waiting on any more, which\n // the page reports as an unhandled rejection — this trick's own noise,\n // arriving in the console of every subject it succeeded on.\n let timer: unknown;\n\n const expired = new Promise<never>((_, reject) => {\n timer = view.setTimeout(() => {\n const stuck = pending.filter((image) => !image.complete);\n reject(\n new Error(\n `${stuck.length} image(s) had not loaded after 15000ms, and neither answered ` +\n `nor failed: ${stuck.map((image) => image.currentSrc || image.src).join(', ')}`,\n ),\n );\n }, 15000);\n });\n\n try {\n await Promise.race([arrived, expired]);\n } finally {\n view.clearTimeout(timer);\n\n // Put back, because the trick has to be invisible to the tier that\n // reads the page after it. `loading` is a reflected attribute, so a\n // document whose deferred images were switched to `eager` and left that\n // way is a document that no longer matches the one the product served —\n // and which images were still undecoded when this ran is a question\n // about the network, so the edit lands in some readings and not others.\n // Left in, it makes the same page at two widths disagree about its own\n // markup: this trick filed as a finding against the application.\n for (let index = 0; index < pending.length; index += 1) {\n pending[index]!.loading = asServed[index]!;\n }\n }\n });\n },\n};\n\nexport const INTERVENTIONS: readonly Intervention[] = [\n holdAnimations,\n pinAnimations,\n hideCaret,\n hideScrollbars,\n hidePresentationalImages,\n waitForFonts,\n waitForImages,\n];\n\nexport type Recipe = readonly Intervention[];\n\n/**\n * Nothing at all, and correct for the tier that reads structure and declared style.\n *\n * A font that has not loaded cannot change which rules match or what they\n * declare; an image that has not decoded cannot either. Waiting for both before\n * a structure-and-style hash buys nothing and costs the wait per subject, on the\n * rung the tier ladder exists to make cheap.\n */\nexport const SEMANTIC_RECIPE: Recipe = [];\n\nexport const LAYOUT_RECIPE: Recipe = [holdAnimations, hideScrollbars, waitForFonts, waitForImages];\n\nexport const RASTER_RECIPE: Recipe = [...LAYOUT_RECIPE, hideCaret];\n\n/**\n * What is applied to a live page *before a subject is observed*, as opposed to\n * before it is painted.\n *\n * The two are different recipes and it is not a preference. {@link\n * holdAnimations} is a *screenshot option* — it asks the browser to settle\n * animations for the image it is about to take — and there is no screenshot at\n * collection time, so it would be a trick that silently does nothing. The CSS\n * variant is the one that works where nobody is holding a camera, which is the\n * whole reason both exist as separate values rather than as one switch.\n *\n * ## Why the cheap tier needs this at all\n *\n * The claim in [`ruleset.ts`](../rules/ruleset.ts) that `transition-*` and\n * `animation-*` \"describe a journey the snapshot does not contain\" is only true\n * if the snapshot is taken with the journey stopped. `transform`, `opacity`,\n * `filter`, `color` and every geometric longhand *are* admitted, and an\n * animation in flight moves all of them — so an unstabilized collection turns a\n * 300ms fade into a component-attributed regression with a real file name on it,\n * which is worse than an unexplained pixel diff because it is credible.\n *\n * Filtered by {@link forTier}, so jsdom applies none of it: with no layout\n * engine and no animation clock there is nothing to hold still, and paying a\n * `fonts.ready` wait per subject on the rung that exists to be cheap is exactly\n * the trade {@link SEMANTIC_RECIPE} refuses.\n */\nexport const COLLECT_RECIPE: Recipe = [\n pinAnimations,\n hideScrollbars,\n waitForFonts,\n waitForImages,\n];\n\n/**\n * Resolve a trick by the name a caller wrote down.\n *\n * The boundary a collection recipe crosses is a `page.evaluate`, and an\n * `Intervention` does not survive it — `settle` is a function. Ids do survive,\n * and the page holds this same registry, so a recipe travels as the list of\n * names it is. A name nothing answers to is a caller error worth failing on\n * rather than a trick to skip quietly: under-stabilizing is how a suite gets a\n * flake it has already paid to prevent.\n */\nexport function interventionById(id: string): Intervention | undefined {\n return INTERVENTIONS.find((intervention) => intervention.id === id);\n}\n\n/**\n * A recipe from the names it travels as.\n *\n * Throws on a name nothing answers to, and names it. The quiet alternative —\n * skip what cannot be resolved — turns a typo in a config into a suite that is\n * one trick less stable than its operator believes, discovered later as a flake\n * they have already paid to prevent. Failing here costs one run and one reading\n * of the message.\n */\nexport function recipeOf(ids: readonly string[]): Recipe {\n return ids.map((id) => {\n const intervention = interventionById(id);\n if (intervention === undefined) {\n throw new Error(\n `no stabilization trick is called \\`${id}\\`; this build knows ` +\n INTERVENTIONS.map((known) => `\\`${known.id}\\``).join(', '),\n );\n }\n return intervention;\n });\n}\n\n/** Only the tricks a tier can observe the effect of. */\nexport function forTier(recipe: Recipe, tier: Tier): Recipe {\n return recipe.filter((intervention) => tierReaches(tier, intervention.needs));\n}\n\n/**\n * Tricks in a recipe that claim the same property.\n *\n * Returned rather than thrown, so a caller can decide — an override is a\n * legitimate composition, and silently applying both is not. Two tricks over one\n * property means one of them wins by accident of ordering, and which one is\n * invisible in the result.\n */\nexport function conflicts(recipe: Recipe): readonly { governs: string; ids: readonly string[] }[] {\n const byProperty = new Map<string, string[]>();\n\n for (const intervention of recipe) {\n byProperty.set(intervention.governs, [\n ...(byProperty.get(intervention.governs) ?? []),\n intervention.id,\n ]);\n }\n\n return [...byProperty.entries()]\n .filter(([, ids]) => ids.length > 1)\n .map(([governs, ids]) => ({ governs, ids }));\n}\n\nexport function recipeCss(recipe: Recipe): string {\n return recipe\n .map((intervention) => intervention.css)\n .filter((css): css is string => css !== undefined)\n .join('\\n');\n}\n\nexport function recipeScreenshot(recipe: Recipe): ScreenshotOptions {\n return recipe.reduce<ScreenshotOptions>(\n (options, intervention) => ({ ...options, ...intervention.screenshot }),\n {},\n );\n}\n\nexport async function settleRecipe(recipe: Recipe, target: SettleTarget): Promise<void> {\n for (const intervention of recipe) {\n if (intervention.settle !== undefined) await intervention.settle(target);\n }\n}\n\n/**\n * The identity of a recipe.\n *\n * Sorted, so the order tricks were composed in does not change the identity —\n * only which ones are present. Folded into `RenderIdentity`, which is what makes\n * a cross-recipe comparison report `incomparable` instead of inventing a\n * component to blame.\n */\nexport function recipeDigest(recipe: Recipe): Digest {\n return digestValue(recipe.map((intervention) => intervention.id).sort());\n}\n\n/** The recipe as a sentence, so the gap between image and product stays visible. */\nexport function describeRecipe(recipe: Recipe): string {\n return recipe.length === 0\n ? 'the subject was observed untouched'\n : `the subject was altered to be observable: ${recipe.map((i) => i.because).join('; ')}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stabilize.js","sourceRoot":"","sources":["../../src/format/stabilize.ts"],"names":[],"mappings":"AAAA,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AC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAC3E,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,cAAc,CAAC,MAAc;IAC3C,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC;QACxB,CAAC,CAAC,oCAAoC;QACtC,CAAC,CAAC,6CAA6C,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7F,CAAC","sourcesContent":["import { digestValue, type Digest } from './hash.js';\nimport { tierReaches, type Tier } from './tier.js';\nimport type { Intervention, PageGlobals, ScreenshotOptions, SettleTarget } from './intervention.js';\n\n/**\n * Interventions as separate, nameable tricks — not a fixed set of switches.\n *\n * A subject that is still changing cannot be compared, so every system of this\n * kind reaches into the page: it holds animations, waits for fonts, hides a\n * caret, suppresses scrollbars. Written as one struct of booleans that becomes a\n * closed vocabulary: adding a trick edits a type every caller depends on, and a\n * project with a need nobody anticipated has to fork.\n *\n * So each is a value. It carries an id, the tier that can actually observe what\n * it fixes, what it costs, and how it is applied — and a *recipe* is any list of\n * them. Two tricks may express the same intent through different mechanisms and\n * remain separate values, because they produce different images and choosing\n * between them is the caller's business.\n *\n * ## What this buys\n *\n * A recipe can be filtered by tier, so the structure-and-style rung waits for\n * nothing; composed from another project's tricks alongside these; digested, so\n * a baseline made under one recipe is `incomparable` with a run made under\n * another rather than `changed`; and checked for tricks that fight each other.\n *\n * ## Where the damage lands\n *\n * Ordered by increasing cost, earliest sufficient option first:\n *\n * - **Outside the subject** — injected CSS, browser screenshot options. Nothing\n * in the product imports it and deleting the tool deletes the intervention.\n * - **Runtime substitution** — wrapping `Promise`, replacing a suspense\n * boundary. Buys the same knowledge without touching a component and is\n * deliberately not shipped here: it moves the damage from design into\n * semantics, where a difference caused by the patch cannot be told apart from\n * a difference caused by the code. Expressible as a trick if a project decides\n * the trade is worth it — that is the point of an open set.\n * - **A contract the subject implements** — a readiness marker. Real design\n * damage, and reserved for what the outside genuinely cannot know.\n *\n * ## Why this is in `format` and not in the raster package\n *\n * It was in `@variance-authority/raster` until 2026-08-06, on the reading that\n * holding a page still is something you do before you photograph it. That\n * reading was wrong in a way that cost correctness: an animation in flight is a\n * *computed style value*, so it reaches the cheap representation too — and the\n * allowlist excludes `animation-*` and `transition-*` precisely because it\n * assumed a snapshot is taken with animation already disabled. Nothing disabled\n * it. See {@link COLLECT_RECIPE} and ADR-0028.\n *\n * So a recipe is a render input on every tier, `EnvironmentInputs` carries its\n * digest, and the vocabulary belongs beside the key it is part of.\n */\n\n// Re-exported from here because this is where a reader arrives looking for the\n// vocabulary; [`intervention.ts`](./intervention.js) holds the declaration.\nexport type { Intervention, ScreenshotOptions, SettleTarget, Trick } from './intervention.js';\n\n/**\n * Hand animations to the browser rather than emulating the hold in CSS.\n *\n * A browser disabling animations for a screenshot fast-forwards a finite\n * animation to completion — the state a user comes to rest on — and cancels an\n * infinite one to its initial frame, replaying it afterwards. That is the\n * behaviour worth having, and CSS cannot express it.\n */\nexport const holdAnimations: Intervention = {\n id: 'hold-animations',\n trick: 'hold',\n needs: 'layout',\n governs: 'animations',\n because: 'animations settled by the browser: finite fast-forwarded, infinite reset',\n screenshot: { animations: 'disabled' },\n};\n\n/**\n * The same intent without a browser that can do it, and it is not equivalent.\n *\n * Pins every animation at its first frame, so a fade-in is captured at the\n * moment it is invisible. `animation: none` is avoided deliberately — removing\n * an animation drops whatever layout its keyframes contribute, which changes the\n * page rather than stopping it.\n */\nexport const pinAnimations: Intervention = {\n id: 'pin-animations',\n trick: 'hold',\n needs: 'layout',\n governs: 'animations',\n because: 'animations pinned at their first frame, which is not where a user sees them',\n css:\n '*,*::before,*::after{' +\n 'animation-play-state:paused !important;' +\n 'animation-delay:-0.0001s !important;' +\n 'transition-duration:0s !important;' +\n 'transition-delay:0s !important;' +\n 'scroll-behavior:auto !important}',\n};\n\n/**\n * A stylesheet rather than the driver's own caret switch, deliberately.\n *\n * Playwright and its peers hide a caret by writing `caret-color` onto every\n * focusable element and putting it back afterwards, and putting it back leaves\n * `style=\"\"` where there was no `style` attribute at all. Any capture that reads\n * the DOM on both sides of a screenshot — which is what the in-place path does\n * to prove the subject held still — then sees markup that moved, and reports the\n * driver's housekeeping as the page being unstable. A page with one text input\n * is enough.\n *\n * So this hold owns the caret the way {@link pinAnimations} owns animations: one\n * stylesheet, installed before the subject is read, removed with the rest of the\n * recipe.\n */\nexport const hideCaret: Intervention = {\n id: 'hide-caret',\n trick: 'support',\n // A caret paints and does not lay out, so a tier that never rasterizes cannot\n // see it and must not pay to hide it.\n needs: 'raster',\n governs: 'caret',\n because: 'text caret hidden, because it blinks on its own schedule',\n css: '*{caret-color:transparent !important}',\n};\n\nexport const hideScrollbars: Intervention = {\n id: 'hide-scrollbars',\n trick: 'support',\n needs: 'layout',\n governs: 'scrollbars',\n because: 'scrollbars hidden, removing a platform and preference difference — and their width',\n css: '*{scrollbar-width:none !important}\\n*::-webkit-scrollbar{display:none !important}',\n};\n\n/**\n * Drop the pixels of images the page itself called decorative, keeping their boxes.\n *\n * The other half of blanking, and it lives here because of what it needs to\n * know. A driver rewriting responses (`@variance-authority/playwright`'s\n * `blank` rules) can decide by URL and by intrinsic size, which answers \"every\n * illustration over 40,000 pixels\" and answers it before the bytes are even\n * fetched. It cannot answer `role=\"presentation\"`, because a request carries no\n * idea which element wanted it — that fact exists only in the document, so the\n * trick that uses it is a stylesheet.\n *\n * `visibility:hidden` rather than `display:none`, and the distinction is the\n * entire design: a hidden element still occupies exactly the box it would have,\n * so a page whose column height comes from an image's intrinsic size is\n * unchanged. `display:none` would collapse it and report a layout regression\n * this tool caused.\n *\n * **Opt-in, and it belongs in no default recipe.** Every other trick here\n * removes something that is not part of the assertion — a caret, a scrollbar, an\n * animation mid-flight. This one removes page content, which is a judgement\n * about what a suite is for, and a default that quietly stopped watching every\n * `alt=\"\"` image would hide real regressions under a green run.\n */\nexport const hidePresentationalImages: Intervention = {\n id: 'hide-presentational-images',\n trick: 'support',\n // `layout` rather than `raster`, and the difference is whether it runs at all.\n // A raster-tier trick is filtered out of every *collection* — `tierOfProfile`\n // never returns `raster` — so it would only reach a page through a renderer\n // option, which is not where an operator configures their suite. A collection\n // sheet is in force when the document is serialized, so hiding it here is what\n // makes the pixels absent from the render.\n needs: 'layout',\n governs: 'presentational-images',\n because:\n 'images the page marked decorative hidden, keeping their boxes — real changes inside them ' +\n 'are not reported',\n css:\n 'img[role=\"presentation\"],img[alt=\"\"],[role=\"presentation\"] img,[role=\"none\"] img' +\n '{visibility:hidden !important}',\n};\n\nexport const waitForFonts: Intervention = {\n id: 'wait-for-fonts',\n trick: 'wait',\n needs: 'layout',\n governs: 'fonts',\n because: 'waited for web fonts, whose advances change every metric on the page',\n // Written without a module-scope helper on purpose: a settle closure is\n // shipped to a page as source text, so anything it names by identifier is a\n // `ReferenceError` on the far side. Types are erased and therefore free.\n settle: async (target) => {\n await target.evaluate(async () => {\n const view = globalThis as unknown as PageGlobals;\n await view.document.fonts?.ready;\n });\n },\n};\n\nexport const waitForImages: Intervention = {\n id: 'wait-for-images',\n trick: 'wait',\n needs: 'layout',\n governs: 'images',\n because:\n 'waited for images to decode, since their intrinsic size participates in layout, and asked ' +\n 'for the ones the browser had deferred',\n settle: async (target) => {\n await target.evaluate(async () => {\n const view = globalThis as unknown as PageGlobals;\n const pending = Array.from(view.document.images).filter((image) => !image.complete);\n\n const arrived = Promise.all(\n pending.map(\n (image) =>\n new Promise<void>((resolve) => {\n image.addEventListener('load', () => resolve(), { once: true });\n image.addEventListener('error', () => resolve(), { once: true });\n }),\n ),\n );\n\n // Asked for, after the listeners are attached and before anything is\n // awaited. A `loading=\"lazy\"` image outside the viewport has not been\n // requested and will not be until something scrolls, so waiting on it is\n // waiting for a decision the browser has already taken the other way.\n //\n // This is the same act as pinning an animation, not a different kind of\n // thing: what the page shows stops depending on where the viewport\n // happens to be. It matters most for the readings that need it most — a\n // full-page capture of a long page is exactly the case where most of the\n // images are deferred, and photographing it without them yields a picture\n // full of empty boxes whose contents change with the browser's loading\n // heuristics rather than with the product.\n const asServed = pending.map((image) => image.loading);\n for (const image of pending) image.loading = 'eager';\n\n // Bounded, and it throws when the bound is reached.\n //\n // A response can stall: a CDN that never answers, an image endpoint that\n // deadlocks under its own concurrency, an image the browser deferred and\n // will not request from where the page is scrolled. None of those fire\n // `load` and none fire `error`, so an unbounded wait turns one stuck\n // request into a run that never ends and never says why — not a wrong\n // answer, no answer.\n //\n // Giving up quietly would be worse than the hang in a subtler way: it\n // photographs a page with holes in it and reports the holes as a change,\n // inventing a regression out of the network this trick exists to hold\n // still. Refused instead, naming what it was still waiting for, because\n // \"these two never answered\" is a finding about the application.\n //\n // The bound is written twice — once as the delay, once in the sentence —\n // because a settle closure is shipped to the page as source text and a\n // constant it named would be a `ReferenceError` on the far side.\n // Held so the loser can be cancelled. A timer left to fire after the\n // images arrived rejects a promise nothing is waiting on any more, which\n // the page reports as an unhandled rejection — this trick's own noise,\n // arriving in the console of every subject it succeeded on.\n let timer: unknown;\n\n const expired = new Promise<never>((_, reject) => {\n timer = view.setTimeout(() => {\n const stuck = pending.filter((image) => !image.complete);\n reject(\n new Error(\n `${stuck.length} image(s) had not loaded after 15000ms, and neither answered ` +\n `nor failed: ${stuck.map((image) => image.currentSrc || image.src).join(', ')}`,\n ),\n );\n }, 15000);\n });\n\n try {\n await Promise.race([arrived, expired]);\n } finally {\n view.clearTimeout(timer);\n\n // Put back, because the trick has to be invisible to the tier that\n // reads the page after it. `loading` is a reflected attribute, so a\n // document whose deferred images were switched to `eager` and left that\n // way is a document that no longer matches the one the product served —\n // and which images were still undecoded when this ran is a question\n // about the network, so the edit lands in some readings and not others.\n // Left in, it makes the same page at two widths disagree about its own\n // markup: this trick filed as a finding against the application.\n for (let index = 0; index < pending.length; index += 1) {\n pending[index]!.loading = asServed[index]!;\n }\n }\n });\n },\n};\n\nexport const INTERVENTIONS: readonly Intervention[] = [\n holdAnimations,\n pinAnimations,\n hideCaret,\n hideScrollbars,\n hidePresentationalImages,\n waitForFonts,\n waitForImages,\n];\n\nexport type Recipe = readonly Intervention[];\n\n/**\n * Nothing at all, and correct for the tier that reads structure and declared style.\n *\n * A font that has not loaded cannot change which rules match or what they\n * declare; an image that has not decoded cannot either. Waiting for both before\n * a structure-and-style hash buys nothing and costs the wait per subject, on the\n * rung the tier ladder exists to make cheap.\n */\nexport const SEMANTIC_RECIPE: Recipe = [];\n\nexport const LAYOUT_RECIPE: Recipe = [holdAnimations, hideScrollbars, waitForFonts, waitForImages];\n\nexport const RASTER_RECIPE: Recipe = [...LAYOUT_RECIPE, hideCaret];\n\n/**\n * What is applied to a live page *before a subject is observed*, as opposed to\n * before it is painted.\n *\n * The two are different recipes and it is not a preference. {@link\n * holdAnimations} is a *screenshot option* — it asks the browser to settle\n * animations for the image it is about to take — and there is no screenshot at\n * collection time, so it would be a trick that silently does nothing. The CSS\n * variant is the one that works where nobody is holding a camera, which is the\n * whole reason both exist as separate values rather than as one switch.\n *\n * ## Why the cheap tier needs this at all\n *\n * The claim in [`ruleset.ts`](../rules/ruleset.ts) that `transition-*` and\n * `animation-*` \"describe a journey the snapshot does not contain\" is only true\n * if the snapshot is taken with the journey stopped. `transform`, `opacity`,\n * `filter`, `color` and every geometric longhand *are* admitted, and an\n * animation in flight moves all of them — so an unstabilized collection turns a\n * 300ms fade into a component-attributed regression with a real file name on it,\n * which is worse than an unexplained pixel diff because it is credible.\n *\n * Filtered by {@link forTier}, so jsdom applies none of it: with no layout\n * engine and no animation clock there is nothing to hold still, and paying a\n * `fonts.ready` wait per subject on the rung that exists to be cheap is exactly\n * the trade {@link SEMANTIC_RECIPE} refuses.\n */\nexport const COLLECT_RECIPE: Recipe = [\n pinAnimations,\n hideScrollbars,\n // Here as well as in {@link RASTER_RECIPE}, because the in-place path\n // photographs the live page and applies no screenshot options of its own: the\n // only caret hold that reaches that image is one installed here. A subject\n // holding a focused input otherwise disagrees with itself between two\n // screenshots taken 600ms apart, and is refused for blinking.\n hideCaret,\n waitForFonts,\n waitForImages,\n];\n\n/**\n * Resolve a trick by the name a caller wrote down.\n *\n * The boundary a collection recipe crosses is a `page.evaluate`, and an\n * `Intervention` does not survive it — `settle` is a function. Ids do survive,\n * and the page holds this same registry, so a recipe travels as the list of\n * names it is. A name nothing answers to is a caller error worth failing on\n * rather than a trick to skip quietly: under-stabilizing is how a suite gets a\n * flake it has already paid to prevent.\n */\nexport function interventionById(id: string): Intervention | undefined {\n return INTERVENTIONS.find((intervention) => intervention.id === id);\n}\n\n/**\n * A recipe from the names it travels as.\n *\n * Throws on a name nothing answers to, and names it. The quiet alternative —\n * skip what cannot be resolved — turns a typo in a config into a suite that is\n * one trick less stable than its operator believes, discovered later as a flake\n * they have already paid to prevent. Failing here costs one run and one reading\n * of the message.\n */\nexport function recipeOf(ids: readonly string[]): Recipe {\n return ids.map((id) => {\n const intervention = interventionById(id);\n if (intervention === undefined) {\n throw new Error(\n `no stabilization trick is called \\`${id}\\`; this build knows ` +\n INTERVENTIONS.map((known) => `\\`${known.id}\\``).join(', '),\n );\n }\n return intervention;\n });\n}\n\n/** Only the tricks a tier can observe the effect of. */\nexport function forTier(recipe: Recipe, tier: Tier): Recipe {\n return recipe.filter((intervention) => tierReaches(tier, intervention.needs));\n}\n\n/**\n * Tricks in a recipe that claim the same property.\n *\n * Returned rather than thrown, so a caller can decide — an override is a\n * legitimate composition, and silently applying both is not. Two tricks over one\n * property means one of them wins by accident of ordering, and which one is\n * invisible in the result.\n */\nexport function conflicts(recipe: Recipe): readonly { governs: string; ids: readonly string[] }[] {\n const byProperty = new Map<string, string[]>();\n\n for (const intervention of recipe) {\n byProperty.set(intervention.governs, [\n ...(byProperty.get(intervention.governs) ?? []),\n intervention.id,\n ]);\n }\n\n return [...byProperty.entries()]\n .filter(([, ids]) => ids.length > 1)\n .map(([governs, ids]) => ({ governs, ids }));\n}\n\nexport function recipeCss(recipe: Recipe): string {\n return recipe\n .map((intervention) => intervention.css)\n .filter((css): css is string => css !== undefined)\n .join('\\n');\n}\n\nexport function recipeScreenshot(recipe: Recipe): ScreenshotOptions {\n return recipe.reduce<ScreenshotOptions>(\n (options, intervention) => ({ ...options, ...intervention.screenshot }),\n {},\n );\n}\n\nexport async function settleRecipe(recipe: Recipe, target: SettleTarget): Promise<void> {\n for (const intervention of recipe) {\n if (intervention.settle !== undefined) await intervention.settle(target);\n }\n}\n\n/**\n * The identity of a recipe.\n *\n * Sorted, so the order tricks were composed in does not change the identity —\n * only which ones are present. Folded into `RenderIdentity`, which is what makes\n * a cross-recipe comparison report `incomparable` instead of inventing a\n * component to blame.\n */\nexport function recipeDigest(recipe: Recipe): Digest {\n return digestValue(recipe.map((intervention) => intervention.id).sort());\n}\n\n/** The recipe as a sentence, so the gap between image and product stays visible. */\nexport function describeRecipe(recipe: Recipe): string {\n return recipe.length === 0\n ? 'the subject was observed untouched'\n : `the subject was altered to be observable: ${recipe.map((i) => i.because).join('; ')}`;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -19,17 +19,9 @@
|
|
|
19
19
|
* | `core/judge` | policy: verdicts, intent, the docket a reader is handed |
|
|
20
20
|
* | `core/plan` | a composition as a value, and the identity derived from it |
|
|
21
21
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* everything else.
|
|
22
|
+
* Every name lives in exactly one of them; nothing is reachable from two paths.
|
|
23
|
+
* This entrypoint holds only what belongs to no group: the artifact a capture is
|
|
24
|
+
* written to.
|
|
26
25
|
*/
|
|
27
|
-
export * from './format/index.js';
|
|
28
|
-
export * from './rules/index.js';
|
|
29
|
-
export * from './compare/index.js';
|
|
30
|
-
export * from './attribute/index.js';
|
|
31
|
-
export * from './relate/index.js';
|
|
32
|
-
export * from './judge/index.js';
|
|
33
|
-
export * from './plan/index.js';
|
|
34
26
|
export * from './artifact.js';
|
|
35
27
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -19,17 +19,9 @@
|
|
|
19
19
|
* | `core/judge` | policy: verdicts, intent, the docket a reader is handed |
|
|
20
20
|
* | `core/plan` | a composition as a value, and the identity derived from it |
|
|
21
21
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* everything else.
|
|
22
|
+
* Every name lives in exactly one of them; nothing is reachable from two paths.
|
|
23
|
+
* This entrypoint holds only what belongs to no group: the artifact a capture is
|
|
24
|
+
* written to.
|
|
26
25
|
*/
|
|
27
|
-
export * from './format/index.js';
|
|
28
|
-
export * from './rules/index.js';
|
|
29
|
-
export * from './compare/index.js';
|
|
30
|
-
export * from './attribute/index.js';
|
|
31
|
-
export * from './relate/index.js';
|
|
32
|
-
export * from './judge/index.js';
|
|
33
|
-
export * from './plan/index.js';
|
|
34
26
|
export * from './artifact.js';
|
|
35
27
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,cAAc,eAAe,CAAC","sourcesContent":["/**\n * `@variance-authority/core` — the format, the rules, and the verdict model.\n *\n * This package is pure data in, pure data out: no DOM, no React, no I/O, no\n * async. That is enforced by its `tsconfig` (`lib: ES2022` only), so \"the core\n * cannot peek at a live document\" is a compile error rather than a convention\n * (ADR-0001). Collectors extract; core normalizes and adjudicates.\n *\n * Seven groups, each its own entrypoint, in the order an answer travels through\n * them:\n *\n * | entrypoint | what it holds |\n * |---|---|\n * | `core/format` | what a subject *is*: capture, snapshot, document, identity |\n * | `core/rules` | the versioned opinions: allowlist, cascade, canonicalization |\n * | `core/compare` | two snapshots become deltas — and no verdict |\n * | `core/attribute` | a position becomes a component becomes a file |\n * | `core/relate` | what reaches what: the graph a change is traversed over |\n * | `core/judge` | policy: verdicts, intent, the docket a reader is handed |\n * | `core/plan` | a composition as a value, and the identity derived from it |\n *\n * Every name lives in exactly one of them; nothing is reachable from two paths.\n * This entrypoint holds only what belongs to no group: the artifact a capture is\n * written to.\n */\n\nexport * from './artifact.js';\n"]}
|
package/dist/relate/graph.d.ts
CHANGED
|
@@ -67,12 +67,12 @@ export type NodeKind = (typeof NODE_KINDS)[number];
|
|
|
67
67
|
/**
|
|
68
68
|
* Edge kinds, in id order.
|
|
69
69
|
*
|
|
70
|
-
* The distinctions are kept because they explain a finding
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
70
|
+
* The distinctions are kept because they explain a finding. One of them also
|
|
71
|
+
* decides a walk: `type` is erased by every compiler, so nothing behind it runs
|
|
72
|
+
* and nothing behind it renders, and the default traversal leaves it out
|
|
73
|
+
* (`RUNTIME_EDGES`). A caller whose question is about source rather than about a
|
|
74
|
+
* runtime — a docgen that reads prop types, a type-check gate — passes
|
|
75
|
+
* `EDGE_KINDS` and walks it.
|
|
76
76
|
*/
|
|
77
77
|
export declare const EDGE_KINDS: readonly [
|
|
78
78
|
/** `import x from './y'` — a value import. */
|
|
@@ -88,6 +88,11 @@ export declare const EDGE_KINDS: readonly [
|
|
|
88
88
|
/** A component to the file that declares it. */
|
|
89
89
|
'declared-in'];
|
|
90
90
|
export type EdgeKind = (typeof EDGE_KINDS)[number];
|
|
91
|
+
/**
|
|
92
|
+
* The edge kinds something at runtime can follow: every kind but `type`. The
|
|
93
|
+
* default for a reach and for a closure, and the list a caller widens from.
|
|
94
|
+
*/
|
|
95
|
+
export declare const RUNTIME_EDGES: readonly EdgeKind[];
|
|
91
96
|
export interface Node {
|
|
92
97
|
readonly kind: NodeKind;
|
|
93
98
|
/** Repository-relative for a file; the identifier for a component. */
|
|
@@ -143,6 +148,17 @@ export interface Relations {
|
|
|
143
148
|
readonly reasons: ReadonlyMap<NodeId, string>;
|
|
144
149
|
/** `keyOf` to id — the interning table, kept for lookup. */
|
|
145
150
|
readonly index: ReadonlyMap<string, NodeId>;
|
|
151
|
+
/**
|
|
152
|
+
* Per file, the files its run never reaches at any depth: what a mock
|
|
153
|
+
* replaces for the whole of a test's run.
|
|
154
|
+
*
|
|
155
|
+
* Carried with the graph rather than handed to each walk, because the graph
|
|
156
|
+
* crosses every seam a walk does and a table left behind at one of them is a
|
|
157
|
+
* selection that quietly widened. Empty for a graph nobody tainted. A walk
|
|
158
|
+
* against the arrows consults it: a file is moved by a change only when some
|
|
159
|
+
* trail from the change arrives without crossing one of that file's shadows.
|
|
160
|
+
*/
|
|
161
|
+
readonly shadows: ReadonlyMap<string, readonly string[]>;
|
|
146
162
|
}
|
|
147
163
|
/**
|
|
148
164
|
* The lookup key for a node.
|
|
@@ -158,7 +174,9 @@ export interface Relations {
|
|
|
158
174
|
* `tools/boundaries.check.ts` fails a build over it.
|
|
159
175
|
*/
|
|
160
176
|
export declare function keyOf(kind: NodeKind, name: string): string;
|
|
177
|
+
/** The id a node is known by in these relations, or `undefined` for a name the scan never met. */
|
|
161
178
|
export declare function idOf(relations: Relations, kind: NodeKind, name: string): NodeId | undefined;
|
|
179
|
+
/** The node an id names: its kind and name, or `undefined` past the end. */
|
|
162
180
|
export declare function nodeAt(relations: Relations, id: NodeId): Node | undefined;
|
|
163
181
|
/** Every node of one kind, as ids. Contiguous, because the order is kind-major. */
|
|
164
182
|
export declare function nodesOfKind(relations: Relations, kind: NodeKind): readonly NodeId[];
|
|
@@ -186,5 +204,7 @@ export declare function relationsOf(input: {
|
|
|
186
204
|
readonly unknown?: Iterable<Node | readonly [Node, string]>;
|
|
187
205
|
/** Nodes with no edges at all, which would otherwise be absent from the graph. */
|
|
188
206
|
readonly isolated?: Iterable<Node>;
|
|
207
|
+
/** Per file, the files its run never reaches; see {@link Relations.shadows}. */
|
|
208
|
+
readonly shadows?: ReadonlyMap<string, readonly string[]>;
|
|
189
209
|
}): Relations;
|
|
190
210
|
//# sourceMappingURL=graph.d.ts.map
|
package/dist/relate/graph.js
CHANGED
|
@@ -66,12 +66,12 @@ export const NODE_KINDS = ['file', 'component'];
|
|
|
66
66
|
/**
|
|
67
67
|
* Edge kinds, in id order.
|
|
68
68
|
*
|
|
69
|
-
* The distinctions are kept because they explain a finding
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
69
|
+
* The distinctions are kept because they explain a finding. One of them also
|
|
70
|
+
* decides a walk: `type` is erased by every compiler, so nothing behind it runs
|
|
71
|
+
* and nothing behind it renders, and the default traversal leaves it out
|
|
72
|
+
* (`RUNTIME_EDGES`). A caller whose question is about source rather than about a
|
|
73
|
+
* runtime — a docgen that reads prop types, a type-check gate — passes
|
|
74
|
+
* `EDGE_KINDS` and walks it.
|
|
75
75
|
*/
|
|
76
76
|
export const EDGE_KINDS = [
|
|
77
77
|
/** `import x from './y'` — a value import. */
|
|
@@ -87,6 +87,11 @@ export const EDGE_KINDS = [
|
|
|
87
87
|
/** A component to the file that declares it. */
|
|
88
88
|
'declared-in',
|
|
89
89
|
];
|
|
90
|
+
/**
|
|
91
|
+
* The edge kinds something at runtime can follow: every kind but `type`. The
|
|
92
|
+
* default for a reach and for a closure, and the list a caller widens from.
|
|
93
|
+
*/
|
|
94
|
+
export const RUNTIME_EDGES = EDGE_KINDS.filter((kind) => kind !== 'type');
|
|
90
95
|
/**
|
|
91
96
|
* The lookup key for a node.
|
|
92
97
|
*
|
|
@@ -103,9 +108,11 @@ export const EDGE_KINDS = [
|
|
|
103
108
|
export function keyOf(kind, name) {
|
|
104
109
|
return `${kind}:${name}`;
|
|
105
110
|
}
|
|
111
|
+
/** The id a node is known by in these relations, or `undefined` for a name the scan never met. */
|
|
106
112
|
export function idOf(relations, kind, name) {
|
|
107
113
|
return relations.index.get(keyOf(kind, name));
|
|
108
114
|
}
|
|
115
|
+
/** The node an id names: its kind and name, or `undefined` past the end. */
|
|
109
116
|
export function nodeAt(relations, id) {
|
|
110
117
|
const name = relations.names[id];
|
|
111
118
|
if (name === undefined)
|
|
@@ -176,7 +183,7 @@ export function relationsOf(input) {
|
|
|
176
183
|
if (because !== undefined)
|
|
177
184
|
reasons.set(id, because);
|
|
178
185
|
}
|
|
179
|
-
return { names, kinds, depends, dependents, unknown, reasons, index };
|
|
186
|
+
return { names, kinds, depends, dependents, unknown, reasons, index, shadows: input.shadows ?? new Map() };
|
|
180
187
|
}
|
|
181
188
|
/**
|
|
182
189
|
* Edges as ids, sorted and deduplicated.
|
package/dist/relate/graph.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","sourceRoot":"","sources":["../../src/relate/graph.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAEH,4EAA4E;AAC5E,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,MAAM,EAAE,WAAW,CAAU,CAAC;AAGzD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,8CAA8C;IAC9C,SAAS;IACT,+DAA+D;IAC/D,WAAW;IACX,4DAA4D;IAC5D,SAAS;IACT,uEAAuE;IACvE,MAAM;IACN,0EAA0E;IAC1E,OAAO;IACP,gDAAgD;IAChD,aAAa;CACL,CAAC;AAoEX;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,KAAK,CAAC,IAAc,EAAE,IAAY;IAChD,OAAO,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC;AAC3B,CAAC;AAED,MAAM,UAAU,IAAI,CAAC,SAAoB,EAAE,IAAc,EAAE,IAAY;IACrE,OA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,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QACjD,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC;QACrB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * What reaches what, stored so that asking is cheap.\n *\n * Every question this project asks about a change is a reachability question. A\n * diff names files; a subject is made of components; a component is declared in a\n * file that imports other files. *Which subjects could this diff have changed* is\n * one traversal of one graph, and the only reason it is not asked that way today\n * is that there has never been a graph to traverse.\n *\n * ## Why a structure rather than a `Map`\n *\n * The obvious shape is `Map<string, string[]>`, and it is wrong at the size this\n * runs at. A monorepo scan produces tens of thousands of files and several times\n * as many edges; the map holds one array object and one string copy per edge, and\n * a traversal chases a pointer for every step. What replaces it here is the\n * standard answer, and it is standard because nothing has beaten it:\n *\n * - **strings are interned once.** A node is an integer. Comparison is an integer\n * compare, membership is an index into a byte array, and a visited set is a\n * `Uint8Array` rather than a `Set<string>`.\n * - **edges are two typed arrays** in compressed-sparse-row form: `offset` says\n * where a node's row starts, `target` holds the rows end to end. One node's\n * edges are contiguous, so a traversal walks memory forwards instead of\n * following pointers into the heap.\n * - **both directions are materialized.** *What does this depend on* and *what\n * depends on this* are different questions, and a graph answering only the\n * first makes the second a whole-graph scan. The transpose is a counting sort —\n * one pass to count, one to place — so holding it costs `O(n + m)` once instead\n * of `O(n + m)` per query.\n *\n * ## Edges point at what a thing depends on\n *\n * One convention, held everywhere: **`A → B` means A depends on B**, so a change\n * in B may move A. Every affected-set question is therefore a walk against the\n * arrows, which is what `dependentsOf` does, and every *what would I have to read\n * to understand this* question is a walk along them.\n *\n * It decides the direction of the less obvious edges too. A component is\n * `declared-in` the file that declares it — the component depends on the file and\n * not the other way round — so editing that file reaches the component in the\n * same traversal that reaches every importer.\n *\n * ## Nodes are typed, because files are not the last kind\n *\n * This ships with two kinds and the join between them: a `file` graph built from\n * imports, and the `component` nodes the source index already knows how to find.\n * That is deliberate rather than incidental. A component relation — *`TodoFooter`\n * renders `Chip`* — is another edge kind between nodes of another kind in this\n * same structure, and\n * [`composition.md`](../../../../docs/composition.md) already computes exactly\n * that relation from what a run rendered. One graph means the static answer and\n * the rendered answer are joinable rather than adjacent.\n *\n * ## What it is not\n *\n * **Not a build graph.** It has no notion of a task, an output or a cache key,\n * and it does not know what an install produced. `nx` and `turbo` own that layer,\n * and what reads them reads their answer rather than competing with it.\n *\n * **Not a resolver.** Nothing here opens a file or knows what a specifier means.\n * `core` performs no I/O (ADR-0006); the records this folds are somebody else's\n * disk.\n */\n\n/** Node kinds, in id order. An id is an index into this, never the word. */\nexport const NODE_KINDS = ['file', 'component'] as const;\nexport type NodeKind = (typeof NODE_KINDS)[number];\n\n/**\n * Edge kinds, in id order.\n *\n * The distinctions are kept because they explain a finding, not because the\n * default traversal narrows on them. `type` is erased by every compiler and can\n * change no rendering, and it is still walked unless a caller says otherwise —\n * for the reason every rule in selection resolves the same way: a subject skipped\n * in error is a green run over an unwatched surface, and a subject observed in\n * error costs a collection.\n */\nexport const EDGE_KINDS = [\n /** `import x from './y'` — a value import. */\n 'imports',\n /** `export … from './y'` — an import that also republishes. */\n 'reexports',\n /** `import('./y')`, with a specifier that was a literal. */\n 'dynamic',\n /** `import type { T } from './y'` — erased before anything renders. */\n 'type',\n /** A stylesheet's `@import`, or a `url()` reaching a font or an image. */\n 'asset',\n /** A component to the file that declares it. */\n 'declared-in',\n] as const;\nexport type EdgeKind = (typeof EDGE_KINDS)[number];\n\nexport interface Node {\n readonly kind: NodeKind;\n /** Repository-relative for a file; the identifier for a component. */\n readonly name: string;\n}\n\nexport interface Relation {\n readonly from: Node;\n readonly to: Node;\n readonly kind: EdgeKind;\n}\n\n/** An index into `Relations.names`. Valid only against the graph it came from. */\nexport type NodeId = number;\n\n/**\n * One direction of the edge set, compressed-sparse-row.\n *\n * Node `i`'s edges are `target[offset[i] … offset[i + 1])`, and `kind[j]`\n * describes `target[j]`. `offset` holds one more entry than there are nodes, so\n * the last row needs no special case.\n */\nexport interface Adjacency {\n readonly offset: Uint32Array;\n readonly target: Uint32Array;\n readonly kind: Uint8Array;\n}\n\nexport interface Relations {\n /** Node names by id, ordered by kind and then by code unit. */\n readonly names: readonly string[];\n /** The `NODE_KINDS` index of each node. */\n readonly kinds: Uint8Array;\n\n /** What each node depends on. */\n readonly depends: Adjacency;\n /** What depends on each node — the transpose, materialized. */\n readonly dependents: Adjacency;\n\n /**\n * `1` where this node's outgoing edges could not be enumerated.\n *\n * A parse failure, a specifier that was not a literal, a file in a language\n * nothing here reads. It is *not* \"this file has no dependencies\", and the\n * difference is the whole safety argument: a file whose edges are unknown may\n * depend on anything that changed, so selection seeds the traversal with every\n * one of them (ADR-0002 — absent is not empty).\n */\n readonly unknown: Uint8Array;\n\n /**\n * Why, for each of those nodes, in the words whoever read the file used.\n *\n * Sparse — a repository the scan understands carries none of these — and kept\n * apart from the mask because the mask is what the inner loop tests and this is\n * what an operator reads. Without it, a run that observed forty subjects instead\n * of twelve can say *because eight files could not be read* and can never say\n * **which**, which is the difference between a fact and a work item.\n */\n readonly reasons: ReadonlyMap<NodeId, string>;\n\n /** `keyOf` to id — the interning table, kept for lookup. */\n readonly index: ReadonlyMap<string, NodeId>;\n}\n\n/**\n * The lookup key for a node.\n *\n * Runtime only; nothing serializes this, and no code parses it back — the\n * separator only has to be injective, and it is, because a kind is one of two\n * fixed words and neither contains a `:`. A name that contains one is therefore\n * fine.\n *\n * The obvious separator is a NUL, and it is the wrong one: a source file\n * carrying that byte stops being text to `grep`, `file` and `git diff`, which is\n * a search finding nothing looking exactly like a search that returned nothing.\n * `tools/boundaries.check.ts` fails a build over it.\n */\nexport function keyOf(kind: NodeKind, name: string): string {\n return `${kind}:${name}`;\n}\n\nexport function idOf(relations: Relations, kind: NodeKind, name: string): NodeId | undefined {\n return relations.index.get(keyOf(kind, name));\n}\n\nexport function nodeAt(relations: Relations, id: NodeId): Node | undefined {\n const name = relations.names[id];\n if (name === undefined) return undefined;\n return { kind: NODE_KINDS[relations.kinds[id]!]!, name };\n}\n\n/** Every node of one kind, as ids. Contiguous, because the order is kind-major. */\nexport function nodesOfKind(relations: Relations, kind: NodeKind): readonly NodeId[] {\n const wanted = NODE_KINDS.indexOf(kind);\n const found: NodeId[] = [];\n for (let id = 0; id < relations.kinds.length; id += 1) {\n if (relations.kinds[id] === wanted) found.push(id);\n }\n return found;\n}\n\n/**\n * Fold relations into the queryable form.\n *\n * Deterministic to the byte: nodes are ordered by kind and then by **code unit** —\n * never `localeCompare`, which would make an id a promise about `LANG` — and edges\n * are sorted and deduplicated, so two runs over the same records produce identical\n * arrays and a serialized graph is stable.\n *\n * `O(n log n + m log m)` for the two sorts and `O(n + m)` for everything else. The\n * transpose is a counting sort rather than a second pass over a map, which is why\n * both directions cost one build instead of one per query.\n */\nexport function relationsOf(input: {\n readonly relations: Iterable<Relation>;\n /**\n * Nodes whose outgoing edges are not fully known, and must be treated as such.\n *\n * A bare node says *this one is blind*. A pair says why, in whatever words the\n * reader of the file used — and the sentence is the half an operator can act on,\n * so it travels with the fact rather than being reconstructed from it.\n */\n readonly unknown?: Iterable<Node | readonly [Node, string]>;\n /** Nodes with no edges at all, which would otherwise be absent from the graph. */\n readonly isolated?: Iterable<Node>;\n}): Relations {\n const relations = [...input.relations];\n const unknownNodes = [...(input.unknown ?? [])].map((entry) =>\n Array.isArray(entry) ? entry : ([entry, undefined] as const),\n ) as readonly (readonly [Node, string | undefined])[];\n\n const seen = new Map<string, Node>();\n const see = (node: Node): void => {\n const key = keyOf(node.kind, node.name);\n if (!seen.has(key)) seen.set(key, node);\n };\n\n for (const relation of relations) {\n see(relation.from);\n see(relation.to);\n }\n for (const [node] of unknownNodes) see(node);\n for (const node of input.isolated ?? []) see(node);\n\n // Kind-major, then code unit. Kind-major keeps one kind's nodes contiguous,\n // which is what lets a caller filter to files without touching a string.\n const ordered = [...seen.values()].sort(\n (a, b) =>\n NODE_KINDS.indexOf(a.kind) - NODE_KINDS.indexOf(b.kind) ||\n (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n );\n\n const index = new Map<string, NodeId>();\n const names: string[] = Array.from<string>({ length: ordered.length });\n const kinds = new Uint8Array(ordered.length);\n\n for (const [id, node] of ordered.entries()) {\n index.set(keyOf(node.kind, node.name), id);\n names[id] = node.name;\n kinds[id] = NODE_KINDS.indexOf(node.kind);\n }\n\n const edges = sortedEdges(relations, index);\n const depends = adjacencyOf(edges, ordered.length, 'from');\n const dependents = adjacencyOf(edges, ordered.length, 'to');\n\n const unknown = new Uint8Array(ordered.length);\n const reasons = new Map<NodeId, string>();\n for (const [node, because] of unknownNodes) {\n const id = index.get(keyOf(node.kind, node.name));\n if (id === undefined) continue;\n\n unknown[id] = 1;\n if (because !== undefined) reasons.set(id, because);\n }\n\n return { names, kinds, depends, dependents, unknown, reasons, index };\n}\n\ninterface Edge {\n readonly from: NodeId;\n readonly to: NodeId;\n readonly kind: number;\n}\n\n/**\n * Edges as ids, sorted and deduplicated.\n *\n * Sorting the whole list once is what makes every row of *both* adjacencies\n * sorted without sorting any row: each fill walks the list in order, so a row\n * receives its targets in order. Two files related twice — a value import and a\n * type import — stay two edges, because the kinds differ and one of them explains\n * a finding the other does not.\n */\nfunction sortedEdges(\n relations: readonly Relation[],\n index: ReadonlyMap<string, NodeId>,\n): readonly Edge[] {\n const edges: Edge[] = [];\n\n for (const relation of relations) {\n const from = index.get(keyOf(relation.from.kind, relation.from.name));\n const to = index.get(keyOf(relation.to.kind, relation.to.name));\n if (from === undefined || to === undefined) continue;\n edges.push({ from, to, kind: EDGE_KINDS.indexOf(relation.kind) });\n }\n\n edges.sort((a, b) => a.from - b.from || a.to - b.to || a.kind - b.kind);\n\n const unique: Edge[] = [];\n for (const edge of edges) {\n const last = unique[unique.length - 1];\n const same =\n last !== undefined && last.from === edge.from && last.to === edge.to && last.kind === edge.kind;\n if (!same) unique.push(edge);\n }\n\n return unique;\n}\n\n/**\n * One direction, by counting sort.\n *\n * `by` names the endpoint a row is keyed on: `from` produces *what this depends\n * on*, `to` produces the transpose. Two passes — count the degrees, then place —\n * and no per-node array is ever allocated.\n */\nfunction adjacencyOf(edges: readonly Edge[], nodes: number, by: 'from' | 'to'): Adjacency {\n const offset = new Uint32Array(nodes + 1);\n for (const edge of edges) offset[edge[by] + 1] = offset[edge[by] + 1]! + 1;\n for (let id = 0; id < nodes; id += 1) offset[id + 1] = offset[id + 1]! + offset[id]!;\n\n const target = new Uint32Array(edges.length);\n const kind = new Uint8Array(edges.length);\n const cursor = Uint32Array.from(offset.subarray(0, nodes));\n\n for (const edge of edges) {\n const row = edge[by];\n const at = cursor[row]!;\n target[at] = by === 'from' ? edge.to : edge.from;\n kind[at] = edge.kind;\n cursor[row] = at + 1;\n }\n\n return { offset, target, kind };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph.js","sourceRoot":"","sources":["../../src/relate/graph.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAEH,4EAA4E;AAC5E,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,MAAM,EAAE,WAAW,CAAU,CAAC;AAGzD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,8CAA8C;IAC9C,SAAS;IACT,+DAA+D;IAC/D,WAAW;IACX,4DAA4D;IAC5D,SAAS;IACT,uEAAuE;IACvE,MAAM;IACN,0EAA0E;IAC1E,OAAO;IACP,gDAAgD;IAChD,aAAa;CACL,CAAC;AAGX;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAwB,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;AA+E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,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;IAE3D,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;QACrB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAE,CAAC;QACxB,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QACjD,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC;QACrB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * What reaches what, stored so that asking is cheap.\n *\n * Every question this project asks about a change is a reachability question. A\n * diff names files; a subject is made of components; a component is declared in a\n * file that imports other files. *Which subjects could this diff have changed* is\n * one traversal of one graph, and the only reason it is not asked that way today\n * is that there has never been a graph to traverse.\n *\n * ## Why a structure rather than a `Map`\n *\n * The obvious shape is `Map<string, string[]>`, and it is wrong at the size this\n * runs at. A monorepo scan produces tens of thousands of files and several times\n * as many edges; the map holds one array object and one string copy per edge, and\n * a traversal chases a pointer for every step. What replaces it here is the\n * standard answer, and it is standard because nothing has beaten it:\n *\n * - **strings are interned once.** A node is an integer. Comparison is an integer\n * compare, membership is an index into a byte array, and a visited set is a\n * `Uint8Array` rather than a `Set<string>`.\n * - **edges are two typed arrays** in compressed-sparse-row form: `offset` says\n * where a node's row starts, `target` holds the rows end to end. One node's\n * edges are contiguous, so a traversal walks memory forwards instead of\n * following pointers into the heap.\n * - **both directions are materialized.** *What does this depend on* and *what\n * depends on this* are different questions, and a graph answering only the\n * first makes the second a whole-graph scan. The transpose is a counting sort —\n * one pass to count, one to place — so holding it costs `O(n + m)` once instead\n * of `O(n + m)` per query.\n *\n * ## Edges point at what a thing depends on\n *\n * One convention, held everywhere: **`A → B` means A depends on B**, so a change\n * in B may move A. Every affected-set question is therefore a walk against the\n * arrows, which is what `dependentsOf` does, and every *what would I have to read\n * to understand this* question is a walk along them.\n *\n * It decides the direction of the less obvious edges too. A component is\n * `declared-in` the file that declares it — the component depends on the file and\n * not the other way round — so editing that file reaches the component in the\n * same traversal that reaches every importer.\n *\n * ## Nodes are typed, because files are not the last kind\n *\n * This ships with two kinds and the join between them: a `file` graph built from\n * imports, and the `component` nodes the source index already knows how to find.\n * That is deliberate rather than incidental. A component relation — *`TodoFooter`\n * renders `Chip`* — is another edge kind between nodes of another kind in this\n * same structure, and\n * [`composition.md`](../../../../docs/composition.md) already computes exactly\n * that relation from what a run rendered. One graph means the static answer and\n * the rendered answer are joinable rather than adjacent.\n *\n * ## What it is not\n *\n * **Not a build graph.** It has no notion of a task, an output or a cache key,\n * and it does not know what an install produced. `nx` and `turbo` own that layer,\n * and what reads them reads their answer rather than competing with it.\n *\n * **Not a resolver.** Nothing here opens a file or knows what a specifier means.\n * `core` performs no I/O (ADR-0006); the records this folds are somebody else's\n * disk.\n */\n\n/** Node kinds, in id order. An id is an index into this, never the word. */\nexport const NODE_KINDS = ['file', 'component'] as const;\nexport type NodeKind = (typeof NODE_KINDS)[number];\n\n/**\n * Edge kinds, in id order.\n *\n * The distinctions are kept because they explain a finding. One of them also\n * decides a walk: `type` is erased by every compiler, so nothing behind it runs\n * and nothing behind it renders, and the default traversal leaves it out\n * (`RUNTIME_EDGES`). A caller whose question is about source rather than about a\n * runtime — a docgen that reads prop types, a type-check gate — passes\n * `EDGE_KINDS` and walks it.\n */\nexport const EDGE_KINDS = [\n /** `import x from './y'` — a value import. */\n 'imports',\n /** `export … from './y'` — an import that also republishes. */\n 'reexports',\n /** `import('./y')`, with a specifier that was a literal. */\n 'dynamic',\n /** `import type { T } from './y'` — erased before anything renders. */\n 'type',\n /** A stylesheet's `@import`, or a `url()` reaching a font or an image. */\n 'asset',\n /** A component to the file that declares it. */\n 'declared-in',\n] as const;\nexport type EdgeKind = (typeof EDGE_KINDS)[number];\n\n/**\n * The edge kinds something at runtime can follow: every kind but `type`. The\n * default for a reach and for a closure, and the list a caller widens from.\n */\nexport const RUNTIME_EDGES: readonly EdgeKind[] = EDGE_KINDS.filter((kind) => kind !== 'type');\n\nexport interface Node {\n readonly kind: NodeKind;\n /** Repository-relative for a file; the identifier for a component. */\n readonly name: string;\n}\n\nexport interface Relation {\n readonly from: Node;\n readonly to: Node;\n readonly kind: EdgeKind;\n}\n\n/** An index into `Relations.names`. Valid only against the graph it came from. */\nexport type NodeId = number;\n\n/**\n * One direction of the edge set, compressed-sparse-row.\n *\n * Node `i`'s edges are `target[offset[i] … offset[i + 1])`, and `kind[j]`\n * describes `target[j]`. `offset` holds one more entry than there are nodes, so\n * the last row needs no special case.\n */\nexport interface Adjacency {\n readonly offset: Uint32Array;\n readonly target: Uint32Array;\n readonly kind: Uint8Array;\n}\n\nexport interface Relations {\n /** Node names by id, ordered by kind and then by code unit. */\n readonly names: readonly string[];\n /** The `NODE_KINDS` index of each node. */\n readonly kinds: Uint8Array;\n\n /** What each node depends on. */\n readonly depends: Adjacency;\n /** What depends on each node — the transpose, materialized. */\n readonly dependents: Adjacency;\n\n /**\n * `1` where this node's outgoing edges could not be enumerated.\n *\n * A parse failure, a specifier that was not a literal, a file in a language\n * nothing here reads. It is *not* \"this file has no dependencies\", and the\n * difference is the whole safety argument: a file whose edges are unknown may\n * depend on anything that changed, so selection seeds the traversal with every\n * one of them (ADR-0002 — absent is not empty).\n */\n readonly unknown: Uint8Array;\n\n /**\n * Why, for each of those nodes, in the words whoever read the file used.\n *\n * Sparse — a repository the scan understands carries none of these — and kept\n * apart from the mask because the mask is what the inner loop tests and this is\n * what an operator reads. Without it, a run that observed forty subjects instead\n * of twelve can say *because eight files could not be read* and can never say\n * **which**, which is the difference between a fact and a work item.\n */\n readonly reasons: ReadonlyMap<NodeId, string>;\n\n /** `keyOf` to id — the interning table, kept for lookup. */\n readonly index: ReadonlyMap<string, NodeId>;\n\n /**\n * Per file, the files its run never reaches at any depth: what a mock\n * replaces for the whole of a test's run.\n *\n * Carried with the graph rather than handed to each walk, because the graph\n * crosses every seam a walk does and a table left behind at one of them is a\n * selection that quietly widened. Empty for a graph nobody tainted. A walk\n * against the arrows consults it: a file is moved by a change only when some\n * trail from the change arrives without crossing one of that file's shadows.\n */\n readonly shadows: ReadonlyMap<string, readonly string[]>;\n}\n\n/**\n * The lookup key for a node.\n *\n * Runtime only; nothing serializes this, and no code parses it back — the\n * separator only has to be injective, and it is, because a kind is one of two\n * fixed words and neither contains a `:`. A name that contains one is therefore\n * fine.\n *\n * The obvious separator is a NUL, and it is the wrong one: a source file\n * carrying that byte stops being text to `grep`, `file` and `git diff`, which is\n * a search finding nothing looking exactly like a search that returned nothing.\n * `tools/boundaries.check.ts` fails a build over it.\n */\nexport function keyOf(kind: NodeKind, name: string): string {\n return `${kind}:${name}`;\n}\n\n/** The id a node is known by in these relations, or `undefined` for a name the scan never met. */\nexport function idOf(relations: Relations, kind: NodeKind, name: string): NodeId | undefined {\n return relations.index.get(keyOf(kind, name));\n}\n\n/** The node an id names: its kind and name, or `undefined` past the end. */\nexport function nodeAt(relations: Relations, id: NodeId): Node | undefined {\n const name = relations.names[id];\n if (name === undefined) return undefined;\n return { kind: NODE_KINDS[relations.kinds[id]!]!, name };\n}\n\n/** Every node of one kind, as ids. Contiguous, because the order is kind-major. */\nexport function nodesOfKind(relations: Relations, kind: NodeKind): readonly NodeId[] {\n const wanted = NODE_KINDS.indexOf(kind);\n const found: NodeId[] = [];\n for (let id = 0; id < relations.kinds.length; id += 1) {\n if (relations.kinds[id] === wanted) found.push(id);\n }\n return found;\n}\n\n/**\n * Fold relations into the queryable form.\n *\n * Deterministic to the byte: nodes are ordered by kind and then by **code unit** —\n * never `localeCompare`, which would make an id a promise about `LANG` — and edges\n * are sorted and deduplicated, so two runs over the same records produce identical\n * arrays and a serialized graph is stable.\n *\n * `O(n log n + m log m)` for the two sorts and `O(n + m)` for everything else. The\n * transpose is a counting sort rather than a second pass over a map, which is why\n * both directions cost one build instead of one per query.\n */\nexport function relationsOf(input: {\n readonly relations: Iterable<Relation>;\n /**\n * Nodes whose outgoing edges are not fully known, and must be treated as such.\n *\n * A bare node says *this one is blind*. A pair says why, in whatever words the\n * reader of the file used — and the sentence is the half an operator can act on,\n * so it travels with the fact rather than being reconstructed from it.\n */\n readonly unknown?: Iterable<Node | readonly [Node, string]>;\n /** Nodes with no edges at all, which would otherwise be absent from the graph. */\n readonly isolated?: Iterable<Node>;\n /** Per file, the files its run never reaches; see {@link Relations.shadows}. */\n readonly shadows?: ReadonlyMap<string, readonly string[]>;\n}): Relations {\n const relations = [...input.relations];\n const unknownNodes = [...(input.unknown ?? [])].map((entry) =>\n Array.isArray(entry) ? entry : ([entry, undefined] as const),\n ) as readonly (readonly [Node, string | undefined])[];\n\n const seen = new Map<string, Node>();\n const see = (node: Node): void => {\n const key = keyOf(node.kind, node.name);\n if (!seen.has(key)) seen.set(key, node);\n };\n\n for (const relation of relations) {\n see(relation.from);\n see(relation.to);\n }\n for (const [node] of unknownNodes) see(node);\n for (const node of input.isolated ?? []) see(node);\n\n // Kind-major, then code unit. Kind-major keeps one kind's nodes contiguous,\n // which is what lets a caller filter to files without touching a string.\n const ordered = [...seen.values()].sort(\n (a, b) =>\n NODE_KINDS.indexOf(a.kind) - NODE_KINDS.indexOf(b.kind) ||\n (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n );\n\n const index = new Map<string, NodeId>();\n const names: string[] = Array.from<string>({ length: ordered.length });\n const kinds = new Uint8Array(ordered.length);\n\n for (const [id, node] of ordered.entries()) {\n index.set(keyOf(node.kind, node.name), id);\n names[id] = node.name;\n kinds[id] = NODE_KINDS.indexOf(node.kind);\n }\n\n const edges = sortedEdges(relations, index);\n const depends = adjacencyOf(edges, ordered.length, 'from');\n const dependents = adjacencyOf(edges, ordered.length, 'to');\n\n const unknown = new Uint8Array(ordered.length);\n const reasons = new Map<NodeId, string>();\n for (const [node, because] of unknownNodes) {\n const id = index.get(keyOf(node.kind, node.name));\n if (id === undefined) continue;\n\n unknown[id] = 1;\n if (because !== undefined) reasons.set(id, because);\n }\n\n return { names, kinds, depends, dependents, unknown, reasons, index, shadows: input.shadows ?? new Map() };\n}\n\ninterface Edge {\n readonly from: NodeId;\n readonly to: NodeId;\n readonly kind: number;\n}\n\n/**\n * Edges as ids, sorted and deduplicated.\n *\n * Sorting the whole list once is what makes every row of *both* adjacencies\n * sorted without sorting any row: each fill walks the list in order, so a row\n * receives its targets in order. Two files related twice — a value import and a\n * type import — stay two edges, because the kinds differ and one of them explains\n * a finding the other does not.\n */\nfunction sortedEdges(\n relations: readonly Relation[],\n index: ReadonlyMap<string, NodeId>,\n): readonly Edge[] {\n const edges: Edge[] = [];\n\n for (const relation of relations) {\n const from = index.get(keyOf(relation.from.kind, relation.from.name));\n const to = index.get(keyOf(relation.to.kind, relation.to.name));\n if (from === undefined || to === undefined) continue;\n edges.push({ from, to, kind: EDGE_KINDS.indexOf(relation.kind) });\n }\n\n edges.sort((a, b) => a.from - b.from || a.to - b.to || a.kind - b.kind);\n\n const unique: Edge[] = [];\n for (const edge of edges) {\n const last = unique[unique.length - 1];\n const same =\n last !== undefined && last.from === edge.from && last.to === edge.to && last.kind === edge.kind;\n if (!same) unique.push(edge);\n }\n\n return unique;\n}\n\n/**\n * One direction, by counting sort.\n *\n * `by` names the endpoint a row is keyed on: `from` produces *what this depends\n * on*, `to` produces the transpose. Two passes — count the degrees, then place —\n * and no per-node array is ever allocated.\n */\nfunction adjacencyOf(edges: readonly Edge[], nodes: number, by: 'from' | 'to'): Adjacency {\n const offset = new Uint32Array(nodes + 1);\n for (const edge of edges) offset[edge[by] + 1] = offset[edge[by] + 1]! + 1;\n for (let id = 0; id < nodes; id += 1) offset[id + 1] = offset[id + 1]! + offset[id]!;\n\n const target = new Uint32Array(edges.length);\n const kind = new Uint8Array(edges.length);\n const cursor = Uint32Array.from(offset.subarray(0, nodes));\n\n for (const edge of edges) {\n const row = edge[by];\n const at = cursor[row]!;\n target[at] = by === 'from' ? edge.to : edge.from;\n kind[at] = edge.kind;\n cursor[row] = at + 1;\n }\n\n return { offset, target, kind };\n}\n"]}
|
package/dist/relate/index.d.ts
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
*
|
|
10
10
|
* See [`docs/selecting.md`](../../../../docs/selecting.md) for what it is for.
|
|
11
11
|
*/
|
|
12
|
-
export { EDGE_KINDS, NODE_KINDS, idOf, keyOf, nodeAt, nodesOfKind, relationsOf, type Adjacency, type EdgeKind, type Node, type NodeId, type NodeKind, type Relation, type Relations, } from './graph.js';
|
|
12
|
+
export { EDGE_KINDS, NODE_KINDS, RUNTIME_EDGES, idOf, keyOf, nodeAt, nodesOfKind, relationsOf, type Adjacency, type EdgeKind, type Node, type NodeId, type NodeKind, type Relation, type Relations, } from './graph.js';
|
|
13
13
|
export { dependenciesOf, dependentsOf, trailOf, type Reach, type ReachOptions, } from './reach.js';
|
|
14
14
|
export { CLOSURE_EDGES, closureOf, driftedBetween, type Closure, type ClosureInput, type Drift, } from './merkle.js';
|
|
15
|
-
export { explain, movedBy, relationsOfFiles, type FileEdge, type FileRecord, type Hole, type Reached, } from './records.js';
|
|
15
|
+
export { explain, movedBy, relationsOfFiles, type FileEdge, type FileRecord, type Hole, type MovedOptions, type RelationsOptions, type Reached, } from './records.js';
|
|
16
16
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/relate/index.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*
|
|
10
10
|
* See [`docs/selecting.md`](../../../../docs/selecting.md) for what it is for.
|
|
11
11
|
*/
|
|
12
|
-
export { EDGE_KINDS, NODE_KINDS, idOf, keyOf, nodeAt, nodesOfKind, relationsOf, } from './graph.js';
|
|
12
|
+
export { EDGE_KINDS, NODE_KINDS, RUNTIME_EDGES, idOf, keyOf, nodeAt, nodesOfKind, relationsOf, } from './graph.js';
|
|
13
13
|
export { dependenciesOf, dependentsOf, trailOf, } from './reach.js';
|
|
14
14
|
export { CLOSURE_EDGES, closureOf, driftedBetween, } from './merkle.js';
|
|
15
15
|
export { explain, movedBy, relationsOfFiles, } from './records.js';
|
package/dist/relate/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/relate/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,UAAU,EACV,UAAU,EACV,IAAI,EACJ,KAAK,EACL,MAAM,EACN,WAAW,EACX,WAAW,GAQZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,cAAc,EACd,YAAY,EACZ,OAAO,GAGR,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,aAAa,EACb,SAAS,EACT,cAAc,GAIf,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,OAAO,EACP,OAAO,EACP,gBAAgB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/relate/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,UAAU,EACV,UAAU,EACV,aAAa,EACb,IAAI,EACJ,KAAK,EACL,MAAM,EACN,WAAW,EACX,WAAW,GAQZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,cAAc,EACd,YAAY,EACZ,OAAO,GAGR,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,aAAa,EACb,SAAS,EACT,cAAc,GAIf,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,OAAO,EACP,OAAO,EACP,gBAAgB,GAOjB,MAAM,cAAc,CAAC","sourcesContent":["/**\n * `core/relate` — what reaches what.\n *\n * A typed, interned, bidirectional graph and the two traversals over it, plus the\n * file-shaped record the scanner produces and the fold that turns a pile of them\n * into the structure. No I/O, no parser, no resolver: the expensive half belongs\n * to whoever owns the disk, and this is the half that has to be fast and has to\n * be provable without one.\n *\n * See [`docs/selecting.md`](../../../../docs/selecting.md) for what it is for.\n */\n\nexport {\n EDGE_KINDS,\n NODE_KINDS,\n RUNTIME_EDGES,\n idOf,\n keyOf,\n nodeAt,\n nodesOfKind,\n relationsOf,\n type Adjacency,\n type EdgeKind,\n type Node,\n type NodeId,\n type NodeKind,\n type Relation,\n type Relations,\n} from './graph.js';\n\nexport {\n dependenciesOf,\n dependentsOf,\n trailOf,\n type Reach,\n type ReachOptions,\n} from './reach.js';\n\nexport {\n CLOSURE_EDGES,\n closureOf,\n driftedBetween,\n type Closure,\n type ClosureInput,\n type Drift,\n} from './merkle.js';\n\nexport {\n explain,\n movedBy,\n relationsOfFiles,\n type FileEdge,\n type FileRecord,\n type Hole,\n type MovedOptions,\n type RelationsOptions,\n type Reached,\n} from './records.js';\n"]}
|
package/dist/relate/merkle.d.ts
CHANGED
|
@@ -100,11 +100,14 @@ export declare function driftedBetween(before: Closure, after: Closure): Drift;
|
|
|
100
100
|
* The edge kinds a closure walks when the caller does not say.
|
|
101
101
|
*
|
|
102
102
|
* Listed rather than derived from `EDGE_KINDS`, and the difference is the whole
|
|
103
|
-
* point. A digest is a claim about *which inputs* were folded, so
|
|
104
|
-
* fold silently changes every digest that exists — one
|
|
105
|
-
* next run finds nothing it can prove unchanged and re-observes
|
|
106
|
-
* while reporting a successful narrowing.
|
|
107
|
-
* cost, and it should read like one.
|
|
103
|
+
* point. A digest is a claim about *which inputs* were folded, so changing the
|
|
104
|
+
* fold silently changes every digest that exists — one edge kind added or
|
|
105
|
+
* removed, and the next run finds nothing it can prove unchanged and re-observes
|
|
106
|
+
* the entire suite while reporting a successful narrowing. Changing this list is
|
|
107
|
+
* a decision with a cost, and it should read like one.
|
|
108
|
+
*
|
|
109
|
+
* `type` is not in it: a type-only import is erased before a render, so a change
|
|
110
|
+
* behind one is not an input the render folded.
|
|
108
111
|
*/
|
|
109
112
|
export declare const CLOSURE_EDGES: readonly EdgeKind[];
|
|
110
113
|
//# sourceMappingURL=merkle.d.ts.map
|
package/dist/relate/merkle.js
CHANGED
|
@@ -216,17 +216,19 @@ function condense(relations, allowed) {
|
|
|
216
216
|
* The edge kinds a closure walks when the caller does not say.
|
|
217
217
|
*
|
|
218
218
|
* Listed rather than derived from `EDGE_KINDS`, and the difference is the whole
|
|
219
|
-
* point. A digest is a claim about *which inputs* were folded, so
|
|
220
|
-
* fold silently changes every digest that exists — one
|
|
221
|
-
* next run finds nothing it can prove unchanged and re-observes
|
|
222
|
-
* while reporting a successful narrowing.
|
|
223
|
-
* cost, and it should read like one.
|
|
219
|
+
* point. A digest is a claim about *which inputs* were folded, so changing the
|
|
220
|
+
* fold silently changes every digest that exists — one edge kind added or
|
|
221
|
+
* removed, and the next run finds nothing it can prove unchanged and re-observes
|
|
222
|
+
* the entire suite while reporting a successful narrowing. Changing this list is
|
|
223
|
+
* a decision with a cost, and it should read like one.
|
|
224
|
+
*
|
|
225
|
+
* `type` is not in it: a type-only import is erased before a render, so a change
|
|
226
|
+
* behind one is not an input the render folded.
|
|
224
227
|
*/
|
|
225
228
|
export const CLOSURE_EDGES = [
|
|
226
229
|
'imports',
|
|
227
230
|
'reexports',
|
|
228
231
|
'dynamic',
|
|
229
|
-
'type',
|
|
230
232
|
'asset',
|
|
231
233
|
'declared-in',
|
|
232
234
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merkle.js","sourceRoot":"","sources":["../../src/relate/merkle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EACL,UAAU,EACV,UAAU,EACV,KAAK,GAIN,MAAM,YAAY,CAAC;AA+BpB;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,KAAmB;IAC3C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AAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,aAAa,GAAwB;IAChD,SAAS;IACT,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,aAAa;CACd,CAAC;AAEF,8DAA8D;AAC9D,SAAS,YAAY,CAAC,OAAuC;IAC3D,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAElD,KAAK,MAAM,IAAI,IAAI,OAAO,IAAI,aAAa,EAAE,CAAC;QAC5C,MAAM,EAAE,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,UAAU,CAAC,CAAS,EAAE,CAAS;IACtC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * The graph, hashed the way a build system hashes an action's inputs.\n *\n * Reachability answers *what could this diff have moved*. It needs a diff, which\n * means it needs `git`, a ref that exists, a checkout deep enough to contain it,\n * and the assumption that the ref is where this branch actually diverged. Every\n * one of those is a thing CI gets wrong, and each failure narrows a run.\n *\n * A Merkle digest asks a different question and needs none of them: **is this\n * subject's entire input closure byte-identical to the one that produced the\n * baseline?** One digest per node, over the node's own content and the digests of\n * everything it rests on — the same construction `bazel` uses to key an action,\n * and the same idea as this project's own content addressing, applied one level\n * out from the document to the source that produced it.\n *\n * What the difference buys:\n *\n * | situation | reachability | closure digest |\n * |---|---|---|\n * | a change, then a revert | both commits are in the diff, so it widens | identical digest, nothing runs |\n * | rebase, squash, branch switch | the merge base moves and the diff with it | unaffected — no ref is consulted |\n * | a shallow clone with no merge base | cannot answer; runs everything | unaffected |\n * | a dependency changed two hops away | reached, and observed | different digest, and observed |\n * | *why* a subject is being observed | a chain of files | a digest that differs |\n *\n * Neither replaces the other. The trail is the explanation, and the digest is the\n * proof; a run wants the digest to decide and the trail to justify.\n *\n * ## Cycles\n *\n * A dependency graph has them and a Merkle tree cannot. Strongly connected\n * components are condensed and hashed as a unit, so every file in a cycle carries\n * the same digest — which is exactly the truth about a cycle: no member of one can\n * be called unchanged while another moved.\n *\n * ## The digest that must never lie\n *\n * A digest says *these inputs are the same*. A file whose content was not supplied,\n * or whose own imports could not be read, breaks that claim — its closure may have\n * moved with no digest in this structure changing. Those nodes are marked\n * **volatile**, the mark propagates to everything that rests on them, and a\n * volatile node is treated as changed however its digest compares. A cache that\n * cannot be trusted must not be silently trusted.\n */\n\nimport { digestCombine, digestString, type Digest } from '../format/hash.js';\nimport {\n EDGE_KINDS,\n NODE_KINDS,\n keyOf,\n type EdgeKind,\n type NodeId,\n type Relations,\n} from './graph.js';\n\nexport interface ClosureInput {\n readonly relations: Relations;\n\n /**\n * Content digest per file, keyed by the file's path.\n *\n * A file with no entry is volatile: nothing here can tell whether it moved.\n * Component nodes take no entry — a component has no bytes of its own, and its\n * content is the file that declares it, which it already depends on.\n */\n readonly content: ReadonlyMap<string, Digest>;\n\n /** Restrict the closure to these edge kinds. Every kind by default. */\n readonly through?: Iterable<EdgeKind>;\n}\n\nexport interface Closure {\n /** `keyOf(kind, name)` → the digest of everything that node rests on. */\n readonly digests: ReadonlyMap<string, Digest>;\n\n /**\n * Nodes whose digest cannot prove sameness, and everything resting on them.\n *\n * Not an error. It is the honest half of the answer, and a caller that ignores\n * it converts a missing input into a subject nobody observed.\n */\n readonly volatile: ReadonlySet<string>;\n}\n\n/**\n * Hash every node over its own content and its whole dependency closure.\n *\n * One pass of Tarjan's algorithm and one pass over the components it emits, which\n * is `O(n + m)` — the same cost as the traversal next door, for an answer that\n * survives a rebase.\n */\nexport function closureOf(input: ClosureInput): Closure {\n const { relations, content } = input;\n const allowed = allowedKinds(input.through);\n const count = relations.names.length;\n\n const { component, order } = condense(relations, allowed);\n const digests = new Map<string, Digest>();\n const unstable = new Set<string>();\n\n // One digest per component, so every member of a cycle carries the same one.\n const byComponent: Digest[] = [];\n const shakyComponent: boolean[] = [];\n\n // Tarjan emits a component only after everything it can reach, so a dependency\n // digest is always already computed by the time it is read here.\n for (const [id, members] of order.entries()) {\n const terms: string[] = [];\n const outward = new Set<string>();\n let shaky = false;\n\n for (const node of members) {\n const kind = NODE_KINDS[relations.kinds[node]!]!;\n const name = relations.names[node]!;\n const own = kind === 'file' ? content.get(name) : SETTLED;\n\n if (own === undefined || relations.unknown[node] === 1) shaky = true;\n terms.push(`${kind}\\u0000${name}\\u0000${own ?? UNREAD}`);\n\n const { offset, target, kind: edgeKind } = relations.depends;\n for (let at = offset[node]!; at < offset[node + 1]!; at += 1) {\n if (allowed[edgeKind[at]!] !== 1) continue;\n\n const other = target[at]!;\n if (component[other] === id) continue;\n\n outward.add(`${EDGE_KINDS[edgeKind[at]!]!}\\u0000${byComponent[component[other]!]!}`);\n if (shakyComponent[component[other]!] === true) shaky = true;\n }\n }\n\n byComponent.push(\n digestCombine('relate.closure', [\n digestString([...terms].sort(byCodeUnit).join('\u0001')),\n digestString([...outward].sort(byCodeUnit).join('\u0001')),\n ]),\n );\n shakyComponent.push(shaky);\n }\n\n for (let node = 0; node < count; node += 1) {\n const key = keyOf(NODE_KINDS[relations.kinds[node]!]!, relations.names[node]!);\n digests.set(key, byComponent[component[node]!]!);\n if (shakyComponent[component[node]!] === true) unstable.add(key);\n }\n\n return { digests, volatile: unstable };\n}\n\n/** The term a node with content contributes when the content is not known. */\nconst UNREAD = '(unread)';\n\n/** The term a node that has no content of its own contributes. */\nconst SETTLED = '(declared)';\n\nexport interface Drift {\n /** Node keys whose closure is not provably the one it was. */\n readonly changed: readonly string[];\n /** The file paths among them. */\n readonly files: readonly string[];\n /** The component names among them. */\n readonly components: readonly string[];\n /** Node keys the earlier closure held and this one does not. */\n readonly gone: readonly string[];\n}\n\n/**\n * What moved between two closures, without consulting a repository.\n *\n * Three ways a node lands in `changed`, and only the first is a difference: its\n * digest differs, it is **new**, or it is **volatile** — the last because a node\n * whose inputs were not fully read has a digest that can match by accident, and a\n * selector that believed it would skip a subject on the strength of a hash over\n * bytes nobody hashed.\n */\nexport function driftedBetween(before: Closure, after: Closure): Drift {\n const changed: string[] = [];\n\n for (const [key, digest] of after.digests) {\n const was = before.digests.get(key);\n if (was === digest && !after.volatile.has(key) && !before.volatile.has(key)) continue;\n changed.push(key);\n }\n\n const gone = [...before.digests.keys()].filter((key) => !after.digests.has(key));\n\n return {\n changed: changed.sort(byCodeUnit),\n files: named(changed, 'file'),\n components: named(changed, 'component'),\n gone: gone.sort(byCodeUnit),\n };\n}\n\nfunction named(keys: readonly string[], kind: 'file' | 'component'): readonly string[] {\n const prefix = `${kind}:`;\n\n return keys\n .filter((key) => key.startsWith(prefix))\n .map((key) => key.slice(prefix.length))\n .sort(byCodeUnit);\n}\n\ninterface Condensation {\n /** Component index per node. */\n readonly component: Int32Array;\n /** Components in emission order — every one after everything it reaches. */\n readonly order: readonly (readonly NodeId[])[];\n}\n\n/**\n * Tarjan's strongly connected components, iteratively.\n *\n * Iterative because the recursion depth is the longest dependency chain in the\n * repository, and a deep monorepo would overflow a call stack on a structure whose\n * whole point is to be cheap. The emission order is the useful half: a component\n * appears only once everything it can reach has, which is the order a Merkle fold\n * needs and costs nothing extra to get.\n */\nfunction condense(relations: Relations, allowed: Uint8Array): Condensation {\n const count = relations.names.length;\n const { offset, target, kind } = relations.depends;\n\n const index = new Int32Array(count).fill(-1);\n const low = new Int32Array(count);\n const onStack = new Uint8Array(count);\n const component = new Int32Array(count).fill(-1);\n\n const pending: NodeId[] = [];\n const order: NodeId[][] = [];\n\n // Frames as two parallel arrays: the node, and how far through its edges it is.\n const frameNode: number[] = [];\n const frameEdge: number[] = [];\n let counter = 0;\n\n for (let root = 0; root < count; root += 1) {\n if (index[root] !== -1) continue;\n\n index[root] = counter;\n low[root] = counter;\n counter += 1;\n pending.push(root);\n onStack[root] = 1;\n frameNode.push(root);\n frameEdge.push(offset[root]!);\n\n while (frameNode.length > 0) {\n const node = frameNode[frameNode.length - 1]!;\n const at = frameEdge[frameEdge.length - 1]!;\n\n if (at < offset[node + 1]!) {\n frameEdge[frameEdge.length - 1] = at + 1;\n if (allowed[kind[at]!] !== 1) continue;\n\n const next = target[at]!;\n if (index[next] === -1) {\n index[next] = counter;\n low[next] = counter;\n counter += 1;\n pending.push(next);\n onStack[next] = 1;\n frameNode.push(next);\n frameEdge.push(offset[next]!);\n } else if (onStack[next] === 1) {\n if (index[next]! < low[node]!) low[node] = index[next]!;\n }\n continue;\n }\n\n frameNode.pop();\n frameEdge.pop();\n\n const parent = frameNode[frameNode.length - 1];\n if (parent !== undefined && low[node]! < low[parent]!) low[parent] = low[node]!;\n\n if (low[node] !== index[node]) continue;\n\n const members: NodeId[] = [];\n for (;;) {\n const member = pending.pop()!;\n onStack[member] = 0;\n component[member] = order.length;\n members.push(member);\n if (member === node) break;\n }\n order.push(members.sort((a, b) => a - b));\n }\n }\n\n return { component, order };\n}\n\n/**\n * The edge kinds a closure walks when the caller does not say.\n *\n * Listed rather than derived from `EDGE_KINDS`, and the difference is the whole\n * point. A digest is a claim about *which inputs* were folded, so widening the\n * fold silently changes every digest that exists — one added edge kind, and the\n * next run finds nothing it can prove unchanged and re-observes the entire suite\n * while reporting a successful narrowing. Adding a kind here is a decision with a\n * cost, and it should read like one.\n */\nexport const CLOSURE_EDGES: readonly EdgeKind[] = [\n 'imports',\n 'reexports',\n 'dynamic',\n 'type',\n 'asset',\n 'declared-in',\n];\n\n/** Edge kinds as a lookup, so the inner loop tests a byte. */\nfunction allowedKinds(through: Iterable<EdgeKind> | undefined): Uint8Array {\n const allowed = new Uint8Array(EDGE_KINDS.length);\n\n for (const kind of through ?? CLOSURE_EDGES) {\n const at = EDGE_KINDS.indexOf(kind);\n if (at !== -1) allowed[at] = 1;\n }\n\n return allowed;\n}\n\nfunction byCodeUnit(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"merkle.js","sourceRoot":"","sources":["../../src/relate/merkle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EACL,UAAU,EACV,UAAU,EACV,KAAK,GAIN,MAAM,YAAY,CAAC;AA+BpB;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,KAAmB;IAC3C,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACrC,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC;IAErC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IAEnC,6EAA6E;IAC7E,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,MAAM,cAAc,GAAc,EAAE,CAAC;IAErC,+EAA+E;IAC/E,iEAAiE;IACjE,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;QAC5C,MAAM,KAAK,GA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,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,UAAU,CAAC,CAAS,EAAE,CAAS;IACtC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * The graph, hashed the way a build system hashes an action's inputs.\n *\n * Reachability answers *what could this diff have moved*. It needs a diff, which\n * means it needs `git`, a ref that exists, a checkout deep enough to contain it,\n * and the assumption that the ref is where this branch actually diverged. Every\n * one of those is a thing CI gets wrong, and each failure narrows a run.\n *\n * A Merkle digest asks a different question and needs none of them: **is this\n * subject's entire input closure byte-identical to the one that produced the\n * baseline?** One digest per node, over the node's own content and the digests of\n * everything it rests on — the same construction `bazel` uses to key an action,\n * and the same idea as this project's own content addressing, applied one level\n * out from the document to the source that produced it.\n *\n * What the difference buys:\n *\n * | situation | reachability | closure digest |\n * |---|---|---|\n * | a change, then a revert | both commits are in the diff, so it widens | identical digest, nothing runs |\n * | rebase, squash, branch switch | the merge base moves and the diff with it | unaffected — no ref is consulted |\n * | a shallow clone with no merge base | cannot answer; runs everything | unaffected |\n * | a dependency changed two hops away | reached, and observed | different digest, and observed |\n * | *why* a subject is being observed | a chain of files | a digest that differs |\n *\n * Neither replaces the other. The trail is the explanation, and the digest is the\n * proof; a run wants the digest to decide and the trail to justify.\n *\n * ## Cycles\n *\n * A dependency graph has them and a Merkle tree cannot. Strongly connected\n * components are condensed and hashed as a unit, so every file in a cycle carries\n * the same digest — which is exactly the truth about a cycle: no member of one can\n * be called unchanged while another moved.\n *\n * ## The digest that must never lie\n *\n * A digest says *these inputs are the same*. A file whose content was not supplied,\n * or whose own imports could not be read, breaks that claim — its closure may have\n * moved with no digest in this structure changing. Those nodes are marked\n * **volatile**, the mark propagates to everything that rests on them, and a\n * volatile node is treated as changed however its digest compares. A cache that\n * cannot be trusted must not be silently trusted.\n */\n\nimport { digestCombine, digestString, type Digest } from '../format/hash.js';\nimport {\n EDGE_KINDS,\n NODE_KINDS,\n keyOf,\n type EdgeKind,\n type NodeId,\n type Relations,\n} from './graph.js';\n\nexport interface ClosureInput {\n readonly relations: Relations;\n\n /**\n * Content digest per file, keyed by the file's path.\n *\n * A file with no entry is volatile: nothing here can tell whether it moved.\n * Component nodes take no entry — a component has no bytes of its own, and its\n * content is the file that declares it, which it already depends on.\n */\n readonly content: ReadonlyMap<string, Digest>;\n\n /** Restrict the closure to these edge kinds. Every kind by default. */\n readonly through?: Iterable<EdgeKind>;\n}\n\nexport interface Closure {\n /** `keyOf(kind, name)` → the digest of everything that node rests on. */\n readonly digests: ReadonlyMap<string, Digest>;\n\n /**\n * Nodes whose digest cannot prove sameness, and everything resting on them.\n *\n * Not an error. It is the honest half of the answer, and a caller that ignores\n * it converts a missing input into a subject nobody observed.\n */\n readonly volatile: ReadonlySet<string>;\n}\n\n/**\n * Hash every node over its own content and its whole dependency closure.\n *\n * One pass of Tarjan's algorithm and one pass over the components it emits, which\n * is `O(n + m)` — the same cost as the traversal next door, for an answer that\n * survives a rebase.\n */\nexport function closureOf(input: ClosureInput): Closure {\n const { relations, content } = input;\n const allowed = allowedKinds(input.through);\n const count = relations.names.length;\n\n const { component, order } = condense(relations, allowed);\n const digests = new Map<string, Digest>();\n const unstable = new Set<string>();\n\n // One digest per component, so every member of a cycle carries the same one.\n const byComponent: Digest[] = [];\n const shakyComponent: boolean[] = [];\n\n // Tarjan emits a component only after everything it can reach, so a dependency\n // digest is always already computed by the time it is read here.\n for (const [id, members] of order.entries()) {\n const terms: string[] = [];\n const outward = new Set<string>();\n let shaky = false;\n\n for (const node of members) {\n const kind = NODE_KINDS[relations.kinds[node]!]!;\n const name = relations.names[node]!;\n const own = kind === 'file' ? content.get(name) : SETTLED;\n\n if (own === undefined || relations.unknown[node] === 1) shaky = true;\n terms.push(`${kind}\\u0000${name}\\u0000${own ?? UNREAD}`);\n\n const { offset, target, kind: edgeKind } = relations.depends;\n for (let at = offset[node]!; at < offset[node + 1]!; at += 1) {\n if (allowed[edgeKind[at]!] !== 1) continue;\n\n const other = target[at]!;\n if (component[other] === id) continue;\n\n outward.add(`${EDGE_KINDS[edgeKind[at]!]!}\\u0000${byComponent[component[other]!]!}`);\n if (shakyComponent[component[other]!] === true) shaky = true;\n }\n }\n\n byComponent.push(\n digestCombine('relate.closure', [\n digestString([...terms].sort(byCodeUnit).join('\u0001')),\n digestString([...outward].sort(byCodeUnit).join('\u0001')),\n ]),\n );\n shakyComponent.push(shaky);\n }\n\n for (let node = 0; node < count; node += 1) {\n const key = keyOf(NODE_KINDS[relations.kinds[node]!]!, relations.names[node]!);\n digests.set(key, byComponent[component[node]!]!);\n if (shakyComponent[component[node]!] === true) unstable.add(key);\n }\n\n return { digests, volatile: unstable };\n}\n\n/** The term a node with content contributes when the content is not known. */\nconst UNREAD = '(unread)';\n\n/** The term a node that has no content of its own contributes. */\nconst SETTLED = '(declared)';\n\nexport interface Drift {\n /** Node keys whose closure is not provably the one it was. */\n readonly changed: readonly string[];\n /** The file paths among them. */\n readonly files: readonly string[];\n /** The component names among them. */\n readonly components: readonly string[];\n /** Node keys the earlier closure held and this one does not. */\n readonly gone: readonly string[];\n}\n\n/**\n * What moved between two closures, without consulting a repository.\n *\n * Three ways a node lands in `changed`, and only the first is a difference: its\n * digest differs, it is **new**, or it is **volatile** — the last because a node\n * whose inputs were not fully read has a digest that can match by accident, and a\n * selector that believed it would skip a subject on the strength of a hash over\n * bytes nobody hashed.\n */\nexport function driftedBetween(before: Closure, after: Closure): Drift {\n const changed: string[] = [];\n\n for (const [key, digest] of after.digests) {\n const was = before.digests.get(key);\n if (was === digest && !after.volatile.has(key) && !before.volatile.has(key)) continue;\n changed.push(key);\n }\n\n const gone = [...before.digests.keys()].filter((key) => !after.digests.has(key));\n\n return {\n changed: changed.sort(byCodeUnit),\n files: named(changed, 'file'),\n components: named(changed, 'component'),\n gone: gone.sort(byCodeUnit),\n };\n}\n\nfunction named(keys: readonly string[], kind: 'file' | 'component'): readonly string[] {\n const prefix = `${kind}:`;\n\n return keys\n .filter((key) => key.startsWith(prefix))\n .map((key) => key.slice(prefix.length))\n .sort(byCodeUnit);\n}\n\ninterface Condensation {\n /** Component index per node. */\n readonly component: Int32Array;\n /** Components in emission order — every one after everything it reaches. */\n readonly order: readonly (readonly NodeId[])[];\n}\n\n/**\n * Tarjan's strongly connected components, iteratively.\n *\n * Iterative because the recursion depth is the longest dependency chain in the\n * repository, and a deep monorepo would overflow a call stack on a structure whose\n * whole point is to be cheap. The emission order is the useful half: a component\n * appears only once everything it can reach has, which is the order a Merkle fold\n * needs and costs nothing extra to get.\n */\nfunction condense(relations: Relations, allowed: Uint8Array): Condensation {\n const count = relations.names.length;\n const { offset, target, kind } = relations.depends;\n\n const index = new Int32Array(count).fill(-1);\n const low = new Int32Array(count);\n const onStack = new Uint8Array(count);\n const component = new Int32Array(count).fill(-1);\n\n const pending: NodeId[] = [];\n const order: NodeId[][] = [];\n\n // Frames as two parallel arrays: the node, and how far through its edges it is.\n const frameNode: number[] = [];\n const frameEdge: number[] = [];\n let counter = 0;\n\n for (let root = 0; root < count; root += 1) {\n if (index[root] !== -1) continue;\n\n index[root] = counter;\n low[root] = counter;\n counter += 1;\n pending.push(root);\n onStack[root] = 1;\n frameNode.push(root);\n frameEdge.push(offset[root]!);\n\n while (frameNode.length > 0) {\n const node = frameNode[frameNode.length - 1]!;\n const at = frameEdge[frameEdge.length - 1]!;\n\n if (at < offset[node + 1]!) {\n frameEdge[frameEdge.length - 1] = at + 1;\n if (allowed[kind[at]!] !== 1) continue;\n\n const next = target[at]!;\n if (index[next] === -1) {\n index[next] = counter;\n low[next] = counter;\n counter += 1;\n pending.push(next);\n onStack[next] = 1;\n frameNode.push(next);\n frameEdge.push(offset[next]!);\n } else if (onStack[next] === 1) {\n if (index[next]! < low[node]!) low[node] = index[next]!;\n }\n continue;\n }\n\n frameNode.pop();\n frameEdge.pop();\n\n const parent = frameNode[frameNode.length - 1];\n if (parent !== undefined && low[node]! < low[parent]!) low[parent] = low[node]!;\n\n if (low[node] !== index[node]) continue;\n\n const members: NodeId[] = [];\n for (;;) {\n const member = pending.pop()!;\n onStack[member] = 0;\n component[member] = order.length;\n members.push(member);\n if (member === node) break;\n }\n order.push(members.sort((a, b) => a - b));\n }\n }\n\n return { component, order };\n}\n\n/**\n * The edge kinds a closure walks when the caller does not say.\n *\n * Listed rather than derived from `EDGE_KINDS`, and the difference is the whole\n * point. A digest is a claim about *which inputs* were folded, so changing the\n * fold silently changes every digest that exists — one edge kind added or\n * removed, and the next run finds nothing it can prove unchanged and re-observes\n * the entire suite while reporting a successful narrowing. Changing this list is\n * a decision with a cost, and it should read like one.\n *\n * `type` is not in it: a type-only import is erased before a render, so a change\n * behind one is not an input the render folded.\n */\nexport const CLOSURE_EDGES: readonly EdgeKind[] = [\n 'imports',\n 'reexports',\n 'dynamic',\n 'asset',\n 'declared-in',\n];\n\n/** Edge kinds as a lookup, so the inner loop tests a byte. */\nfunction allowedKinds(through: Iterable<EdgeKind> | undefined): Uint8Array {\n const allowed = new Uint8Array(EDGE_KINDS.length);\n\n for (const kind of through ?? CLOSURE_EDGES) {\n const at = EDGE_KINDS.indexOf(kind);\n if (at !== -1) allowed[at] = 1;\n }\n\n return allowed;\n}\n\nfunction byCodeUnit(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n"]}
|