🎥 Make videos programmatically with React
Docs: Remove shared Twoslash cache (#10944)
Igor Samokhovets8f9775815716
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.tsindex 86f4b7629c..3923074d4d 100644--- a/packages/docs/prewarm-twoslash.ts+++ b/packages/docs/prewarm-twoslash.ts@@ -8,11 +8,9 @@ import {createInterface} from 'readline';import {Glob} from 'bun';import {createTwoslashCacheContext,- garbageCollectSharedTwoslashCache,getTwoslashCacheKey,getTwoslashLocalCachePath,getTwoslashVersions,- publishLocalTwoslashCacheEntry,readTwoslashCacheEntry,} from '../docusaurus-plugin/src/twoslash-cache';import {isTwoslashEnabled} from '../docusaurus-plugin/src/twoslash-enabled';@@ -111,17 +109,6 @@ function computeCacheLocation(return {key, path: getTwoslashLocalCachePath(cacheContext, key)};}-function publishLocalCacheEntries(validCachePaths: Set<string>): void {- for (const cachePath of validCachePaths) {- publishLocalTwoslashCacheEntry({- context: cacheContext,- key: basename(cachePath, '.json'),- });- }-- garbageCollectSharedTwoslashCache(cacheContext);-}-function addIncludes(map: Map<string, string>,name: string,@@ -421,7 +408,6 @@ async function main() {const uncachedBlocks = [...uniqueBlocks.values()];if (uncachedBlocks.length === 0) {- publishLocalCacheEntries(validCachePaths);const elapsed = ((performance.now() - startTime) / 1000).toFixed(1);console.log(`All twoslash blocks are cached (${elapsed}s to scan)`);return;@@ -603,9 +589,14 @@ async function main() {if (unfinished.length > 0) {const requeue: TwoslashBlock[] = [];for (const item of unfinished) {- // Workers publish cache files using an atomic rename, so an existing- // final path is complete even when the completion message was lost.- if (existsSync(item.cachePath)) {+ // Workers publish cache files using an atomic rename, so a valid final+ // entry is complete even when the completion message was lost.+ if (+ readTwoslashCacheEntry({+ context: cacheContext,+ key: basename(item.cachePath, '.json'),+ }) !== null+ ) {recordResult({cachePath: item.cachePath, ms: 0});continue;}@@ -792,7 +783,6 @@ async function main() {process.exit(1);}- publishLocalCacheEntries(validCachePaths);process.exit(0);}diff --git a/packages/docusaurus-plugin/src/caching.ts b/packages/docusaurus-plugin/src/caching.tsindex 4f811a2d89..2eb0a47f7f 100644--- a/packages/docusaurus-plugin/src/caching.ts+++ b/packages/docusaurus-plugin/src/caching.ts@@ -41,8 +41,7 @@ const getCacheContext = () => {};/**- * Keeps a local cache of the final HTML and shares immutable entries with the- * other worktrees belonging to the same Git repository.+ * Keeps a local cache of the final HTML in node_modules/.cache/twoslash.*/export const cachedTwoslashCall = (code: string,diff --git a/packages/docusaurus-plugin/src/twoslash-cache.test.ts b/packages/docusaurus-plugin/src/twoslash-cache.test.tsindex 8f1527ac51..fba061d371 100644--- a/packages/docusaurus-plugin/src/twoslash-cache.test.ts+++ b/packages/docusaurus-plugin/src/twoslash-cache.test.ts@@ -1,24 +1,14 @@import {afterEach, describe, expect, test} from 'bun:test';import {execFileSync} from 'child_process';-import {- existsSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- rmSync,- utimesSync,- writeFileSync,-} from 'fs';+import {mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync} from 'fs';import {tmpdir} from 'os';import {join} from 'path';import {pathToFileURL} from 'url';import {createTwoslashCacheContext,- garbageCollectSharedTwoslashCache,- getSharedTwoslashCacheRoot,getTwoslashCacheKey,getTwoslashEnvironmentHash,+ getTwoslashLocalCachePath,readTwoslashCacheEntry,type TwoslashCacheContext,writeTwoslashCacheEntry,@@ -26,20 +16,17 @@ import {const temporaryDirectories: string[] = [];-const makeContext = (- root: string,- localName: string,- environmentHash = 'environment-a',-): TwoslashCacheContext => ({- localRoot: join(root, localName),- sharedRoot: join(root, 'shared'),- environmentHash,- versions: {- twoslash: '1.0.0',- shiki: '1.0.0',- typescript: '1.0.0',- shikiTwoslash: '1.0.0',- },+const versions = {+ twoslash: '1.0.0',+ shiki: '1.0.0',+ typescript: '1.0.0',+ shikiTwoslash: '1.0.0',+};++const makeContext = (root: string): TwoslashCacheContext => ({+ localRoot: join(root, 'node_modules', '.cache', 'twoslash'),+ environmentHash: 'environment-a',+ versions,workspacePackages: {},});@@ -49,20 +36,15 @@ const makeTemporaryDirectory = () => {return directory;};-const versions = {- twoslash: '1.0.0',- shiki: '1.0.0',- typescript: '1.0.0',- shikiTwoslash: '1.0.0',-};-const makeEnvironmentRepository = ({- lockfile = 'lockfile',+ committedLockfile = 'lockfile',+ installedLockfile,name,packages,root,}: {- lockfile?: string;+ committedLockfile?: string;+ installedLockfile?: string;name: string;packages: Record<string,@@ -73,7 +55,7 @@ const makeEnvironmentRepository = ({const repository = join(root, name);const docsRoot = join(repository, 'packages', 'docs');mkdirSync(docsRoot, {recursive: true});- writeFileSync(join(repository, 'bun.lock'), lockfile, 'utf8');+ writeFileSync(join(repository, 'bun.lock'), committedLockfile, 'utf8');writeFileSync(join(repository, 'package.json'), '{}', 'utf8');writeFileSync(join(docsRoot, 'package.json'),@@ -102,6 +84,23 @@ const makeEnvironmentRepository = ({execFileSync('git', ['init', '--quiet', repository]);execFileSync('git', ['-C', repository, 'add', '.']);+ execFileSync('git', [+ '-C',+ repository,+ '-c',+ 'user.name=Test',+ '-c',+ '[email protected]',+ 'commit',+ '--quiet',+ '-m',+ 'Initial',+ ]);++ if (installedLockfile !== undefined) {+ writeFileSync(join(repository, 'bun.lock'), installedLockfile, 'utf8');+ }+return docsRoot;};@@ -112,9 +111,101 @@ afterEach(() => {for (const directory of temporaryDirectories.splice(0)) {rmSync(directory, {recursive: true, force: true});}+});++describe('Twoslash local cache', () => {+ test('reuses unchanged snippets and invalidates only a changed snippet', () => {+ const context = makeContext(makeTemporaryDirectory());+ const firstCode = 'const first = 1;';+ const secondCode = 'const second = 2;';+ const firstKey = getTwoslashCacheKey({+ code: firstCode,+ context,+ lang: 'ts',+ });+ const secondKey = getTwoslashCacheKey({+ code: secondCode,+ context,+ lang: 'ts',+ });++ writeTwoslashCacheEntry({+ context,+ html: '<pre>first</pre>',+ key: firstKey,+ });+ writeTwoslashCacheEntry({+ context,+ html: '<pre>second</pre>',+ key: secondKey,+ });++ expect(readTwoslashCacheEntry({context, key: firstKey})).toBe(+ '<pre>first</pre>',+ );+ const changedFirstKey = getTwoslashCacheKey({+ code: `${firstCode}\nconst changed = true;`,+ context,+ lang: 'ts',+ });+ expect(readTwoslashCacheEntry({context, key: changedFirstKey})).toBeNull();+ expect(readTwoslashCacheEntry({context, key: secondKey})).toBe(+ '<pre>second</pre>',+ );+ });++ test('publishes local entries atomically and rejects empty entries', async () => {+ const root = makeTemporaryDirectory();+ const context = makeContext(root);+ const key = getTwoslashCacheKey({+ code: 'const value = 1;',+ context,+ lang: 'ts',+ });+ const candidates = Array.from(+ {length: 6},+ (_, index) => `<pre>worker-${index}</pre>`,+ );+ const moduleUrl = pathToFileURL(join(__dirname, 'twoslash-cache.ts')).href;+ const script = `+ import {writeTwoslashCacheEntry} from ${JSON.stringify(moduleUrl)};+ writeTwoslashCacheEntry({+ context: JSON.parse(process.env.TWOSLASH_TEST_CONTEXT),+ key: process.env.TWOSLASH_TEST_KEY,+ html: process.env.TWOSLASH_TEST_HTML,+ });+ `;+ const processes = candidates.map((html) =>+ Bun.spawn({+ cmd: [process.execPath, '-e', script],+ env: {+ ...process.env,+ TWOSLASH_TEST_CONTEXT: JSON.stringify(context),+ TWOSLASH_TEST_KEY: key,+ TWOSLASH_TEST_HTML: html,+ },+ stderr: 'pipe',+ stdout: 'ignore',+ }),+ );+ expect(+ await Promise.all(processes.map((process) => process.exited)),+ ).toEqual(candidates.map(() => 0));- delete process.env.TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS;- delete process.env.TWOSLASH_SHARED_CACHE_MAX_AGE_MS;+ const cached = readTwoslashCacheEntry({context, key});+ if (cached === null) {+ throw new Error('Expected a local cache entry');+ }++ expect(candidates).toContain(cached);+ expect(+ readdirSync(context.localRoot).filter((file) => file.endsWith('.tmp')),+ ).toEqual([]);++ const emptyKey = 'empty';+ writeFileSync(getTwoslashLocalCachePath(context, emptyKey), '', 'utf8');+ expect(readTwoslashCacheEntry({context, key: emptyKey})).toBeNull();+ });});describe('Twoslash cache keys', () => {@@ -167,63 +258,14 @@ describe('Twoslash cache keys', () => {}),);const alphaCode = "import {alpha} from '@remotion/alpha';\nalpha;";- const alphaKey = getTwoslashCacheKey({- code: alphaCode,- context: baseline,- lang: 'ts',- });const getAlphaKey = (context: TwoslashCacheContext) =>getTwoslashCacheKey({code: alphaCode, context, lang: 'ts'});+ const alphaKey = getAlphaKey(baseline);expect(getAlphaKey(unrelatedChange)).toBe(alphaKey);expect(getAlphaKey(directChange)).not.toBe(alphaKey);expect(getAlphaKey(transitiveChange)).not.toBe(alphaKey);- const sharedRoot = join(root, 'selective-shared-cache');- const baselineCache = {- ...baseline,- localRoot: join(root, 'baseline-cache'),- sharedRoot,- };- writeTwoslashCacheEntry({- context: baselineCache,- html: '<pre>alpha</pre>',- key: alphaKey,- });- expect(- readTwoslashCacheEntry({- context: {- ...unrelatedChange,- localRoot: join(root, 'unrelated-cache'),- sharedRoot,- },- key: getAlphaKey(unrelatedChange),- }),- ).toBe('<pre>alpha</pre>');- expect(- readTwoslashCacheEntry({- context: {- ...directChange,- localRoot: join(root, 'direct-cache'),- sharedRoot,- },- key: getAlphaKey(directChange),- }),- ).toBeNull();-- for (const code of [- "import type {Alpha} from '@remotion/alpha/subpath';",- "import '@remotion/alpha';",- "export {alpha} from '@remotion/alpha';",- "import('@remotion/alpha');",- "require('@remotion/alpha');",- '/// <reference types="@remotion/alpha" />',- ]) {- expect(- getTwoslashCacheKey({code, context: directChange, lang: 'ts'}),- ).not.toBe(getTwoslashCacheKey({code, context: baseline, lang: 'ts'}));- }-expect(getTwoslashCacheKey({code: "import {beta} from '@remotion/beta';\nbeta;",@@ -252,226 +294,83 @@ describe('Twoslash cache keys', () => {);});- test('fingerprint external dependency resolutions globally', () => {+ test('uses the committed lockfile after a Vercel-style install', () => {const root = makeTemporaryDirectory();- const first = makeEnvironmentRepository({- name: 'first',+ const checkout = makeEnvironmentRepository({+ name: 'checkout',packages: {},root,});- const second = makeEnvironmentRepository({- lockfile: 'updated lockfile',- name: 'second',+ const installedCheckout = makeEnvironmentRepository({+ installedLockfile: 'lockfile rewritten during install',+ name: 'installed-checkout',packages: {},root,});-- expect(getTwoslashEnvironmentHash(second)).not.toBe(- getTwoslashEnvironmentHash(first),- );- });-- test('include the language and type environment', () => {- const root = makeTemporaryDirectory();- const context = makeContext(root, 'local-a');- const base = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context,- });- const differentLanguage = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'tsx',- context,- });- const differentEnvironment = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context: makeContext(root, 'local-b', 'environment-b'),- });- const differentVersions = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context: {- ...context,- versions: {...context.versions, shikiTwoslash: '2.0.0'},- },+ const updatedCheckout = makeEnvironmentRepository({+ committedLockfile: 'committed dependency update',+ name: 'updated-checkout',+ packages: {},+ root,});- expect(differentLanguage).not.toBe(base);- expect(differentEnvironment).not.toBe(base);- expect(differentVersions).not.toBe(base);- });-});--describe('shared Twoslash cache', () => {- test('uses the same root for all Git worktrees', () => {- const root = makeTemporaryDirectory();- const repository = join(root, 'repository');- const worktree = join(root, 'worktree');- mkdirSync(repository);- execFileSync('git', ['init', '--quiet', repository]);- execFileSync('git', [- '-C',- repository,- 'config',- 'user.email',- '[email protected]',- ]);- execFileSync('git', ['-C', repository, 'config', 'user.name', 'Test']);- writeFileSync(join(repository, 'file'), 'content', 'utf8');- execFileSync('git', ['-C', repository, 'add', 'file']);- execFileSync('git', [- '-C',- repository,- 'commit',- '--quiet',- '-m',- 'Initial',- ]);- execFileSync('git', [- '-C',- repository,- 'worktree',- 'add',- '--quiet',- '--detach',- worktree,- ]);-- expect(getSharedTwoslashCacheRoot(worktree)).toBe(- getSharedTwoslashCacheRoot(repository),+ expect(getTwoslashEnvironmentHash(installedCheckout)).toBe(+ getTwoslashEnvironmentHash(checkout),);- });-- test('hydrates another worktree and does not replace immutable entries', () => {- const root = makeTemporaryDirectory();- const first = makeContext(root, 'local-a');- const second = makeContext(root, 'local-b');- const third = makeContext(root, 'local-c');- const key = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context: first,- });-- writeTwoslashCacheEntry({context: first, key, html: '<pre>first</pre>'});- expect(readTwoslashCacheEntry({context: second, key})).toBe(- '<pre>first</pre>',+ expect(getTwoslashEnvironmentHash(updatedCheckout)).not.toBe(+ getTwoslashEnvironmentHash(checkout),);-- writeTwoslashCacheEntry({context: second, key, html: '<pre>second</pre>'});- expect(readTwoslashCacheEntry({context: third, key})).toBe(- '<pre>first</pre>',+ const code = 'const value = 1;';+ expect(+ getTwoslashCacheKey({+ code,+ context: makeRepositoryContext(installedCheckout),+ lang: 'ts',+ }),+ ).toBe(+ getTwoslashCacheKey({+ code,+ context: makeRepositoryContext(checkout),+ lang: 'ts',+ }),);});- test('publishes one complete entry when processes race', async () => {+ test('include the language and Twoslash environment', () => {const root = makeTemporaryDirectory();- const context = makeContext(root, 'local-parent');- const key = getTwoslashCacheKey({+ const context = makeContext(root);+ const base = getTwoslashCacheKey({code: 'const value = 1;',lang: 'ts',context,});- const candidates = Array.from(- {length: 6},- (_, index) => `<pre>worker-${index}</pre>`,- );- const moduleUrl = pathToFileURL(join(__dirname, 'twoslash-cache.ts')).href;- const script = `- import {writeTwoslashCacheEntry} from ${JSON.stringify(moduleUrl)};- const context = JSON.parse(process.env.TWOSLASH_TEST_CONTEXT);- writeTwoslashCacheEntry({+ expect(+ getTwoslashCacheKey({+ code: 'const value = 1;',+ lang: 'tsx',context,- key: process.env.TWOSLASH_TEST_KEY,- html: process.env.TWOSLASH_TEST_HTML,- });- `;- const processes = candidates.map((html, index) =>- Bun.spawn({- cmd: [process.execPath, '-e', script],- env: {- ...process.env,- TWOSLASH_TEST_CONTEXT: JSON.stringify({- ...context,- localRoot: join(root, `local-worker-${index}`),- }),- TWOSLASH_TEST_KEY: key,- TWOSLASH_TEST_HTML: html,- },- stderr: 'pipe',- stdout: 'ignore',}),- );- const exitCodes = await Promise.all(- processes.map((process) => process.exited),- );-- expect(exitCodes).toEqual(candidates.map(() => 0));- const cached = readTwoslashCacheEntry({- context: makeContext(root, 'local-reader'),- key,- });- expect(cached).not.toBeNull();- if (cached === null) {- throw new Error('Expected a shared cache entry');- }-- expect(candidates).toContain(cached);+ ).not.toBe(base);expect(- readdirSync(context.sharedRoot!).filter(- (file) => file.endsWith('.tmp') || file.endsWith('.lock'),- ),- ).toEqual([]);- });-- test('rejects and repairs corrupt shared entries', () => {- const root = makeTemporaryDirectory();- const first = makeContext(root, 'local-a');- const second = makeContext(root, 'local-b');- const third = makeContext(root, 'local-c');- const key = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context: first,- });- const sharedPath = join(first.sharedRoot!, `${key}.json`);-- writeTwoslashCacheEntry({context: first, key, html: '<pre>first</pre>'});- writeFileSync(sharedPath, 'corrupt', 'utf8');- expect(readTwoslashCacheEntry({context: second, key})).toBeNull();-- writeTwoslashCacheEntry({- context: second,- key,- html: '<pre>repaired</pre>',- });- expect(readTwoslashCacheEntry({context: third, key})).toBe(- '<pre>repaired</pre>',- );- });-- test('garbage-collects old shared entries without deleting local entries', () => {- const root = makeTemporaryDirectory();- const context = makeContext(root, 'local-a');- const key = getTwoslashCacheKey({- code: 'const value = 1;',- lang: 'ts',- context,- });- const sharedPath = join(context.sharedRoot!, `${key}.json`);- const localPath = join(context.localRoot, `${key}.json`);-- writeTwoslashCacheEntry({context, key, html: '<pre>cached</pre>'});- const old = new Date(Date.now() - 10_000);- utimesSync(sharedPath, old, old);- process.env.TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS = '0';- process.env.TWOSLASH_SHARED_CACHE_MAX_AGE_MS = '1';-- garbageCollectSharedTwoslashCache(context);-- expect(existsSync(sharedPath)).toBeFalse();- expect(readFileSync(localPath, 'utf8')).toBe('<pre>cached</pre>');+ getTwoslashCacheKey({+ code: 'const value = 1;',+ lang: 'ts',+ context: {...context, environmentHash: 'environment-b'},+ }),+ ).not.toBe(base);+ for (const dependency of Object.keys(+ versions,+ ) as (keyof typeof versions)[]) {+ expect(+ getTwoslashCacheKey({+ code: 'const value = 1;',+ lang: 'ts',+ context: {+ ...context,+ versions: {...context.versions, [dependency]: '2.0.0'},+ },+ }),+ ).not.toBe(base);+ }});});diff --git a/packages/docusaurus-plugin/src/twoslash-cache.ts b/packages/docusaurus-plugin/src/twoslash-cache.tsindex c749fbf361..b61108cdd0 100644--- a/packages/docusaurus-plugin/src/twoslash-cache.ts+++ b/packages/docusaurus-plugin/src/twoslash-cache.ts@@ -2,15 +2,11 @@ import {execFileSync} from 'child_process';import {createHash, randomBytes} from 'crypto';import {existsSync,- linkSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,- statSync,- unlinkSync,- utimesSync,writeFileSync,} from 'fs';import {dirname, join, relative, resolve} from 'path';@@ -20,12 +16,6 @@ export const TWOSLASH_THEME = 'github-dark';export const TWOSLASH_EXPLICIT_TRIGGER = false;export const TWOSLASH_RENDERER = 'classic';-const SHARED_CACHE_FILE_VERSION = 1;-const DAY_MS = 24 * 60 * 60 * 1000;-const DEFAULT_MAX_CACHE_AGE_MS = 90 * DAY_MS;-const DEFAULT_MAX_CACHE_BYTES = 512 * 1024 * 1024;-const DEFAULT_GC_INTERVAL_MS = DAY_MS;-export const getTwoslashCompilerOptions = () => ({types: ['node'],target: 99 /* ESNext */,@@ -48,45 +38,16 @@ interface TwoslashWorkspacePackage {export interface TwoslashCacheContext {localRoot: string;- sharedRoot: string | null;environmentHash: string;versions: TwoslashVersions;workspacePackages: Record<string, TwoslashWorkspacePackage>;}-interface SharedCacheHeader {- fileVersion: number;- key: string;- contentHash: string;-}-const environmentHashCache = new Map<string, string>();-const isNodeError = (error: unknown, code: string): boolean => {- return (- error instanceof Error &&- 'code' in error &&- (error as NodeJS.ErrnoException).code === code- );-};--const safeUnlink = (path: string): void => {- try {- unlinkSync(path);- } catch (error) {- if (!isNodeError(error, 'ENOENT')) {- throw error;- }- }-};--const getTemporaryPath = (path: string): string => {- return `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;-};-const writeFileAtomically = (path: string, contents: string): void => {mkdirSync(dirname(path), {recursive: true});- const temporaryPath = getTemporaryPath(path);+ const temporaryPath = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;writeFileSync(temporaryPath, contents, {encoding: 'utf8', flag: 'wx'});try {@@ -97,9 +58,7 @@ const writeFileAtomically = (path: string, contents: string): void => {throw error;}} finally {- if (existsSync(temporaryPath)) {- safeUnlink(temporaryPath);- }+ rmSync(temporaryPath, {force: true});}};@@ -152,24 +111,6 @@ const getGitPath = (cwd: string, argument: string): string | null => {}};-export const getSharedTwoslashCacheRoot = (cwd: string): string | null => {- if (process.env.TWOSLASH_SHARED_CACHE_DIR) {- return resolve(process.env.TWOSLASH_SHARED_CACHE_DIR);- }-- const gitCommonDir = getGitPath(cwd, '--git-common-dir');- if (!gitCommonDir) {- return null;- }-- return join(- gitCommonDir,- 'remotion-cache',- 'twoslash',- `v${TWOSLASH_CACHE_SCHEMA_VERSION}`,- );-};-const getRepositoryRoot = (docsRoot: string): string => {return (getGitPath(docsRoot, '--show-toplevel') ?? resolve(docsRoot, '..', '..')@@ -236,11 +177,24 @@ export const getTwoslashEnvironmentHash = (docsRoot: string): string => {return cached;}- // External package versions, TypeScript's ambient types and package-manager- // resolutions can affect any snippet. Workspace declarations are fingerprinted- // separately so a change to one package does not invalidate every snippet.+ // External package resolutions can affect any snippet. Hash the committed+ // lockfile so an install-time rewrite cannot invalidate restored cache entries.const hash = createHash('sha256');- hashFile(hash, repositoryRoot, join(repositoryRoot, 'bun.lock'));+ hash.update('bun.lock\0');+ try {+ hash.update(+ execFileSync('git', ['-C', repositoryRoot, 'show', 'HEAD:bun.lock'], {+ encoding: 'utf8',+ maxBuffer: 100 * 1024 * 1024,+ }),+ );+ } catch {+ const lockfile = join(repositoryRoot, 'bun.lock');+ hash.update(+ existsSync(lockfile) ? readFileSync(lockfile, 'utf8') : '<missing>',+ );+ }+const digest = hash.digest('hex');environmentHashCache.set(repositoryRoot, digest);return digest;@@ -299,7 +253,6 @@ export const createTwoslashCacheContext = ({}): TwoslashCacheContext => {return {localRoot: join(docsRoot, 'node_modules', '.cache', 'twoslash'),- sharedRoot: getSharedTwoslashCacheRoot(docsRoot),environmentHash: getTwoslashEnvironmentHash(docsRoot),versions,workspacePackages: getTwoslashWorkspacePackages(docsRoot),@@ -398,135 +351,6 @@ export const getTwoslashLocalCachePath = (return join(context.localRoot, `${key}.json`);};-const getSharedCachePath = (- context: TwoslashCacheContext,- key: string,-): string | null => {- return context.sharedRoot ? join(context.sharedRoot, `${key}.json`) : null;-};--const serializeSharedCacheEntry = (key: string, html: string): string => {- const header: SharedCacheHeader = {- fileVersion: SHARED_CACHE_FILE_VERSION,- key,- contentHash: createHash('sha256').update(html).digest('hex'),- };- return `${JSON.stringify(header)}\n${html}`;-};--const deserializeSharedCacheEntry = (- contents: string,- expectedKey: string,-): string | null => {- const headerEnd = contents.indexOf('\n');- if (headerEnd === -1) {- return null;- }-- try {- const header = JSON.parse(- contents.slice(0, headerEnd),- ) as SharedCacheHeader;- const html = contents.slice(headerEnd + 1);- if (- header.fileVersion !== SHARED_CACHE_FILE_VERSION ||- header.key !== expectedKey ||- header.contentHash !== createHash('sha256').update(html).digest('hex')- ) {- return null;- }-- return html;- } catch {- return null;- }-};--const readSharedCacheEntry = (path: string, key: string): string | null => {- try {- return deserializeSharedCacheEntry(readFileSync(path, 'utf8'), key);- } catch {- return null;- }-};--const touchSharedCacheEntry = (path: string): void => {- try {- const stats = statSync(path);- if (Date.now() - stats.mtimeMs > DAY_MS) {- const now = new Date();- utimesSync(path, now, now);- }- } catch {- // Cache maintenance must not fail a docs build.- }-};--const publishSharedCacheEntry = (- path: string,- key: string,- html: string,-): void => {- const existing = readSharedCacheEntry(path, key);- if (existing !== null) {- touchSharedCacheEntry(path);- return;- }-- mkdirSync(dirname(path), {recursive: true});- const temporaryPath = getTemporaryPath(path);- writeFileSync(temporaryPath, serializeSharedCacheEntry(key, html), {- encoding: 'utf8',- flag: 'wx',- });-- try {- if (!existsSync(path)) {- try {- // A hard link installs the immutable object without replacing a winner.- linkSync(temporaryPath, path);- return;- } catch (error) {- if (- !isNodeError(error, 'EEXIST') &&- readSharedCacheEntry(path, key) !== null- ) {- return;- }- }- }-- if (readSharedCacheEntry(path, key) !== null) {- return;- }-- // Corrupt entries and filesystems without hard links use a per-key lock- // before atomically installing the replacement.- const lockPath = `${path}.lock`;- try {- mkdirSync(lockPath);- } catch {- return;- }-- try {- if (readSharedCacheEntry(path, key) === null) {- if (existsSync(path)) {- safeUnlink(path);- }-- renameSync(temporaryPath, path);- }- } finally {- rmSync(lockPath, {recursive: true, force: true});- }- } finally {- if (existsSync(temporaryPath)) {- safeUnlink(temporaryPath);- }- }-};-export const readTwoslashCacheEntry = ({context,key,@@ -534,29 +358,15 @@ export const readTwoslashCacheEntry = ({context: TwoslashCacheContext;key: string;}): string | null => {- const localPath = getTwoslashLocalCachePath(context, key);try {- const localContents = readFileSync(localPath, 'utf8');- if (localContents.length > 0) {- return localContents;- }+ const contents = readFileSync(+ getTwoslashLocalCachePath(context, key),+ 'utf8',+ );+ return contents.length > 0 ? contents : null;} catch {- // Fall through to the shared cache.- }-- const sharedPath = getSharedCachePath(context, key);- if (!sharedPath) {return null;}-- const html = readSharedCacheEntry(sharedPath, key);- if (html === null) {- return null;- }-- touchSharedCacheEntry(sharedPath);- writeFileAtomically(localPath, html);- return html;};export const writeTwoslashCacheEntry = ({@@ -569,156 +379,4 @@ export const writeTwoslashCacheEntry = ({html: string;}): void => {writeFileAtomically(getTwoslashLocalCachePath(context, key), html);- const sharedPath = getSharedCachePath(context, key);- if (!sharedPath) {- return;- }-- try {- publishSharedCacheEntry(sharedPath, key, html);- } catch {- // The local cache is sufficient for this build. A later prewarm can retry- // publishing to the shared cache.- }-};--export const publishLocalTwoslashCacheEntry = ({- context,- key,-}: {- context: TwoslashCacheContext;- key: string;-}): void => {- const sharedPath = getSharedCachePath(context, key);- if (!sharedPath) {- return;- }-- try {- const html = readFileSync(getTwoslashLocalCachePath(context, key), 'utf8');- if (html.length > 0) {- publishSharedCacheEntry(sharedPath, key, html);- }- } catch {- // Publishing is only an optimization.- }-};--const readEnvNumber = (name: string, fallback: number): number => {- const value = process.env[name];- if (!value) {- return fallback;- }-- const parsed = Number(value);- return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;-};--export const garbageCollectSharedTwoslashCache = (- context: TwoslashCacheContext,-): void => {- if (!context.sharedRoot || !existsSync(context.sharedRoot)) {- return;- }-- const now = Date.now();- const gcIntervalMs = readEnvNumber(- 'TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS',- DEFAULT_GC_INTERVAL_MS,- );- const stampPath = join(context.sharedRoot, '.gc-stamp');- try {- if (now - statSync(stampPath).mtimeMs < gcIntervalMs) {- return;- }- } catch {- // No previous GC stamp.- }-- const lockPath = join(context.sharedRoot, '.gc-lock');- try {- mkdirSync(lockPath);- } catch {- try {- if (now - statSync(lockPath).mtimeMs <= DAY_MS) {- return;- }-- rmSync(lockPath, {recursive: true, force: true});- mkdirSync(lockPath);- } catch {- return;- }- }-- try {- const maxAgeMs = readEnvNumber(- 'TWOSLASH_SHARED_CACHE_MAX_AGE_MS',- DEFAULT_MAX_CACHE_AGE_MS,- );- const maxBytes = readEnvNumber(- 'TWOSLASH_SHARED_CACHE_MAX_BYTES',- DEFAULT_MAX_CACHE_BYTES,- );- const entries: {path: string; size: number; mtimeMs: number}[] = [];-- for (const file of readdirSync(context.sharedRoot)) {- const path = join(context.sharedRoot, file);- if (file.endsWith('.tmp') || file.endsWith('.lock')) {- try {- if (now - statSync(path).mtimeMs > DAY_MS) {- if (file.endsWith('.lock')) {- rmSync(path, {recursive: true, force: true});- } else {- safeUnlink(path);- }- }- } catch {- // The file disappeared concurrently.- }-- continue;- }-- if (!file.endsWith('.json')) {- continue;- }-- try {- const stats = statSync(path);- const key = file.slice(0, -'.json'.length);- if (- now - stats.mtimeMs > maxAgeMs ||- readSharedCacheEntry(path, key) === null- ) {- safeUnlink(path);- continue;- }-- entries.push({path, size: stats.size, mtimeMs: stats.mtimeMs});- } catch {- // The entry disappeared concurrently.- }- }-- let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);- for (const entry of entries.sort((a, b) => a.mtimeMs - b.mtimeMs)) {- if (totalBytes <= maxBytes) {- break;- }-- try {- safeUnlink(entry.path);- totalBytes -= entry.size;- } catch {- // Keep going if another process is using or removed the entry.- }- }-- writeFileAtomically(stampPath, String(now));- } catch {- // Shared cache maintenance must never fail prewarming.- } finally {- rmSync(lockPath, {recursive: true, force: true});- }};diff --git a/turbo.json b/turbo.jsonindex 3fd64fc36a..0098b82222 100644--- a/turbo.json+++ b/turbo.json@@ -120,10 +120,6 @@"NODE_OPTIONS","REMOTION_DOCS_LOW_MEMORY_BUILD","TWOSLASH_RECYCLE_LIMIT_BYTES",- "TWOSLASH_SHARED_CACHE_DIR",- "TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS",- "TWOSLASH_SHARED_CACHE_MAX_AGE_MS",- "TWOSLASH_SHARED_CACHE_MAX_BYTES","TWOSLASH_STALL_TIMEOUT_MS","TWOSLASH_WORKER_COUNT","VERCEL"