feat: bump typescript (#14507)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Chores**
  * Upgraded TypeScript toolchain to v5.9.3 across packages and tooling.
* Removed legacy ts-node and migrated developer tooling to newer
runtimes (tsx/SWC) where applicable.
* **Documentation**
* Updated developer CLI docs and runtime behavior notes to reflect the
new loader/runtime for running TypeScript files; no changes to public
APIs or end-user behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
DarkSky
2026-02-24 13:22:46 +08:00
committed by GitHub
parent c2c7dde06c
commit 046e126054
48 changed files with 371 additions and 402 deletions
+2 -2
View File
@@ -40,9 +40,9 @@ yarn affine init
## Tricks
### Define scripts to run a .ts files without `--loader ts-node/esm/transpile-only`
### Define scripts to run a .ts files without manually wiring a TypeScript loader
`affine run` will automatically inject `ts-node`'s transpile service(swc used) for your scripts
`affine run` will automatically inject `tsx` for your scripts
```json
{
+7 -2
View File
@@ -7,7 +7,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
const scriptsFolder = join(fileURLToPath(import.meta.url), '..', '..');
const scriptsSrcFolder = join(scriptsFolder, 'src');
const projectRoot = join(scriptsFolder, '..', '..');
const loader = join(scriptsFolder, 'register.js');
const serverRoot = join(projectRoot, 'packages', 'backend', 'server');
const tsRuntimeRegister = join(scriptsFolder, 'register.js');
const [node, _self, file, ...options] = process.argv;
@@ -60,7 +61,11 @@ if (
scriptLocation.endsWith('.ts') ||
scriptLocation.startsWith(scriptsFolder)
) {
nodeOptions.unshift(`--import=${pathToFileURL(loader)}`);
if (scriptLocation.startsWith(serverRoot)) {
nodeOptions.unshift(`--import=${pathToFileURL(tsRuntimeRegister)}`);
} else {
nodeOptions.unshift('--import=tsx');
}
} else {
nodeOptions.unshift('--experimental-specifier-resolution=node');
}
+162 -10
View File
@@ -1,13 +1,165 @@
import { create, createEsmHooks, register } from 'ts-node';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const service = create({
experimentalSpecifierResolution: 'node',
esm: true,
transpileOnly: true,
});
import { transform } from '@swc/core';
register(service);
const hooks = createEsmHooks(service);
const TS_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);
const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
const ALL_EXTENSIONS = [...TS_EXTENSIONS, ...JS_EXTENSIONS];
export const resolve = hooks.resolve;
export const load = hooks.load;
const JS_EXTENSION_TO_TS = {
'.js': ['.ts', '.tsx', '.js'],
'.mjs': ['.mts', '.mjs'],
'.cjs': ['.cts', '.cjs'],
};
const transformCache = new Map();
function createCandidates(basePath) {
const parsedExt = path.extname(basePath);
const hasKnownExtension =
parsedExt in JS_EXTENSION_TO_TS || ALL_EXTENSIONS.includes(parsedExt);
const ext = hasKnownExtension ? parsedExt : '';
const stem = ext ? basePath.slice(0, -ext.length) : basePath;
const candidates = new Set();
const extensions = ext ? (JS_EXTENSION_TO_TS[ext] ?? [ext]) : ALL_EXTENSIONS;
for (const candidateExt of extensions) {
candidates.add(`${stem}${candidateExt}`);
}
if (!ext) {
for (const candidateExt of ALL_EXTENSIONS) {
candidates.add(path.join(basePath, `index${candidateExt}`));
}
}
return candidates;
}
function isPathLike(specifier) {
return (
specifier.startsWith('./') ||
specifier.startsWith('../') ||
specifier.startsWith('/') ||
specifier.startsWith('file:')
);
}
function resolvePathLikeSpecifier(specifier, parentURL) {
if (!isPathLike(specifier)) {
return undefined;
}
const [specifierWithoutQuery, queryString = ''] = specifier.split('?');
const querySuffix = queryString ? `?${queryString}` : '';
const parentPath = parentURL?.startsWith('file:')
? fileURLToPath(parentURL)
: path.join(process.cwd(), 'index.js');
const basePath = specifierWithoutQuery.startsWith('file:')
? fileURLToPath(specifierWithoutQuery)
: path.isAbsolute(specifierWithoutQuery)
? specifierWithoutQuery
: path.resolve(path.dirname(parentPath), specifierWithoutQuery);
for (const candidate of createCandidates(basePath)) {
try {
if (fs.statSync(candidate).isFile()) {
return `${pathToFileURL(candidate).href}${querySuffix}`;
}
} catch {
// ignore missing candidates
}
}
return undefined;
}
export async function resolve(specifier, context, nextResolve) {
try {
return await nextResolve(specifier, context);
} catch (error) {
const resolvedUrl = resolvePathLikeSpecifier(specifier, context.parentURL);
if (resolvedUrl) {
return {
url: resolvedUrl,
shortCircuit: true,
};
}
throw error;
}
}
export async function load(url, context, nextLoad) {
const [urlWithoutQuery] = url.split('?');
if (!urlWithoutQuery.startsWith('file:')) {
return nextLoad(url, context);
}
const filePath = fileURLToPath(urlWithoutQuery);
if (!TS_EXTENSIONS.has(path.extname(filePath))) {
return nextLoad(url, context);
}
const stat = await fs.promises.stat(filePath);
const cached = transformCache.get(filePath);
if (cached?.mtimeMs === stat.mtimeMs) {
return {
format: cached.format,
source: cached.source,
shortCircuit: true,
};
}
const sourceText = await fs.promises.readFile(filePath, 'utf8');
const isCommonJs = filePath.endsWith('.cts');
const moduleType = isCommonJs ? 'commonjs' : 'es6';
const tsx = filePath.endsWith('.tsx');
let output;
try {
output = await transform(sourceText, {
filename: filePath,
sourceMaps: 'inline',
module: { type: moduleType },
jsc: {
target: 'es2022',
keepClassNames: true,
experimental: { keepImportAttributes: true },
parser: {
syntax: 'typescript',
tsx,
decorators: true,
dynamicImport: true,
},
transform: {
legacyDecorator: true,
decoratorMetadata: true,
useDefineForClassFields: false,
react: tsx
? { runtime: 'automatic', importSource: 'react' }
: undefined,
},
},
});
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`[swc-loader] Failed to compile ${filePath}\n${detail}`);
}
const source = output.code ?? '';
const format = isCommonJs ? 'commonjs' : 'module';
transformCache.set(filePath, { mtimeMs: stat.mtimeMs, source, format });
return {
format,
source,
shortCircuit: true,
};
}
+2 -2
View File
@@ -47,9 +47,9 @@
"swc-loader": "^0.2.6",
"tailwindcss": "^4.1.17",
"terser-webpack-plugin": "^5.3.10",
"ts-node": "^10.9.2",
"tsx": "^4.21.0",
"typanion": "^3.14.0",
"typescript": "^5.5.4",
"typescript": "^5.9.3",
"webpack": "^5.102.1",
"webpack-dev-server": "^5.2.0",
"webpack-merge": "^6.0.1"
+10 -4
View File
@@ -11,11 +11,15 @@ interface RunScriptOptions {
}
const currentDir = Path.dir(import.meta.url);
const serverRuntimeLoader = currentDir
.join('../register.js')
.toFileUrl()
.toString();
const ignoreLoaderScripts = [
'vitest',
'vite',
'ts-node',
'tsx',
'prisma',
'cap',
'tsc',
@@ -161,13 +165,15 @@ export class RunCommand extends PackageCommand {
args = extractedArgs;
const bin = args[0] === 'yarn' ? args[1] : args[0];
const loader = currentDir.join('../register.js').toFileUrl().toString();
const loader = pkg.name === '@affine/server' ? serverRuntimeLoader : 'tsx';
const hasKnownLoader =
process.env.NODE_OPTIONS?.includes('tsx') ||
process.env.NODE_OPTIONS?.includes(serverRuntimeLoader);
// very simple test for auto ts/mjs scripts
const isLoaderRequired =
!ignoreLoaderScripts.some(ignore => new RegExp(ignore).test(bin)) ||
process.env.NODE_OPTIONS?.includes('ts-node/esm') ||
hasKnownLoader ||
process.env.NODE_OPTIONS?.includes(loader);
let NODE_OPTIONS = process.env.NODE_OPTIONS