An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): a long-running caller sees an edit to a doc file it already read (#7998)
Joeyfccd7713e4ea
diff --git a/.changeset/doc-edits-seen-in-process.md b/.changeset/doc-edits-seen-in-process.mdnew file mode 100644index 0000000000..2df373957f--- /dev/null+++ b/.changeset/doc-edits-seen-in-process.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] A process that calls the CLI API more than once, such as a docs site's search or an agent harness, now sees an edit to a doc file it already read: `search()`, `docs()` and `component()` read the edited file's new content on their next call, instead of what the process first imported. An unchanged doc file is still imported once and shared, so readers keep getting the module's own doc.++@josephfarinadiff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex b21de28d59..d67f7f2389 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -77,6 +77,7 @@ import {discoverIntegrationTemplatesForOne,} from '../../foundation/discovery/template-adapter.mjs';import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {reusedWhileUnchanged} from '../../foundation/fs/read-record.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {orderRouteSuggestions} from '../../foundation/text/suggest-order.mjs';@@ -393,8 +394,8 @@ export function projectTree(catalog, {fresh = false} = {}) {return tree;}-/** @type {ReturnType<typeof loadTreeInputs> | undefined} */-let cliTreeInputs;+/** The CLI's own tree files, loaded again after one of them changes. */+const cliTreeInputs = reusedWhileUnchanged(() => loadTreeInputs());/*** Every flat topic in the catalog, as the tree's topic levels read it.@@ -441,8 +442,7 @@ async function flatTopicInputs(catalog) {*/async function buildProjectTree(catalog, fresh) {const added = catalog.treeInputs;- if (fresh || !cliTreeInputs) cliTreeInputs = loadTreeInputs();- const cli = await cliTreeInputs;+ const cli = await cliTreeInputs({fresh});const result = buildDocsTree({namespaces: [...cli.namespaces, ...added.flatMap(each => each.namespaces)],docs: [...cli.docs, ...added.flatMap(each => each.guides)],@@ -573,11 +573,15 @@ function identitiesOf(tree) {/*** The CLI's authoring docs, by kind and name. The field reference under* `astryx docs authoring` reads each as one section keyed by its name, so a- * link to one opens that section. Loaded once per process, like the CLI's- * tree files.- * @type {Promise<Map<string, any>> | undefined}+ * link to one opens that section. Loaded again after one of them changes,+ * like the CLI's tree files.*/-let authoringDocs;+const authoringDocs = reusedWhileUnchanged(() =>+ loadAuthoringSelfDocs().then(+ ({loaded}) =>+ new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),+ ),+);/*** The CLI authoring doc a link names. The `authoring` namespace is the CLI's@@ -587,11 +591,7 @@ let authoringDocs;* @returns {Promise<any | null>}*/async function authoringDoc(kind, name) {- authoringDocs ??= loadAuthoringSelfDocs().then(- ({loaded}) =>- new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),- );- return (await authoringDocs).get(`${kind}\u0000${name}`) ?? null;+ return (await authoringDocs()).get(`${kind}\u0000${name}`) ?? null;}/**diff --git a/packages/cli/api/search/_adapter.test.mjs b/packages/cli/api/search/_adapter.test.mjsindex 499b245fdb..d0d7960cb3 100644--- a/packages/cli/api/search/_adapter.test.mjs+++ b/packages/cli/api/search/_adapter.test.mjs@@ -85,7 +85,7 @@ describe('gatherCandidatesReused', () => {);it(- 'gathers again when a file the gather read changes, in a linked package too',+ 'gathers again when a file the gather read or imported changes, in a linked package too',async () => {// A consumer whose integration is a symlink to a package folder// elsewhere, as a workspace package is.@@ -162,7 +162,26 @@ describe('gatherCandidatesReused', () => {// An edited file the gather read: the linked package's manifest.const later = new Date(Date.now() + 5_000);fs.utimesSync(path.join(pkg, 'package.json'), later, later);- expect(await gatherCandidatesReused(options)).not.toBe(second);+ const third = await gatherCandidatesReused(options);+ expect(third).not.toBe(second);++ // An edited doc the gather imported: the next gather reads its new+ // content, not the module this process imported first.+ fs.writeFileSync(+ path.join(pkg, 'components', 'FancyGizmo.doc.mjs'),+ `export default {+ type: 'component',+ name: 'FancyGizmo',+ keywords: ['gizmo'],+ usage: {description: 'A shinier part, now with sprockets.'},+ props: [],+ };\n`,+ );+ const fourth = await gatherCandidatesReused(options);+ expect(fourth).not.toBe(third);+ expect(+ JSON.stringify(fourth.all.find(c => c.name === 'FancyGizmo')),+ ).toContain('A shinier part, now with sprockets.');} finally {fs.rmSync(dir, {recursive: true, force: true});fs.rmSync(pkg, {recursive: true, force: true});diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex 5320f420a2..5775b115c0 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -345,12 +345,12 @@ const RUNNERS = {sites: ['require(@babel/parser)', 'require(jscodeshift)'],},'foundation/doc-compiler/import.mjs': {- runs: 'authored doc files, for the doc reader and discovery',+ runs: 'authored doc files, for the doc reader and discovery, and again after an edit',sites: [- '.import()',- 'createJiti',- 'import(<computed>) ×2',- 'importUserModule',+ '.import() ×2',+ 'createJiti ×2',+ 'import(<computed>) ×4',+ 'importUserModule ×2',],},'foundation/doc-compiler/read.mjs': {diff --git a/packages/cli/foundation/doc-compiler/import.mjs b/packages/cli/foundation/doc-compiler/import.mjsindex e1ca80314f..6edcedea54 100644--- a/packages/cli/foundation/doc-compiler/import.mjs+++ b/packages/cli/foundation/doc-compiler/import.mjs@@ -5,7 +5,12 @@* authored doc file.** @input An absolute path to a `.doc.{ts,mjs,js}` (or legacy template) file.- * @output The module's namespace object.+ * @output The module's namespace object: the one a plain import of the file+ * gives, until the file changes; then the edited file's, read once by each+ * importer, its own way, and shared until the next change. A long-running+ * process (a docs site's search, an agent harness) thereby sees an edit to+ * a doc file it already read, as a new process would read it. Only the doc+ * file's own edits count: a module it imports stays as first loaded.* @position Called by ./read.mjs, which hands what comes back to the compiler,* and by discovery, which reads a contributed topic's name and relationships* to build the catalog. Doc files also run outside these importers: each CLI@@ -20,10 +25,59 @@import {pathToFileURL} from 'node:url';import {createJiti} from 'jiti';import {importUserModule} from '../fs/module-loader.mjs';+import {fileStamp, recordContentRead} from '../fs/read-record.mjs';/** @type {ReturnType<typeof createJiti> | undefined} */let jsxJiti;+/**+ * Each doc file imported in this process: its stamp at the last import and,+ * once it changed, the module each importer read for that change.+ * @type {Map<string, {stamp: string, changed: Record<string, Promise<any>> | null}>}+ */+const imported = new Map();++/** Numbers each fresh native import's URL, so it names a new module. */+let changes = 0;++/**+ * Import `file` with `load` until it changes, then once with `loadFresh` for+ * each change, sharing that module until the next one. Each importer (`kind`)+ * keeps its own module, as each has its own loader. The file counts as read+ * by the running operation (see ../fs/read-record.mjs).+ * @param {string} file+ * @param {'doc' | 'template' | 'native'} kind+ * @param {(file: string) => Promise<any>} load+ * @param {(file: string) => Promise<any>} loadFresh+ * @returns {Promise<any>}+ */+function importCurrent(file, kind, load, loadFresh) {+ recordContentRead(file);+ const stamp = fileStamp(file);+ let seen = imported.get(file);+ if (!seen) {+ imported.set(file, {stamp, changed: null});+ return load(file);+ }+ if (seen.stamp !== stamp) {+ seen = {stamp, changed: {}};+ imported.set(file, seen);+ }+ if (!seen.changed) return load(file);+ return (seen.changed[kind] ??= loadFresh(file));+}++/**+ * The file's URL, naming a new module for each change.+ * @param {string} file+ * @returns {string}+ */+function freshUrl(file) {+ const url = pathToFileURL(file);+ url.searchParams.set('astryx-doc', String(++changes));+ return url.href;+}+/*** Import a component, hook, topic, or self-doc module: `.ts` through jiti,* anything else natively.@@ -31,7 +85,9 @@ let jsxJiti;* @returns {Promise<any>}*/export function importDocModule(file) {- return importUserModule(file);+ return importCurrent(file, 'doc', importUserModule, changed =>+ importUserModule(changed, {fresh: true}),+ );}/**@@ -41,11 +97,23 @@ export function importDocModule(file) {* @returns {Promise<any>}*/export function importTemplateModule(file) {- if (file.endsWith('.ts')) {- jsxJiti ??= createJiti(import.meta.url, {jsx: true});- return jsxJiti.import(file);- }- return import(`file://${file}`);+ return importCurrent(+ file,+ 'template',+ first => {+ if (first.endsWith('.ts')) {+ jsxJiti ??= createJiti(import.meta.url, {jsx: true});+ return jsxJiti.import(first);+ }+ return import(`file://${first}`);+ },+ changed =>+ changed.endsWith('.ts')+ ? createJiti(import.meta.url, {jsx: true, moduleCache: false}).import(+ changed,+ )+ : import(freshUrl(changed)),+ );}/**@@ -55,5 +123,10 @@ export function importTemplateModule(file) {* @returns {Promise<any>}*/export function importNativeModule(file) {- return import(pathToFileURL(file).href);+ return importCurrent(+ file,+ 'native',+ first => import(pathToFileURL(first).href),+ changed => import(freshUrl(changed)),+ );}diff --git a/packages/cli/foundation/doc-compiler/read.mjs b/packages/cli/foundation/doc-compiler/read.mjsindex 525feac318..08466f1823 100644--- a/packages/cli/foundation/doc-compiler/read.mjs+++ b/packages/cli/foundation/doc-compiler/read.mjs@@ -8,9 +8,9 @@* how strictly the reader checks.* @output The lowered doc for that file. Readers get the view they have always* read, lowered afresh on every read; a whole-project compile also gets the- * sealed node, memoized per file for the life of the process. For doc- * topics: the compiler input for a topic, with its extensions and overlays- * loaded.+ * sealed node, memoized per file while the file is unchanged. An edited file+ * is read again in the same process (./import.mjs). For doc topics: the+ * compiler input for a topic, with its extensions and overlays loaded.* @position Loads authored doc files for the readers in api/ and clients/ and* hands each to ./compile.mjs. Each reader keeps its own loader, export* order, and strictness, so what it prints is what it printed before.@@ -30,6 +30,7 @@ import {importNativeModule,importTemplateModule,} from './import.mjs';+import {fileStamp, recordContentRead} from '../fs/read-record.mjs';import {lowerDoc, parserFor} from './compile.mjs';import {translationFor} from './overlays.mjs';import {parseReadableDoc} from './parse-readable.mjs';@@ -82,13 +83,14 @@ const LOADERS = Object.freeze({* @property {boolean} [check] hold the doc to its kind's parser*/-/** @type {Map<string, Promise<import('./compile.mjs').LoweredDoc>>} */+/** @type {Map<string, {stamp: string, result: Promise<import('./compile.mjs').LoweredDoc>}>} */const lowered = new Map();/**- * Lower one descriptor file. Memoized per file and options for the life of the- * process; a file that failed to load is tried again on the next read, as a- * fresh import would be.+ * Lower one descriptor file. Memoized per file and options while the file is+ * unchanged; an edited file is lowered again from its new content, and a file+ * that failed to load is tried again on the next read, as a fresh import+ * would be.* @param {string} file absolute path* @param {ReadOptions} options* @param {{node?: boolean}} [want] also build the sealed node@@ -110,7 +112,10 @@ export function compileDocFile(file, options, {node = false} = {}) {check,node,]);- let result = lowered.get(key);+ recordContentRead(file);+ const stamp = fileStamp(file);+ const hit = lowered.get(key);+ let result = hit?.stamp === stamp ? hit.result : undefined;if (!result) {result = loadAuthored(file, options, lang).then(authored => {const provider = options.provider ?? packageOf(file);@@ -130,11 +135,11 @@ export function compileDocFile(file, options, {node = false} = {}) {);if (out.node) deepFreeze(out.node);if (out.loadFailed || 'overlayError' in authored) {- lowered.delete(key);+ if (lowered.get(key)?.result === result) lowered.delete(key);}return out;});- lowered.set(key, result);+ lowered.set(key, {stamp, result});}return result;}diff --git a/packages/cli/foundation/doc-compiler/read.test.mjs b/packages/cli/foundation/doc-compiler/read.test.mjsindex 6d671b2b10..24fecffcca 100644--- a/packages/cli/foundation/doc-compiler/read.test.mjs+++ b/packages/cli/foundation/doc-compiler/read.test.mjs@@ -16,6 +16,7 @@ import {Project} from '../config/project.mjs';import {CLI_ROOT} from '../fs/paths.mjs';import {loadComponentDoc, loadDocs} from '../discovery/component-loader.mjs';import {compileDocFile, readDocView} from './read.mjs';+import {importDocModule, importNativeModule} from './import.mjs';import {collectDocInputs} from './inputs.mjs';const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');@@ -151,7 +152,7 @@ describe('readDocView', () => {).toBe('Legacy');});- it('reads each file once per process, and retries a file that failed to load', async () => {+ it('reads each file once while it is unchanged, and retries a file that failed to load', async () => {const file = write('Card.doc.mjs', card);const before = await compileDocFile(file, {root: 'components'});expect(await compileDocFile(file, {root: 'components'})).toBe(before);@@ -320,3 +321,60 @@ catch (e) { console.log('threw', e.message.split('\\n')[0]); }`,expect(run('loadComponentDoc')).toMatch(/^(ok Typed|threw .*is invalid)/);});});++describe('an edited doc file, read again in the same process', () => {+ /** @param {string} displayName */+ const doc = displayName =>+ `export default {type: 'component', name: 'Edited', displayName: ${JSON.stringify(displayName)}, usage: {description: 'd'}, props: []};\n`;++ it('reads the new content, and shares each version while it is unchanged', async () => {+ const file = write('Edited.doc.mjs', doc('First'));+ const first = await loadDocs(file);+ expect(first.displayName).toBe('First');+ expect(await loadDocs(file)).toBe(first);+ fs.writeFileSync(file, doc('Second, longer'));+ const second = await loadDocs(file);+ expect(second.displayName).toBe('Second, longer');+ expect(await loadDocs(file)).toBe(second);+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');+ });++ it('reads an edited TypeScript doc again', async () => {+ const file = write('Edited.doc.ts', doc('First'));+ expect((await loadComponentDoc(file)).displayName).toBe('First');+ fs.writeFileSync(file, doc('Second, longer'));+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');+ });++ it('gives each importer its own read of an edited TypeScript doc, as a new process would', async () => {+ const file = write('Pair.doc.ts', doc('First'));+ const nativeBefore = await importNativeModule(file);+ expect(await importDocModule(file)).not.toBe(nativeBefore);+ fs.writeFileSync(file, doc('Second, longer'));+ // The unchecked reader (a plain import) first, then the checked one (jiti).+ expect((await loadDocs(file)).displayName).toBe('Second, longer');+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');+ const nativeAfter = await importNativeModule(file);+ const docAfter = await importDocModule(file);+ expect(docAfter).not.toBe(nativeAfter);+ expect(await importNativeModule(file)).toBe(nativeAfter);+ expect(await importDocModule(file)).toBe(docAfter);+ });++ it('lowers an edited file again for a whole-project compile', async () => {+ const file = write('Edited.doc.mjs', doc('First'));+ const read = () => compileDocFile(file, {root: 'components'});+ expect((await read()).view.displayName).toBe('First');+ fs.writeFileSync(file, doc('Second, longer'));+ expect((await read()).view.displayName).toBe('Second, longer');+ });++ it('reads a fix after an edit that broke the file', async () => {+ const file = write('Edited.doc.mjs', doc('First'));+ expect((await loadDocs(file)).displayName).toBe('First');+ fs.writeFileSync(file, 'export default {;\n');+ await expect(loadDocs(file)).rejects.toThrow();+ fs.writeFileSync(file, doc('Fixed again'));+ expect((await loadDocs(file)).displayName).toBe('Fixed again');+ });+});diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjsindex 74ad5f8be2..1943edaafe 100644--- a/packages/cli/foundation/fs/module-loader.mjs+++ b/packages/cli/foundation/fs/module-loader.mjs@@ -104,8 +104,9 @@ async function withStdoutOnStderr(load) {* no-cache jiti instance. A fresh CommonJS `.js` read evicts and reloads through* `require`; an ESM `.js` or `.mjs` read uses a cache-busted file URL. The* nearest package.json `type` decides `.js`, matching Node's package scopes.- * Normal loads retain module caching. `fresh` is an explicit migration-only- * escape hatch for rereading files that a codemod changed during this process.+ * Normal loads retain module caching. `fresh` rereads a file that changed+ * during this process: one a codemod rewrote, or an edited doc file (the doc+ * importers in ../doc-compiler/import.mjs read each change once).* Anything the module writes to stdout while it loads goes to stderr.** @param {string} file absolute pathdiff --git a/packages/cli/foundation/fs/read-record.mjs b/packages/cli/foundation/fs/read-record.mjsindex 5387ff7874..0ef1f39c33 100644--- a/packages/cli/foundation/fs/read-record.mjs+++ b/packages/cli/foundation/fs/read-record.mjs@@ -6,11 +6,16 @@** @input An operation run inside `recordReads(seen, fn)`.* @output `seen` gets every file whose content the operation read through fs- * and every folder it listed or probed, each with its state when first- * read; `unchangedSince(seen)` says whether all are still in that state.+ * or imported as a doc module (`recordContentRead`), and every folder it+ * listed or probed, each with its state when first read;+ * `unchangedSince(seen)` says whether all are still in that state.* @position Used by search's adapter to reuse a gathered catalog only while- * it is exact. Outside `recordReads` nothing is recorded and every fs call- * behaves as before.+ * it is exact, by the docs adapter to rebuild the CLI's own docs tree after+ * an edit (`reusedWhileUnchanged`), and by the doc importers and reader+ * (../doc-compiler) to read an edited doc file again. A run inside another+ * records into both, so an outer reuse sees what an inner one read.+ * Outside `recordReads` nothing is recorded and every fs call behaves as+ * before.*/import {AsyncLocalStorage} from 'node:async_hooks';@@ -19,12 +24,25 @@ import * as path from 'node:path';import {fileURLToPath} from 'node:url';/**- * The paths the running operation touched: every file it read and every- * folder it listed or probed.- * @type {AsyncLocalStorage<Map<string, string>>}+ * The paths the running operations touched, one map per enclosing+ * `recordReads`: every file read and every folder listed or probed.+ * @type {AsyncLocalStorage<Map<string, string>[]>}*/const reads = new AsyncLocalStorage();+/**+ * Add `file` to every running operation's map, with its state now, unless it+ * is there already.+ * @param {Map<string, string>[]} runs+ * @param {string} file+ */+function note(runs, file) {+ let state;+ for (const seen of runs) {+ if (!seen.has(file)) seen.set(file, (state ??= stateOf(file)));+ }+}+/** node:fs's module object, whose functions every import of it shares. */const fs = createRequire(import.meta.url)('node:fs');@@ -64,9 +82,9 @@ function installRecorder() {* @param {...any} args*/const wrapped = function (...args) {- const seen = reads.getStore();+ const runs = reads.getStore();const target = args[0];- if (seen && (typeof target === 'string' || target instanceof URL)) {+ if (runs && (typeof target === 'string' || target instanceof URL)) {const file =typeof target === 'string'? path.resolve(target)@@ -80,7 +98,7 @@ function installRecorder() {: path.dirname(file);// Its state is taken when it is first read, before the read, so a// change made while the operation runs shows as a change afterwards.- if (!seen.has(checked)) seen.set(checked, stateOf(checked));+ note(runs, checked);}return original.apply(this, args);};@@ -92,19 +110,23 @@ function installRecorder() {}/**- * One path's state: its change time and size, or that it is absent.+ * One path's state: its size and modification time, plus its change time and+ * inode, which change on a rewrite even when npm stamps the same size and+ * modification time; or that it is absent.* @param {string} file* @returns {string}*/-function stateOf(file) {+export function fileStamp(file) {try {- const stat = statSyncRaw(file);- return `${stat.mtimeMs}\0${stat.size}`;+ const {size, mtimeMs, ctimeMs, ino} = statSyncRaw(file);+ return `${size}:${mtimeMs}:${ctimeMs}:${ino}`;} catch {return '-';}}+const stateOf = fileStamp;+/*** Whether every recorded path is still in the state it had when it was read.* @param {Map<string, string>} recorded - From recordReads.@@ -117,6 +139,17 @@ export function unchangedSince(recorded) {return true;}+/**+ * Count `file` as read by the running operation, as a content read through fs+ * would be, for a read that does not go through fs: a module import. Outside+ * `recordReads` it does nothing.+ * @param {string} file+ */+export function recordContentRead(file) {+ const runs = reads.getStore();+ if (runs) note(runs, path.resolve(file));+}+/*** Run `fn`, adding to `seen` each path it reads, with that path's state when* it was first read (see the file header).@@ -127,5 +160,40 @@ export function unchangedSince(recorded) {*/export function recordReads(seen, fn) {installRecorder();- return reads.run(seen, fn);+ return reads.run([...(reads.getStore() ?? []), seen], fn);+}++/**+ * A loader whose value is kept while every file and folder it read is+ * unchanged, and loaded again after a change, so a long-running process sees+ * an edit. A failed load is tried again on the next call. What a kept value+ * read counts as read by the operation that asks for it.+ * @template T+ * @param {() => Promise<T>} load+ * @returns {(options?: {fresh?: boolean}) => Promise<T>}+ */+export function reusedWhileUnchanged(load) {+ /** @type {{reads: Map<string, string>, value: Promise<T>} | undefined} */+ let last;+ return ({fresh = false} = {}) => {+ if (!fresh && last && unchangedSince(last.reads)) {+ const {reads: recorded, value} = last;+ return value.then(result => {+ const runs = reads.getStore();+ if (runs) for (const [file, state] of recorded) {+ for (const seen of runs) if (!seen.has(file)) seen.set(file, state);+ }+ return result;+ });+ }+ /** @type {Map<string, string>} */+ const seen = new Map();+ const value = recordReads(seen, load);+ const entry = {reads: seen, value};+ last = entry;+ value.catch(() => {+ if (last === entry) last = undefined;+ });+ return value;+ };}diff --git a/packages/cli/foundation/fs/read-record.test.mjs b/packages/cli/foundation/fs/read-record.test.mjsindex 67675c7e7c..f77566ce10 100644--- a/packages/cli/foundation/fs/read-record.test.mjs+++ b/packages/cli/foundation/fs/read-record.test.mjs@@ -9,7 +9,12 @@ import {describe, it, expect} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import {recordReads, unchangedSince} from './read-record.mjs';+import {+ recordContentRead,+ recordReads,+ reusedWhileUnchanged,+ unchangedSince,+} from './read-record.mjs';function scratch() {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-read-record-'));@@ -72,6 +77,88 @@ describe('recordReads', () => {const seen = new Map();recordReads(seen, () => {});fs.readFileSync(file, 'utf8');+ recordContentRead(file);expect(seen.size).toBe(0);});++ it('records a file read without fs, such as an imported doc module, and sees it edited', () => {+ const {file} = scratch();+ /** @type {Map<string, string>} */+ const seen = new Map();+ recordReads(seen, () => recordContentRead(file));+ expect([...seen.keys()]).toEqual([file]);+ expect(unchangedSince(seen)).toBe(true);+ fs.writeFileSync(file, 'two, longer');+ expect(unchangedSince(seen)).toBe(false);+ });++ it('records a read in an operation inside another into both', async () => {+ const {file} = scratch();+ /** @type {Map<string, string>} */+ const outer = new Map();+ /** @type {Map<string, string>} */+ const inner = new Map();+ await recordReads(outer, async () => {+ await recordReads(inner, async () => fs.readFileSync(file, 'utf8'));+ });+ expect([...inner.keys()]).toEqual([file]);+ expect([...outer.keys()]).toEqual([file]);+ });++ it('sees a rewrite that keeps the size and modification time, as an npm reinstall does', () => {+ const {file} = scratch();+ const stamped = new Date('1985-10-26T08:15:00Z');+ fs.utimesSync(file, stamped, stamped);+ /** @type {Map<string, string>} */+ const seen = new Map();+ recordReads(seen, () => fs.readFileSync(file, 'utf8'));+ // Same size, and the same modification time npm stamps on every file.+ const replacement = `${file}.new`;+ fs.writeFileSync(replacement, 'two');+ fs.utimesSync(replacement, stamped, stamped);+ fs.renameSync(replacement, file);+ expect(unchangedSince(seen)).toBe(false);+ });+});++describe('reusedWhileUnchanged', () => {+ it('keeps a loaded value while what it read is unchanged, and loads again after an edit', async () => {+ const {file} = scratch();+ let loads = 0;+ const get = reusedWhileUnchanged(async () => {+ loads += 1;+ return fs.readFileSync(file, 'utf8');+ });+ expect(await get()).toBe('one');+ expect(await get()).toBe('one');+ expect(loads).toBe(1);+ fs.writeFileSync(file, 'two, longer');+ expect(await get()).toBe('two, longer');+ expect(loads).toBe(2);+ expect(await get({fresh: true})).toBe('two, longer');+ expect(loads).toBe(3);+ });++ it('counts what a kept value read as read by the operation that asks for it', async () => {+ const {file} = scratch();+ const get = reusedWhileUnchanged(async () => fs.readFileSync(file, 'utf8'));+ await get();+ /** @type {Map<string, string>} */+ const seen = new Map();+ await recordReads(seen, () => get());+ expect([...seen.keys()]).toEqual([file]);+ fs.writeFileSync(file, 'two, longer');+ expect(unchangedSince(seen)).toBe(false);+ });++ it('tries a failed load again', async () => {+ let calls = 0;+ const get = reusedWhileUnchanged(async () => {+ calls += 1;+ if (calls === 1) throw new Error('first try');+ return 'second try';+ });+ await expect(get()).rejects.toThrow('first try');+ expect(await get()).toBe('second try');+ });});