@seanhogg/builderforce-memory 2026.10.79 → 2026.10.81
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/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +45 -5
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/cooperative.d.ts +51 -0
- package/dist/knowledge/cooperative.d.ts.map +1 -0
- package/dist/knowledge/cooperative.js +58 -0
- package/dist/knowledge/cooperative.js.map +1 -0
- package/dist/knowledge/findings.d.ts +7 -1
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +39 -14
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/ignoreMatcher.d.ts +25 -0
- package/dist/knowledge/ignoreMatcher.d.ts.map +1 -0
- package/dist/knowledge/ignoreMatcher.js +121 -0
- package/dist/knowledge/ignoreMatcher.js.map +1 -0
- package/dist/knowledge/index.d.ts +6 -2
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +4 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/model.d.ts +26 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/plan.d.ts +6 -0
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +17 -1
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/reviewAnalyse.d.ts.map +1 -1
- package/dist/knowledge/reviewAnalyse.js +6 -1
- package/dist/knowledge/reviewAnalyse.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +7 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +10 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/rules/factStore.d.ts +11 -4
- package/dist/knowledge/rules/factStore.d.ts.map +1 -1
- package/dist/knowledge/rules/factStore.js +57 -25
- package/dist/knowledge/rules/factStore.js.map +1 -1
- package/dist/knowledge/rules/fixpointRules.d.ts +68 -0
- package/dist/knowledge/rules/fixpointRules.d.ts.map +1 -0
- package/dist/knowledge/rules/fixpointRules.js +0 -0
- package/dist/knowledge/rules/fixpointRules.js.map +1 -0
- package/dist/knowledge/sources.d.ts +9 -9
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +11 -50
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/statManifest.d.ts +89 -0
- package/dist/knowledge/statManifest.d.ts.map +1 -0
- package/dist/knowledge/statManifest.js +125 -0
- package/dist/knowledge/statManifest.js.map +1 -0
- package/dist/stats/estimators.d.ts +8 -1
- package/dist/stats/estimators.d.ts.map +1 -1
- package/dist/stats/estimators.js +18 -7
- package/dist/stats/estimators.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +12 -0
- package/src/contract/regression.assets.test.ts +2 -2
- package/src/contract/regression.factStoreBatchedLoad.test.ts +62 -0
- package/src/contract/regression.factStoreFastPath.test.ts +116 -0
- package/src/contract/regression.findingsProvider.test.ts +80 -0
- package/src/contract/regression.ignoreMatcher.test.ts +116 -0
- package/src/contract/types.contract.test.ts +9 -1
- package/src/knowledge/build.ts +37 -5
- package/src/knowledge/cooperative.test.ts +57 -0
- package/src/knowledge/cooperative.ts +76 -0
- package/src/knowledge/docs.test.ts +30 -0
- package/src/knowledge/findings.ts +55 -14
- package/src/knowledge/ignoreMatcher.ts +143 -0
- package/src/knowledge/index.ts +9 -2
- package/src/knowledge/model.ts +24 -0
- package/src/knowledge/plan.ts +20 -1
- package/src/knowledge/reviewAnalyse.ts +6 -1
- package/src/knowledge/reviewFinish.ts +7 -1
- package/src/knowledge/reviewModel.ts +6 -0
- package/src/knowledge/rules/factStore.ts +59 -21
- package/src/knowledge/rules/fixpointRules.test.ts +94 -0
- package/src/knowledge/rules/fixpointRules.ts +0 -0
- package/src/knowledge/sources.ts +12 -46
- package/src/knowledge/statManifest.test.ts +122 -0
- package/src/knowledge/statManifest.ts +176 -0
- package/src/stats/estimators.ts +18 -7
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.ignoreMatcher.test.ts — the memoized `ignoreMatcher` answers exactly as the algorithm it replaced.
|
|
3
|
+
*
|
|
4
|
+
* Before: for every path the matcher built every ancestor folder and tested EVERY rule against every ancestor (and the
|
|
5
|
+
* path): O(files × rules × depth) regex tests on the VS Code extension host's main thread, which a 34k-file multi-repo
|
|
6
|
+
* tree (every nested `.gitignore` adds its rules) stalled for seconds. The reference below IS that algorithm, kept
|
|
7
|
+
* verbatim, and is the oracle over a randomized tree with many nested `.gitignore` bases.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { ignoreMatcher } from '../knowledge/sources.js';
|
|
11
|
+
import { matchGlob } from '../knowledge/partitions.js';
|
|
12
|
+
|
|
13
|
+
const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore', '*.lock'];
|
|
14
|
+
|
|
15
|
+
/** The matcher as it was before the memoization (sources.ts, 2026-11-14), verbatim. */
|
|
16
|
+
function referenceMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
|
|
17
|
+
const rules: Array<{ glob: string; negate: boolean; dirOnly: boolean }> = [];
|
|
18
|
+
const lines = [
|
|
19
|
+
...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
|
|
20
|
+
...texts.flatMap((t) => {
|
|
21
|
+
const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
|
|
22
|
+
return text.split(/\r?\n/).map((line) => ({ line, base }));
|
|
23
|
+
}),
|
|
24
|
+
];
|
|
25
|
+
for (const { line, base } of lines) {
|
|
26
|
+
let p = line.replace(/\s+$/, '');
|
|
27
|
+
if (!p || p.startsWith('#')) continue;
|
|
28
|
+
const negate = p.startsWith('!');
|
|
29
|
+
if (negate) p = p.slice(1);
|
|
30
|
+
const dirOnly = p.endsWith('/');
|
|
31
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
32
|
+
const anchored = p.includes('/');
|
|
33
|
+
p = p.replace(/^\//, '');
|
|
34
|
+
const prefix = base ? `${base}/` : '';
|
|
35
|
+
if (p) rules.push({ glob: anchored ? `${prefix}${p}` : `${prefix}**/${p}`, negate, dirOnly });
|
|
36
|
+
}
|
|
37
|
+
return (path) => {
|
|
38
|
+
const segments = path.split('/');
|
|
39
|
+
const dirs = segments.slice(0, -1).map((_, i) => segments.slice(0, i + 1).join('/'));
|
|
40
|
+
let ignored = false;
|
|
41
|
+
for (const r of rules) {
|
|
42
|
+
const hit = (r.dirOnly ? dirs : [...dirs, path]).some((c) => matchGlob(c, r.glob));
|
|
43
|
+
if (hit) ignored = !r.negate;
|
|
44
|
+
}
|
|
45
|
+
return ignored;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A small deterministic PRNG (mulberry32), so a failure reproduces. */
|
|
50
|
+
function rng(seed: number): () => number {
|
|
51
|
+
let a = seed >>> 0;
|
|
52
|
+
return () => {
|
|
53
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
54
|
+
let t = a;
|
|
55
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
56
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
57
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const SEGMENTS = ['src', 'lib', 'dist', 'build', 'out', 'node_modules', 'docs', 'test', 'tmp', 'cache', 'a', 'b', 'repo1', 'repo2', 'pkg', '.git', 'vendor', 'gen'];
|
|
62
|
+
const FILES = ['index.ts', 'a.md', 'b.js', 'yarn.lock', '.gitignore', 'x.log', 'notes.txt', 'keep.log', 'main.min.js', 'copy*.txt', 'data.json'];
|
|
63
|
+
const PATTERNS = [
|
|
64
|
+
'dist/', 'build', '*.log', '!keep.log', '/out', 'tmp/', '*.min.js', 'cache/**', '!src/keep.log', 'docs/*.md', '!docs/',
|
|
65
|
+
'gen/**/*.ts', '**/vendor', 'a/b', '!a', '*.json', '# a comment', '', 'test/', '!test/index.ts', 'copy\\*.txt', '{a,b}.md',
|
|
66
|
+
'lib/?.js', '!yarn.lock', 'node_modules/', '/src/*.ts', 'pkg/**/b.js',
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
function randomTree(seed: number, opts: { paths: number; bases: number; rulesPerBase: number }) {
|
|
70
|
+
const next = rng(seed);
|
|
71
|
+
const pick = <T>(xs: readonly T[]): T => xs[Math.floor(next() * xs.length)]!;
|
|
72
|
+
const dir = (depth: number) => Array.from({ length: depth }, () => pick(SEGMENTS)).join('/');
|
|
73
|
+
const texts: Array<{ text: string; base: string }> = [];
|
|
74
|
+
for (let i = 0; i < opts.bases; i++) {
|
|
75
|
+
const base = i === 0 ? '' : dir(1 + Math.floor(next() * 4));
|
|
76
|
+
const text = Array.from({ length: opts.rulesPerBase }, () => pick(PATTERNS)).join(i % 2 ? '\r\n' : '\n');
|
|
77
|
+
texts.push({ text, base });
|
|
78
|
+
}
|
|
79
|
+
const paths = Array.from({ length: opts.paths }, () => {
|
|
80
|
+
const depth = Math.floor(next() * 7);
|
|
81
|
+
return depth === 0 ? pick(FILES) : `${dir(depth)}/${pick(FILES)}`;
|
|
82
|
+
});
|
|
83
|
+
return { texts, paths };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
describe('regression: ignoreMatcher memoization', () => {
|
|
87
|
+
it('regression: answers exactly as the unmemoized matcher over a randomized tree with many nested .gitignore bases', () => {
|
|
88
|
+
for (const seed of [1, 2, 3, 42, 1337]) {
|
|
89
|
+
const { texts, paths } = randomTree(seed, { paths: 2000, bases: 40, rulesPerBase: 8 });
|
|
90
|
+
const fast = ignoreMatcher(texts);
|
|
91
|
+
const ref = referenceMatcher(texts);
|
|
92
|
+
const mismatches = paths.filter((p) => fast(p) !== ref(p));
|
|
93
|
+
expect(mismatches).toEqual([]);
|
|
94
|
+
// Both outcomes occur, so the comparison is not vacuous.
|
|
95
|
+
expect(new Set(paths.map(ref)).size).toBe(2);
|
|
96
|
+
// Asking again (served from the folder memo) changes nothing.
|
|
97
|
+
expect(paths.filter((p) => fast(p) !== ref(p))).toEqual([]);
|
|
98
|
+
}
|
|
99
|
+
// Plain string texts (base ''), and degenerate paths.
|
|
100
|
+
const plain = ['dist/\n!keep.log', '*.log'];
|
|
101
|
+
const paths = ['dist/a.log', 'src/keep.log', 'a/dist/x.ts', 'x.log', 'dist', 'keep.log', '', '/abs/x.log', 'a//b.log'];
|
|
102
|
+
expect(paths.map(ignoreMatcher(plain))).toEqual(paths.map(referenceMatcher(plain)));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('perf guard: 30k paths × 300 rules finishes well within a few seconds', () => {
|
|
106
|
+
const { texts, paths } = randomTree(7, { paths: 30_000, bases: 60, rulesPerBase: 5 }); // ≈300 rules with the defaults
|
|
107
|
+
const fast = ignoreMatcher(texts);
|
|
108
|
+
const start = performance.now();
|
|
109
|
+
let ignored = 0;
|
|
110
|
+
for (const p of paths) if (fast(p)) ignored++;
|
|
111
|
+
const ms = performance.now() - start;
|
|
112
|
+
expect(ignored).toBeGreaterThan(0);
|
|
113
|
+
// Measured 2026-11-14 on this shape (folders nearly all distinct, the memo's worst case): the reference ≈4.6 s, this ≈0.2 s.
|
|
114
|
+
expect(ms).toBeLessThan(2000);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -45,7 +45,7 @@ import type {
|
|
|
45
45
|
import type {
|
|
46
46
|
Awaitable, DerivedRow, EffectiveEntryPoint, EffectiveGuardsOptions, EffectiveGuardsResult, FactManifestDelta, FactManifestEntry,
|
|
47
47
|
FactStoreManifest, FactStorePort, FactStoreSaveResult, FactStoreVersion, LoadFactGraphOptions, MemoryFactStore, MountFact, ResolvedMount,
|
|
48
|
-
StoredFactGraph, UseFact, RootRouter, MountTarget,
|
|
48
|
+
StoredFactGraph, UseFact, RootRouter, MountTarget, BuildGraphOptions, FindingsProvider, KnowledgeFacts, computeFindingsWith,
|
|
49
49
|
effectiveGuards, factStoreDump, loadFactGraph, memoryFactStore, rootRouters, saveFactGraph, sweepFactStore,
|
|
50
50
|
} from '../knowledge/index.js';
|
|
51
51
|
import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
@@ -460,6 +460,14 @@ export type EffectiveGuardsOptions_shape = Expect<Equal<EffectiveGuardsOptions,
|
|
|
460
460
|
export type rootRouters_signature = Expect<Equal<
|
|
461
461
|
typeof rootRouters, (files: ReadonlyMap<string, FileFacts>, resolveMount: (from: string, mount: MountFact) => MountTarget | undefined) => RootRouter[]
|
|
462
462
|
>>;
|
|
463
|
+
/* ── buildGraph findings provider (PRD 41 §B5 host seam) ────────────────────────────────────────────────────── */
|
|
464
|
+
export type BuildGraphOptions_findings_is_optional = Expect<Equal<IsOptional<BuildGraphOptions, 'findings'>, true>>;
|
|
465
|
+
export type BuildGraphOptions_findings = Expect<Equal<BuildGraphOptions['findings'], FindingsProvider | undefined>>;
|
|
466
|
+
export type FindingsProvider_keys = Expect<Equal<keyof FindingsProvider, 'kinds' | 'findings'>>;
|
|
467
|
+
export type FindingsProvider_findings = Expect<Equal<
|
|
468
|
+
FindingsProvider['findings'], (input: { graph: KnowledgeGraph; knowledge: KnowledgeFacts }) => Finding[]
|
|
469
|
+
>>;
|
|
470
|
+
export type computeFindingsWith_last_param = Expect<Equal<Parameters<typeof computeFindingsWith>[4], FindingsProvider>>;
|
|
463
471
|
export type RootRouter_shape = Expect<Equal<RootRouter, { path: string; router: string }>>;
|
|
464
472
|
export type MountTarget_shape = Expect<Equal<MountTarget, { path: string; router?: string }>>;
|
|
465
473
|
export type ResolvedMount_shape = Expect<Equal<ResolvedMount, {
|
package/src/knowledge/build.ts
CHANGED
|
@@ -24,7 +24,7 @@ import type {
|
|
|
24
24
|
PartitionRegistry, StoredFact,
|
|
25
25
|
} from './model.js';
|
|
26
26
|
import { crossesSystems, placeInSystem } from './systems.js';
|
|
27
|
-
import { computeFindings } from './findings.js';
|
|
27
|
+
import { computeFindings, computeFindingsWith } from './findings.js';
|
|
28
28
|
import { pageRank } from './importance.js';
|
|
29
29
|
import { applyCommunities } from './communities.js';
|
|
30
30
|
import { applyCoChangeHidden } from './coChange.js';
|
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
} from './refs.js';
|
|
37
37
|
import { buildOutline } from './outline.js';
|
|
38
38
|
import { truncateGraph } from './truncate.js';
|
|
39
|
+
import { LINKABLE_DOC_EXT } from './sources.js';
|
|
39
40
|
|
|
40
41
|
export const DEFAULT_MAX_NODES = 400;
|
|
41
42
|
export const MAX_NODES_CAP = 2000;
|
|
@@ -219,7 +220,10 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
|
|
|
219
220
|
...(systems.length > 0 ? { meta: { systems: systemsMeta(systems, allNodes) } } : {}),
|
|
220
221
|
stats: { sources: sources.size, nodes: allNodes.length, edges: allEdges.length, stale: 0, truncated: false, modularity, communityMethod },
|
|
221
222
|
};
|
|
222
|
-
|
|
223
|
+
// A findings provider (the host's fact index) sees the WHOLE graph, so its findings hold whether or not the view is cut.
|
|
224
|
+
full.findings = opts.findings
|
|
225
|
+
? computeFindingsWith(full, input.packs, registries, input.nearDuplicates ?? [], opts.findings)
|
|
226
|
+
: computeFindings(full, input.packs, registries, input.nearDuplicates ?? []);
|
|
223
227
|
full.stats.stale = allNodes.filter((n) => n.stale).length;
|
|
224
228
|
|
|
225
229
|
const maxNodes = Math.min(MAX_NODES_CAP, Math.max(1, Math.floor(opts.maxNodes ?? DEFAULT_MAX_NODES)));
|
|
@@ -265,19 +269,47 @@ function repointByName(e: KEdge, rootId: string, resolve: (name: string) => stri
|
|
|
265
269
|
return fileRefOf(e.from) === to ? null : { ...edge, to };
|
|
266
270
|
}
|
|
267
271
|
|
|
268
|
-
/**
|
|
272
|
+
/**
|
|
273
|
+
* A missing `src:` endpoint becomes a `missing` placeholder (a broken link); a missing fact drops the edge.
|
|
274
|
+
* A `links` target with no file of its own name is resolved against the files present NOW — an extensionless
|
|
275
|
+
* document target may name a sibling file like `troubleshooting.md`: an extract is cached, so it must record
|
|
276
|
+
* the written target, but whether the file exists is decided here. (The docs pack's broken-link rule only
|
|
277
|
+
* judges extensionless/document targets, so those are the only ones resolved.)
|
|
278
|
+
*/
|
|
269
279
|
function closeEndpoints(g: GraphBuilder): void {
|
|
280
|
+
const byFolderExt = new Map<string, NodeRef>();
|
|
281
|
+
for (const n of g.nodes.values()) {
|
|
282
|
+
if (n.kind !== 'file') continue;
|
|
283
|
+
const path = pathOfRef(n.ref);
|
|
284
|
+
if (path === undefined || path.startsWith('../')) continue;
|
|
285
|
+
const slash = path.lastIndexOf('/');
|
|
286
|
+
const folder = slash === -1 ? '' : path.slice(0, slash + 1);
|
|
287
|
+
const dot = path.lastIndexOf('.');
|
|
288
|
+
if (dot === -1 || dot < slash + 1) continue;
|
|
289
|
+
for (const ext of LINKABLE_DOC_EXT) {
|
|
290
|
+
if (ext === path.slice(dot + 1).toLowerCase()) { byFolderExt.set(folder + path.slice(slash + 1, dot), n.ref); break; }
|
|
291
|
+
}
|
|
292
|
+
}
|
|
270
293
|
for (const [id, e] of [...g.edges.entries()].sort((a, b) => compareStr(a[0], b[0]))) {
|
|
271
|
-
const
|
|
294
|
+
const { from } = e;
|
|
295
|
+
let { to } = e;
|
|
296
|
+
// An extensionless `links` target may name an existing sibling document; otherwise a placeholder is fabricated below.
|
|
297
|
+
if (e.kind === 'links' && !g.nodes.has(to)) {
|
|
298
|
+
const path = pathOfRef(to);
|
|
299
|
+
const resolved = path === undefined ? undefined : byFolderExt.get(path);
|
|
300
|
+
if (resolved !== undefined) to = resolved;
|
|
301
|
+
}
|
|
302
|
+
const ends = [from, to].filter((end) => !g.nodes.has(end));
|
|
272
303
|
if (ends.some((end) => pathOfRef(end) === undefined)) { g.edges.delete(id); continue; }
|
|
273
304
|
for (const end of ends) {
|
|
274
305
|
const path = pathOfRef(end)!;
|
|
275
|
-
const other = g.nodes.get(end ===
|
|
306
|
+
const other = g.nodes.get(end === from ? to : from);
|
|
276
307
|
g.node({
|
|
277
308
|
ref: end, kind: 'missing', label: basenameOf(path) || path, pack: other?.pack ?? FALLBACK_PACK_ID,
|
|
278
309
|
importance: 0, origin: 'extracted', badges: { missing: 1 },
|
|
279
310
|
});
|
|
280
311
|
}
|
|
312
|
+
if (to !== e.to) g.edges.set(id, { ...e, to });
|
|
281
313
|
}
|
|
282
314
|
}
|
|
283
315
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/cooperative.test.ts — the yield is chosen once, in order setImmediate > scheduler.yield > MessageChannel >
|
|
3
|
+
* setTimeout, from functions captured at pick time (fake timers installed later never reach it).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { jest } from '@jest/globals';
|
|
7
|
+
import { cooperativeBudget, pickYield, yieldToEventLoop, type YieldHost } from './cooperative.js';
|
|
8
|
+
|
|
9
|
+
/** A MessageChannel stand-in that delivers on a real immediate, and counts posts. */
|
|
10
|
+
function fakeChannel(posts: { n: number }): YieldHost['MessageChannel'] {
|
|
11
|
+
return class {
|
|
12
|
+
port1: { onmessage: ((ev: unknown) => void) | null } = { onmessage: null };
|
|
13
|
+
port2 = { postMessage: (_: unknown) => { posts.n++; setImmediate(() => this.port1.onmessage?.({})); } };
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('cooperative yield selection', () => {
|
|
18
|
+
it('prefers setImmediate, then scheduler.yield, then MessageChannel, then setTimeout', () => {
|
|
19
|
+
const timeout = (fn: () => void) => setTimeout(fn, 0);
|
|
20
|
+
const posts = { n: 0 };
|
|
21
|
+
const all: YieldHost = { setImmediate, scheduler: { yield: async () => undefined }, MessageChannel: fakeChannel(posts), setTimeout: timeout };
|
|
22
|
+
expect(pickYield(all).kind).toBe('setImmediate');
|
|
23
|
+
expect(pickYield({ ...all, setImmediate: undefined }).kind).toBe('scheduler.yield');
|
|
24
|
+
expect(pickYield({ ...all, setImmediate: undefined, scheduler: {} }).kind).toBe('MessageChannel');
|
|
25
|
+
expect(pickYield({ setTimeout: timeout }).kind).toBe('setTimeout');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('the MessageChannel fallback resolves each yield, in order', async () => {
|
|
29
|
+
const posts = { n: 0 };
|
|
30
|
+
const { yield: y } = pickYield({ MessageChannel: fakeChannel(posts) });
|
|
31
|
+
const order: number[] = [];
|
|
32
|
+
await Promise.all([y().then(() => order.push(1)), y().then(() => order.push(2))]);
|
|
33
|
+
expect(order).toEqual([1, 2]);
|
|
34
|
+
expect(posts.n).toBe(2);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('the setTimeout fallback is captured at pick time: replacing the host timer afterwards does not reach it', async () => {
|
|
38
|
+
let used = 0;
|
|
39
|
+
const host: YieldHost = { setTimeout: (fn) => { used++; return setTimeout(fn, 0); } };
|
|
40
|
+
const { yield: y } = pickYield(host);
|
|
41
|
+
host.setTimeout = () => { throw new Error('a later (fake) timer was used'); };
|
|
42
|
+
await y();
|
|
43
|
+
expect(used).toBe(1);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('fake timers installed after load do not stall the module yield or the budget', async () => {
|
|
47
|
+
jest.useFakeTimers();
|
|
48
|
+
try {
|
|
49
|
+
await yieldToEventLoop();
|
|
50
|
+
const budget = cooperativeBudget(0);
|
|
51
|
+
expect(budget.due()).toBe(true);
|
|
52
|
+
await budget.pause();
|
|
53
|
+
} finally {
|
|
54
|
+
jest.useRealTimers();
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/cooperative.ts — THE cooperative-yield helper of long synchronous loops (the plan's walk, the fact store's load).
|
|
3
|
+
*
|
|
4
|
+
* A host may run a review on its UI thread (the VS Code extension host does): a loop over tens of thousands of files must
|
|
5
|
+
* hand the event loop back every few milliseconds or the host stalls. {@link cooperativeBudget} times the work since the
|
|
6
|
+
* last yield and {@link yieldToEventLoop} returns to the event loop (a macrotask, so I/O and input run in between).
|
|
7
|
+
*
|
|
8
|
+
* Portable: `setImmediate`, `scheduler.yield`, a `MessageChannel` or `setTimeout(0)` ({@link pickYield}) and
|
|
9
|
+
* `performance.now()` — Node, browsers and Workers alike. All are captured when the module loads, so a test's fake timers
|
|
10
|
+
* never stall a yield.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Default work budget between two yields, in ms. */
|
|
14
|
+
export const COOPERATIVE_BUDGET_MS = 12;
|
|
15
|
+
|
|
16
|
+
/** The host globals the yield may use. */
|
|
17
|
+
export interface YieldHost {
|
|
18
|
+
setImmediate?: (fn: () => void) => unknown;
|
|
19
|
+
scheduler?: { yield?: () => Promise<void> };
|
|
20
|
+
MessageChannel?: new () => { port1: { onmessage: ((ev: unknown) => void) | null }; port2: { postMessage(msg: unknown): void } };
|
|
21
|
+
setTimeout?: (fn: () => void, ms?: number) => unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type YieldKind = 'setImmediate' | 'scheduler.yield' | 'MessageChannel' | 'setTimeout';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* THE choice of how to return to the event loop, made ONCE (at module load for `globalThis`): `setImmediate` (Node), else
|
|
28
|
+
* `scheduler.yield` (Chromium), else a `MessageChannel` message (browsers, Workers — a hidden tab throttles `setTimeout(0)` to
|
|
29
|
+
* ≥ 1 s, a message is not throttled), else `setTimeout(0)`. Every function is captured here, so fake timers installed later
|
|
30
|
+
* never reach it.
|
|
31
|
+
*/
|
|
32
|
+
export function pickYield(host: YieldHost): { kind: YieldKind; yield: () => Promise<void> } {
|
|
33
|
+
const immediate = host.setImmediate;
|
|
34
|
+
if (typeof immediate === 'function') return { kind: 'setImmediate', yield: () => new Promise((r) => { immediate.call(host, r); }) };
|
|
35
|
+
const scheduler = host.scheduler;
|
|
36
|
+
const schedulerYield = scheduler?.yield;
|
|
37
|
+
if (typeof schedulerYield === 'function') return { kind: 'scheduler.yield', yield: () => schedulerYield.call(scheduler) };
|
|
38
|
+
if (typeof host.MessageChannel === 'function') {
|
|
39
|
+
const channel = new host.MessageChannel();
|
|
40
|
+
const waiting: Array<() => void> = [];
|
|
41
|
+
channel.port1.onmessage = () => { waiting.shift()?.(); };
|
|
42
|
+
return { kind: 'MessageChannel', yield: () => new Promise((r) => { waiting.push(r); channel.port2.postMessage(0); }) };
|
|
43
|
+
}
|
|
44
|
+
const timeout = host.setTimeout;
|
|
45
|
+
if (typeof timeout === 'function') return { kind: 'setTimeout', yield: () => new Promise((r) => { timeout.call(host, r, 0); }) };
|
|
46
|
+
// No timer at all: a resolved promise still lets other microtasks run.
|
|
47
|
+
return { kind: 'setTimeout', yield: () => Promise.resolve() };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const g = globalThis as YieldHost & { performance?: { now(): number } };
|
|
51
|
+
const picked = pickYield(g);
|
|
52
|
+
const clock: () => number = g.performance && typeof g.performance.now === 'function' ? g.performance.now.bind(g.performance) : Date.now;
|
|
53
|
+
|
|
54
|
+
/** Returns to the event loop once (one macrotask). */
|
|
55
|
+
export function yieldToEventLoop(): Promise<void> {
|
|
56
|
+
return picked.yield();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CooperativeBudget {
|
|
60
|
+
/** Whether the work since the last yield exceeded the budget (cheap: one clock read). */
|
|
61
|
+
due(): boolean;
|
|
62
|
+
/** Yields to the event loop and restarts the budget. */
|
|
63
|
+
pause(): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A work budget: `if (budget.due()) await budget.pause();` inside a long loop. */
|
|
67
|
+
export function cooperativeBudget(budgetMs = COOPERATIVE_BUDGET_MS): CooperativeBudget {
|
|
68
|
+
let since = clock();
|
|
69
|
+
return {
|
|
70
|
+
due: () => clock() - since >= budgetMs,
|
|
71
|
+
pause: async () => {
|
|
72
|
+
await yieldToEventLoop();
|
|
73
|
+
since = clock();
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -119,3 +119,33 @@ describe('docs findings and cards', () => {
|
|
|
119
119
|
expect(setup.hash).toMatch(/^[0-9a-f]{64}$/);
|
|
120
120
|
});
|
|
121
121
|
});
|
|
122
|
+
|
|
123
|
+
describe('extensionless link resolution (build time)', () => {
|
|
124
|
+
const LINK_FILES: Record<string, string> = {
|
|
125
|
+
'gateway/index.md': '# Gateway\n\nSee [trouble](/gateway/troubleshooting), [rel](./authentication) and [gone](/gateway/nope).\n',
|
|
126
|
+
'gateway/troubleshooting.md': '# Trouble\n\nx\n',
|
|
127
|
+
'gateway/authentication.md': '# Auth\n\ny\n',
|
|
128
|
+
};
|
|
129
|
+
const linkSource = (path: string): SourceDocument =>
|
|
130
|
+
asPathSource({ id: path, tenantId: 't', content: { kind: 'text', text: LINK_FILES[path]! } }, path, `h:${path}`);
|
|
131
|
+
const linkExtract = (path: string): Extracted => {
|
|
132
|
+
const src = linkSource(path);
|
|
133
|
+
return markdownParser.extract!(src, markdownParser.parse(src), ctx);
|
|
134
|
+
};
|
|
135
|
+
const lg = buildGraph({ rootId: ROOT, extracted: Object.keys(LINK_FILES).map(linkExtract), facts: [], relations: [], packs: [DOCS_PACK] });
|
|
136
|
+
|
|
137
|
+
it('resolves an extensionless link to the existing sibling document, not a missing placeholder', () => {
|
|
138
|
+
expect(lg.nodes.some((n) => n.kind === 'missing' && n.ref === ref('gateway/troubleshooting'))).toBe(false);
|
|
139
|
+
expect(lg.nodes.some((n) => n.kind === 'missing' && n.ref === ref('gateway/authentication'))).toBe(false);
|
|
140
|
+
// the links edge now targets the real .md file node, in the same folder as the written target
|
|
141
|
+
expect(lg.edges.some((e) => e.kind === 'links' && e.to === ref('gateway/troubleshooting.md'))).toBe(true);
|
|
142
|
+
expect(lg.edges.some((e) => e.kind === 'links' && e.to === ref('gateway/authentication.md'))).toBe(true);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('still reports a link with no matching file as broken', () => {
|
|
146
|
+
expect(lg.nodes.find((n) => n.ref === ref('gateway/nope'))?.kind).toBe('missing');
|
|
147
|
+
const broken = lg.findings.filter((f) => f.kind === 'broken-link');
|
|
148
|
+
expect(broken).toHaveLength(1);
|
|
149
|
+
expect(broken[0]!.nodes).toEqual([ref('gateway/index.md'), ref('gateway/nope')]);
|
|
150
|
+
});
|
|
151
|
+
});
|
|
@@ -10,10 +10,10 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { finding, findingId, MAX_FINDING_NODES, requestKeyFor } from './findingBuilder.js';
|
|
13
|
-
import type { Finding, KnowledgeGraph, KnowledgePack, PartitionRegistry } from './model.js';
|
|
13
|
+
import type { Finding, FindingsProvider, KnowledgeGraph, KnowledgePack, PartitionRegistry } from './model.js';
|
|
14
14
|
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
15
15
|
import { compareStr } from './refs.js';
|
|
16
|
-
import { knowledgeFacts, runKnowledgeRules, type KnowledgeRule } from './rules/knowledgeInput.js';
|
|
16
|
+
import { knowledgeFacts, runKnowledgeRules, type KnowledgeFacts, type KnowledgeRule } from './rules/knowledgeInput.js';
|
|
17
17
|
import { cycleRule } from './rules/cycle.js';
|
|
18
18
|
import { cloneGroupRule, CLONE_GROUP_BADGE } from './rules/cloneGroup.js';
|
|
19
19
|
import { nearDuplicateRule } from './rules/nearDuplicate.js';
|
|
@@ -41,6 +41,21 @@ export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<strin
|
|
|
41
41
|
return runKnowledgeRules(GENERIC_FINDING_RULES, knowledgeFacts(g, registries));
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/** A finding from outside the generic rules (a pack rule, a findings provider) in the one shape: id, sorted nodes, request key. */
|
|
45
|
+
const normalizeFinding = (f: Finding): Finding => ({
|
|
46
|
+
...f,
|
|
47
|
+
id: f.id || findingId(f.kind, f.nodes),
|
|
48
|
+
nodes: [...new Set(f.nodes)].sort(compareStr),
|
|
49
|
+
requestKey: f.requestKey ?? requestKeyFor(f.kind),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** Deduped by id (first wins), sorted by severity then id: the one order of every finding list. */
|
|
53
|
+
function finishFindings(all: readonly Finding[]): Finding[] {
|
|
54
|
+
const byId = new Map<string, Finding>();
|
|
55
|
+
for (const f of all) if (!byId.has(f.id)) byId.set(f.id, f);
|
|
56
|
+
return [...byId.values()].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || compareStr(a.id, b.id));
|
|
57
|
+
}
|
|
58
|
+
|
|
44
59
|
/** Generic + possible-same + every pack's rules; deduped by id; severity, then id. */
|
|
45
60
|
export function computeFindings(
|
|
46
61
|
g: KnowledgeGraph,
|
|
@@ -48,20 +63,46 @@ export function computeFindings(
|
|
|
48
63
|
registries: ReadonlyMap<string, PartitionRegistry>,
|
|
49
64
|
nearDuplicates: readonly SimilarPair[],
|
|
50
65
|
): Finding[] {
|
|
51
|
-
|
|
66
|
+
return finishFindings(internalFindings(g, packs, registries, nearDuplicates, new Set()));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The built-in and pack findings, without any of the `owned` kinds (generic rules owned by id are not run at all). */
|
|
70
|
+
function internalFindings(
|
|
71
|
+
g: KnowledgeGraph,
|
|
72
|
+
packs: readonly KnowledgePack[],
|
|
73
|
+
registries: ReadonlyMap<string, PartitionRegistry>,
|
|
74
|
+
nearDuplicates: readonly SimilarPair[],
|
|
75
|
+
owned: ReadonlySet<string>,
|
|
76
|
+
knowledge: KnowledgeFacts = knowledgeFacts(g, registries, nearDuplicates),
|
|
77
|
+
): Finding[] {
|
|
78
|
+
const rules = owned.size === 0 ? KNOWLEDGE_FINDING_RULES : KNOWLEDGE_FINDING_RULES.filter((r) => !owned.has(r.id));
|
|
79
|
+
const all = runKnowledgeRules(rules, knowledge);
|
|
52
80
|
for (const pack of [...packs].sort((a, b) => compareStr(a.id, b.id))) {
|
|
53
81
|
for (const rule of pack.findings ?? []) {
|
|
54
|
-
for (const f of rule.find(g))
|
|
55
|
-
all.push({
|
|
56
|
-
...f,
|
|
57
|
-
id: f.id || findingId(f.kind, f.nodes),
|
|
58
|
-
nodes: [...new Set(f.nodes)].sort(compareStr),
|
|
59
|
-
requestKey: f.requestKey ?? requestKeyFor(f.kind),
|
|
60
|
-
});
|
|
61
|
-
}
|
|
82
|
+
for (const f of rule.find(g)) all.push(normalizeFinding(f));
|
|
62
83
|
}
|
|
63
84
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
85
|
+
return owned.size === 0 ? all : all.filter((f) => !owned.has(f.kind));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* {@link computeFindings} with a {@link FindingsProvider}: the provider's findings replace every built-in and pack finding
|
|
90
|
+
* of the kinds it owns (`provider.kinds`); the provider sees the WHOLE graph (`buildGraph` calls this before truncation)
|
|
91
|
+
* and its output is kept only for its own kinds, normalized like a pack finding. Same dedupe and order.
|
|
92
|
+
*/
|
|
93
|
+
export function computeFindingsWith(
|
|
94
|
+
g: KnowledgeGraph,
|
|
95
|
+
packs: readonly KnowledgePack[],
|
|
96
|
+
registries: ReadonlyMap<string, PartitionRegistry>,
|
|
97
|
+
nearDuplicates: readonly SimilarPair[],
|
|
98
|
+
provider: FindingsProvider,
|
|
99
|
+
): Finding[] {
|
|
100
|
+
const owned = new Set(provider.kinds);
|
|
101
|
+
// ONE knowledge-rule input, shared by the built-in rules and the provider.
|
|
102
|
+
const knowledge = knowledgeFacts(g, registries, nearDuplicates);
|
|
103
|
+
const internal = internalFindings(g, packs, registries, nearDuplicates, owned, knowledge);
|
|
104
|
+
const supplied = provider.findings({ graph: g, knowledge })
|
|
105
|
+
.filter((f) => owned.has(f.kind))
|
|
106
|
+
.map(normalizeFinding);
|
|
107
|
+
return finishFindings([...internal, ...supplied]);
|
|
67
108
|
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/ignoreMatcher.ts — THE `.gitignore`-style matcher of a review (plan.ts asks it about every listed file).
|
|
3
|
+
*
|
|
4
|
+
* Semantics (unchanged since it lived in sources.ts): `#` comments, `!` negation, a trailing `/` for directories only, a
|
|
5
|
+
* `/` elsewhere anchors the pattern (to its base), otherwise any depth. A path's CANDIDATES are its ancestor folders, plus
|
|
6
|
+
* the path itself for a rule that is not directory-only; the LAST rule that matches any candidate decides (a negation
|
|
7
|
+
* re-includes). Unlike git, a negation may re-include a file under an excluded folder.
|
|
8
|
+
*
|
|
9
|
+
* Cost: "the last rule that matches any candidate" is the largest index of a matching rule over the candidates, and the
|
|
10
|
+
* candidates of a path are its parent folder's candidates plus one more. So the matcher keeps, per folder, the largest
|
|
11
|
+
* index of a rule matching that folder or an ancestor, and the rules whose literal prefix can still match below it
|
|
12
|
+
* ({@link IGNORE_DIR_CACHE_LIMIT} folders at most). It tests only those rules ABOVE the index — each folder once per walk,
|
|
13
|
+
* each file only against its folder's remaining non-directory rules — and a literal prefix/suffix check skips the regex for
|
|
14
|
+
* a candidate that cannot match (a nested `.gitignore`'s rules all start with `base/`). Same answers as testing every rule
|
|
15
|
+
* against every candidate (regression.ignoreMatcher.test.ts).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { globToRegExp } from './partitions.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Always ignored: VCS internals, installed dependencies, builderforce config, and lockfiles (`yarn.lock`, `Cargo.lock` …): generated,
|
|
22
|
+
* huge, and plain text — extracted they would cost judgement calls for nothing; they were never stored (once skipped as binary).
|
|
23
|
+
* A `.builderforce/ignore` rule can still re-include one (`!yarn.lock`).
|
|
24
|
+
*/
|
|
25
|
+
const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore', '*.lock'];
|
|
26
|
+
|
|
27
|
+
/** How many folders' answers a matcher remembers; past it the memo starts over (answers stay exact, only work repeats). */
|
|
28
|
+
const IGNORE_DIR_CACHE_LIMIT = 100_000;
|
|
29
|
+
|
|
30
|
+
interface IgnoreRule {
|
|
31
|
+
glob: string;
|
|
32
|
+
negate: boolean;
|
|
33
|
+
dirOnly: boolean;
|
|
34
|
+
/** The literal text every match starts with / ends with ('' when the glob starts / ends with a wildcard). */
|
|
35
|
+
prefix: string;
|
|
36
|
+
suffix: string;
|
|
37
|
+
re: RegExp;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Characters with a meaning in a glob (partitions.ts globToRegExp): everything else is literal. */
|
|
41
|
+
const SPECIAL = new Set(['*', '?', '{', '}', '\\']);
|
|
42
|
+
|
|
43
|
+
function literalPrefix(glob: string): string {
|
|
44
|
+
let i = 0;
|
|
45
|
+
while (i < glob.length && !SPECIAL.has(glob[i]!)) i++;
|
|
46
|
+
return glob.slice(0, i);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function literalSuffix(glob: string): string {
|
|
50
|
+
let i = glob.length;
|
|
51
|
+
while (i > 0 && !SPECIAL.has(glob[i - 1]!)) i--;
|
|
52
|
+
// `**/` may match nothing (`**/x` matches `x`), so the slash after a `**` is not a required literal.
|
|
53
|
+
if (glob[i] === '/' && glob.slice(i - 2, i) === '**') i++;
|
|
54
|
+
return glob.slice(i);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What the matcher remembers of a folder: `top`, the largest index of a rule matching the folder or an ancestor (-1: none),
|
|
59
|
+
* and `live`, the indices (ascending) of the rules that can still match the folder's descendants — those whose literal
|
|
60
|
+
* prefix agrees with `folder/` (a nested `.gitignore`'s rules drop out everywhere outside its base).
|
|
61
|
+
*/
|
|
62
|
+
interface DirEntry {
|
|
63
|
+
top: number;
|
|
64
|
+
live: readonly number[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const matches = (r: IgnoreRule, candidate: string): boolean =>
|
|
68
|
+
candidate.startsWith(r.prefix) && candidate.endsWith(r.suffix) && r.re.test(candidate);
|
|
69
|
+
|
|
70
|
+
/** The rules of the ignore texts, in precedence order (the defaults first). */
|
|
71
|
+
function parseRules(texts: ReadonlyArray<string | { text: string; base: string }>): IgnoreRule[] {
|
|
72
|
+
const rules: IgnoreRule[] = [];
|
|
73
|
+
const lines = [
|
|
74
|
+
...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
|
|
75
|
+
...texts.flatMap((t) => {
|
|
76
|
+
const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
|
|
77
|
+
return text.split(/\r?\n/).map((line) => ({ line, base }));
|
|
78
|
+
}),
|
|
79
|
+
];
|
|
80
|
+
for (const { line, base } of lines) {
|
|
81
|
+
let p = line.replace(/\s+$/, '');
|
|
82
|
+
if (!p || p.startsWith('#')) continue;
|
|
83
|
+
const negate = p.startsWith('!');
|
|
84
|
+
if (negate) p = p.slice(1);
|
|
85
|
+
const dirOnly = p.endsWith('/');
|
|
86
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
87
|
+
const anchored = p.includes('/');
|
|
88
|
+
p = p.replace(/^\//, '');
|
|
89
|
+
// A nested `.gitignore` scopes its patterns to its own folder.
|
|
90
|
+
const prefix = base ? `${base}/` : '';
|
|
91
|
+
if (!p) continue;
|
|
92
|
+
const glob = anchored ? `${prefix}${p}` : `${prefix}**/${p}`;
|
|
93
|
+
rules.push({ glob, negate, dirOnly, prefix: literalPrefix(glob), suffix: literalSuffix(glob), re: globToRegExp(glob) });
|
|
94
|
+
}
|
|
95
|
+
return rules;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A `.gitignore`-style matcher: `#` comments, `!` negation (last match wins), a trailing
|
|
100
|
+
* `/` for directories only, a `/` elsewhere anchors to the root, otherwise any depth.
|
|
101
|
+
*/
|
|
102
|
+
export function ignoreMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
|
|
103
|
+
const rules = parseRules(texts);
|
|
104
|
+
const root: DirEntry = { top: -1, live: rules.map((_, i) => i) };
|
|
105
|
+
const dirs = new Map<string, DirEntry>();
|
|
106
|
+
|
|
107
|
+
/** The largest index above `floor` among `live` of a rule (all, or only non-directory ones) matching `candidate`, else `floor`. */
|
|
108
|
+
const topAbove = (candidate: string, live: readonly number[], floor: number, dirOnlyToo: boolean): number => {
|
|
109
|
+
for (let k = live.length - 1; k >= 0; k--) {
|
|
110
|
+
const i = live[k]!;
|
|
111
|
+
if (i <= floor) break;
|
|
112
|
+
const r = rules[i]!;
|
|
113
|
+
if ((dirOnlyToo || !r.dirOnly) && matches(r, candidate)) return i;
|
|
114
|
+
}
|
|
115
|
+
return floor;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** The entry of `dir`, from its parent's: the rules that can still match below it are those whose literal prefix agrees with `dir/`. */
|
|
119
|
+
const entryOf = (dir: string, parent: DirEntry): DirEntry => {
|
|
120
|
+
const top = topAbove(dir, parent.live, parent.top, true);
|
|
121
|
+
const below = `${dir}/`;
|
|
122
|
+
const live = parent.live.filter((i) => { const p = rules[i]!.prefix; return p.startsWith(below) || below.startsWith(p); });
|
|
123
|
+
return { top, live: live.length === parent.live.length ? parent.live : live };
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
return (path) => {
|
|
127
|
+
const segments = path.split('/');
|
|
128
|
+
let entry = root;
|
|
129
|
+
let dir = '';
|
|
130
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
131
|
+
dir = i === 0 ? segments[0]! : `${dir}/${segments[i]!}`;
|
|
132
|
+
let next = dirs.get(dir);
|
|
133
|
+
if (!next) {
|
|
134
|
+
next = entryOf(dir, entry);
|
|
135
|
+
if (dirs.size >= IGNORE_DIR_CACHE_LIMIT) dirs.clear();
|
|
136
|
+
dirs.set(dir, next);
|
|
137
|
+
}
|
|
138
|
+
entry = next;
|
|
139
|
+
}
|
|
140
|
+
const top = topAbove(path, entry.live, entry.top, false);
|
|
141
|
+
return top >= 0 && !rules[top]!.negate;
|
|
142
|
+
};
|
|
143
|
+
}
|