fix(build): remove private fields (#3514)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(build): remove private fields * chore: format scripts * test: add test code * reduce package.json diff * feat(build): add progress for removing private fields * feat: rename `scripts` to `build`
authored by Shotaro Nakamura · committed by GitHub · parent aa50e0a · Browse files · 8 files·+250 added−93 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+250 added−93 removed
- tests:+21 added−0 removed
- other:+229 added−93 removed
Provenance
- Commit
6cf01e5- Tree
ea7c745- Author
Shotaro Nakamura <79000684+nakasyou@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
aa50e0a
8 files changed+250 added−93 removed
added:build/build.ts+106 added
1+/*2+ This script is heavily inspired by `built.ts` used in @kaze-style/react.3+ https://github.com/taishinaritomi/kaze-style/blob/main/scripts/build.ts4+ MIT License5+ Copyright (c) 2022 Taishi Naritomi6+*/7+8+/// <reference types="bun-types/bun" />9+10+import fs, { write } from 'fs'11+import path from 'path'12+import arg from 'arg'13+import { build } from 'esbuild'14+import type { Plugin, PluginBuild, BuildOptions } from 'esbuild'15+import * as glob from 'glob'16+import { removePrivateFields } from './remove-private-fields'17+import { $, stdout } from 'bun'18+19+const args = arg({20+ '--watch': Boolean,21+})22+23+const isWatch = args['--watch'] || false24+25+const entryPoints = glob.sync('./src/**/*.ts', {26+ ignore: ['./src/**/*.test.ts', './src/mod.ts', './src/middleware.ts', './src/deno/**/*.ts'],27+})28+29+/*30+ This plugin is inspired by the following.31+ https://github.com/evanw/esbuild/issues/622#issuecomment-76946261132+*/33+const addExtension = (extension: string = '.js', fileExtension: string = '.ts'): Plugin => ({34+ name: 'add-extension',35+ setup(build: PluginBuild) {36+ build.onResolve({ filter: /.*/ }, (args) => {37+ if (args.importer) {38+ const p = path.join(args.resolveDir, args.path)39+ let tsPath = `${p}${fileExtension}`40+41+ let importPath = ''42+ if (fs.existsSync(tsPath)) {43+ importPath = args.path + extension44+ } else {45+ tsPath = path.join(args.resolveDir, args.path, `index${fileExtension}`)46+ if (fs.existsSync(tsPath)) {47+ if (args.path.endsWith('/')) {48+ importPath = `${args.path}index${extension}`49+ } else {50+ importPath = `${args.path}/index${extension}`51+ }52+ }53+ }54+ return { path: importPath, external: true }55+ }56+ })57+ },58+})59+60+const commonOptions: BuildOptions = {61+ watch: isWatch,62+ entryPoints,63+ logLevel: 'info',64+ platform: 'node',65+}66+67+const cjsBuild = () =>68+ build({69+ ...commonOptions,70+ outbase: './src',71+ outdir: './dist/cjs',72+ format: 'cjs',73+ })74+75+const esmBuild = () =>76+ build({77+ ...commonOptions,78+ bundle: true,79+ outbase: './src',80+ outdir: './dist',81+ format: 'esm',82+ plugins: [addExtension('.js')],83+ })84+85+Promise.all([esmBuild(), cjsBuild()])86+87+await $`tsc ${88+ isWatch ? '-w' : ''89+} --emitDeclarationOnly --declaration --project tsconfig.build.json`.nothrow()90+91+// Remove #private fields92+const dtsEntries = glob.globSync('./dist/types/**/*.d.ts')93+const writer = stdout.writer()94+writer.write('\n')95+let lastOutputLength = 096+for (let i = 0; i < dtsEntries.length; i++) {97+ const entry = dtsEntries[i]98+99+ const message = `Removing private fields(${i}/${dtsEntries.length}): ${entry}`100+ writer.write(`\r${' '.repeat(lastOutputLength)}`)101+ lastOutputLength = message.length102+ writer.write(`\r${message}`)103+104+ fs.writeFileSync(entry, removePrivateFields(entry))105+}106+writer.write('\n')added:build/remove-private-fields.test.ts+21 added
123456789101112131415161718192021/// <reference types="vitest/globals" />
import { removePrivateFields } from './remove-private-fields'import fs from 'node:fs/promises'import path from 'node:path'import os from 'node:os'
describe('removePrivateFields', () => { it('Works', async () => { const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'removePrivateFields')) const tsPath = path.join(tmpDir, 'class.ts') await fs.writeFile(tsPath, 'class X { #private: number = 0; a: number = 0 }') expect(removePrivateFields(tsPath)).toBe(`class X { a: number = 0;}`) }) it('Should throw error when path does not exist', () => { expect(() => removePrivateFields('./unknown.ts')).toThrowError(Error) })})added:build/remove-private-fields.ts+52 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import * as ts from 'typescript'
const removePrivateTransformer = <T extends ts.Node>(ctx: ts.TransformationContext) => { const visit: ts.Visitor = (node) => { if (ts.isClassDeclaration(node)) { const newMembers = node.members.filter((elem) => { if (ts.isPropertyDeclaration(elem) || ts.isMethodDeclaration(elem)) { for (const modifier of elem.modifiers ?? []) { if (modifier.kind === ts.SyntaxKind.PrivateKeyword) { return false } } } if (elem.name && ts.isPrivateIdentifier(elem.name)) { return false } return true }) return ts.factory.createClassDeclaration( node.modifiers, node.name, node.typeParameters, node.heritageClauses, newMembers ) } return ts.visitEachChild(node, visit, ctx) }
return (node: T) => { const visited = ts.visitNode(node, visit) if (!visited) { throw new Error('The result visited is undefined.') } return visited }}
export const removePrivateFields = (tsPath: string) => { const program = ts.createProgram([tsPath], { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, }) const file = program.getSourceFile(tsPath)
const transformed = ts.transform(file!, [removePrivateTransformer]) const printer = ts.createPrinter() const transformedSourceFile = transformed.transformed[0] as ts.SourceFile const code = printer.printFile(transformedSourceFile) transformed.dispose() return code}deleted:build.ts-84 removed
1-/*2- This script is heavily inspired by `built.ts` used in @kaze-style/react.3- https://github.com/taishinaritomi/kaze-style/blob/main/scripts/build.ts4- MIT License5- Copyright (c) 2022 Taishi Naritomi6-*/7-8-import { exec } from 'child_process'9-import fs from 'fs'10-import path from 'path'11-import arg from 'arg'12-import { build } from 'esbuild'13-import type { Plugin, PluginBuild, BuildOptions } from 'esbuild'14-import glob from 'glob'15-16-const args = arg({17- '--watch': Boolean,18-})19-20-const isWatch = args['--watch'] || false21-22-const entryPoints = glob.sync('./src/**/*.ts', {23- ignore: ['./src/**/*.test.ts', './src/mod.ts', './src/middleware.ts', './src/deno/**/*.ts'],24-})25-26-/*27- This plugin is inspired by the following.28- https://github.com/evanw/esbuild/issues/622#issuecomment-76946261129-*/30-const addExtension = (extension: string = '.js', fileExtension: string = '.ts'): Plugin => ({31- name: 'add-extension',32- setup(build: PluginBuild) {33- build.onResolve({ filter: /.*/ }, (args) => {34- if (args.importer) {35- const p = path.join(args.resolveDir, args.path)36- let tsPath = `${p}${fileExtension}`37-38- let importPath = ''39- if (fs.existsSync(tsPath)) {40- importPath = args.path + extension41- } else {42- tsPath = path.join(args.resolveDir, args.path, `index${fileExtension}`)43- if (fs.existsSync(tsPath)) {44- if (args.path.endsWith('/')) {45- importPath = `${args.path}index${extension}`46- } else {47- importPath = `${args.path}/index${extension}`48- }49- }50- }51- return { path: importPath, external: true }52- }53- })54- },55-})56-57-const commonOptions: BuildOptions = {58- watch: isWatch,59- entryPoints,60- logLevel: 'info',61- platform: 'node',62-}63-64-const cjsBuild = () =>65- build({66- ...commonOptions,67- outbase: './src',68- outdir: './dist/cjs',69- format: 'cjs',70- })71-72-const esmBuild = () =>73- build({74- ...commonOptions,75- bundle: true,76- outbase: './src',77- outdir: './dist',78- format: 'esm',79- plugins: [addExtension('.js')],80- })81-82-Promise.all([esmBuild(), cjsBuild()])83-84-exec(`tsc ${isWatch ? '-w' : ''} --emitDeclarationOnly --declaration --project tsconfig.build.json`)modified:bun.lockbbinary
A binary file, modified.
modified:package.json+7 added-6 removed
20 unmodified lines21 "test:lambda-edge": "vitest --run --config ./runtime-tests/lambda-edge/vitest.config.ts",22 "test:all": "bun run test && bun test:deno && bun test:bun && bun test:fastly && bun test:node && bun test:workerd && bun test:lambda && bun test:lambda-edge",23 "lint": "eslint src runtime-tests",24 "lint:fix": "eslint src runtime-tests --fix",25- "format": "prettier --check --cache \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\"",26- "format:fix": "prettier --write --cache --cache-strategy metadata \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\"",27- "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json ",28- "build": "bun run --shell bun remove-dist && bun ./build.ts && bun run copy:package.cjs.json",25+ "format": "prettier --check --cache \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\"",26+ "format:fix": "prettier --write --cache --cache-strategy metadata \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\"",27+ "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json",28+ "build": "bun run --shell bun remove-dist && bun ./build/build.ts && bun run copy:package.cjs.json",29 "postbuild": "publint",30- "watch": "bun run --shell bun remove-dist && bun ./build.ts --watch && bun run copy:package.cjs.json",30+ "watch": "bun run --shell bun remove-dist && bun ./build/build.ts --watch && bun run copy:package.cjs.json",31 "coverage": "vitest --run --coverage",32 "prerelease": "bun test:deno && bun run build",33 "release": "np",34 "remove-dist": "rm -rf dist"590 unmodified lines625 "@types/node": "20.11.4",626 "@types/supertest": "^2.0.12",627 "@vitest/coverage-v8": "^2.0.5",628 "arg": "^5.0.2",629+ "bun-types": "^1.1.30",630 "esbuild": "^0.15.12",631 "eslint": "^9.10.0",631- "glob": "7.2.3",632+ "glob": "^11.0.0",633 "jsdom": "^22.1.0",634 "msw": "^2.3.0",635 "np": "7.7.0",636 "prettier": "^2.6.2",13 unmodified linesmodified:vitest.config.ts+1 added-1 removed
6 unmodified lines7891011111213141520 unmodified lines6 unmodified lines jsxImportSource: __dirname + '/../src/jsx', }, test: { globals: true, include: ['**/src/**/(*.)+(spec|test).+(ts|tsx|js)'], include: ['**/src/**/(*.)+(spec|test).+(ts|tsx|js)', '**/scripts/**/(*.)+(spec|test).+(ts|tsx|js)'], exclude: [...configDefaults.exclude, '**/sandbox/**', '**/*.case.test.+(ts|tsx|js)'], setupFiles: ['./.vitest.config/setup-vitest.ts'], coverage: { enabled: true,20 unmodified linesmodified:yarn.lock+63 added-2 removed
1 # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2 # yarn lockfile v13-# bun ./bun.lockb --hash: 229521234768470F-a4cd9955ab6a6ada-9D052F6AF60C5C4D-0bfb97a3d93af7423+# bun ./bun.lockb --hash: 77B78F6BF9FCD5E8-99bd6727146efa0f-3A60C19E44E6AEA6-b935857e930aa3074 5 6 "@ampproject/remapping@^2.3.0":7 version "2.3.0"1201 unmodified lines1209 integrity sha512-6I0fMH8Aoy2lOejL3s4LhyIYX34DPwY8bl5xlNjBvUEk8OHrcuzsFt+Ied4LvJihbtXPM+8zUqdydfIti86v9g==1210 dependencies:1211 undici-types "~5.26.4"1212 1213+"@types/node@~20.12.8":1214+ version "20.12.14"1215+ resolved "https://registry.npmjs.org/@types/node/-/node-20.12.14.tgz"1216+ integrity sha512-scnD59RpYD91xngrQQLGkE+6UrHUPzeKZWhhjBSa3HSkwjbQc38+q3RoIVEwxQGRw3M+j5hpNAM+lgV3cVormg==1217+ dependencies:1218+ undici-types "~5.26.4"1219+1220 "@types/node@*", "@types/node@^22.5.5":1221 version "22.6.1"1222 resolved "https://registry.npmjs.org/@types/node/-/node-22.6.1.tgz"1223 integrity sha512-V48tCfcKb/e6cVUigLAaJDAILdMP0fUW6BidkPK4GpGjXcfbnoHasCZDwz3N3yVt5we2RHm4XTQCpv0KJz9zqw==55 unmodified lines1279 version "3.0.0"1280 resolved "https://registry.npmjs.org/@types/wrap-ansi/-/wrap-ansi-3.0.0.tgz"1281 integrity sha512-ltIpx+kM7g/MLRZfkbL7EsCEjfzCcScLpkg37eXEtx5kmrAKBkTJwd1GIAjDSL8wTpM6Hzn5YO4pSb91BEwu1g==1282 1283+"@types/ws@~8.5.10":1284+ version "8.5.12"1285+ resolved "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz"1286+ integrity sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ==1287+ dependencies:1288+ "@types/node" "*"1289+1290 "@typescript-eslint/eslint-plugin@^8.7.0":1291 version "8.7.0"1292 resolved "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.7.0.tgz"1293 integrity sha512-RIHOoznhA3CCfSTFiB6kBGLQtB/sox+pJ6jeFu6FxJvqL8qRxq/FfGO/UhsGgQM9oGdXkV4xUgli+dt26biB6A==440 unmodified lines1734 version "1.0.3"1735 resolved "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz"1736 integrity sha512-uYBjakWipfaO/bXI7E8rq6kpwHRZK5cNYrUv2OzZSI/FvmdMyXJ2tG9dKcjEC5YHmHpUAwsargWIZNWdxb/bnQ==1737 1738+bun-types@^1.1.30:1739+ version "1.1.30"1740+ resolved "https://registry.npmjs.org/bun-types/-/bun-types-1.1.30.tgz"1741+ integrity sha512-mGh7NLisOXskBU62DxLS+/nwmLlCYHYAkCzdo4DZ9+fzrpP41hAdOqaN4DO6tQfenHb4pYb0/shw29k4/6I2yQ==1742+ dependencies:1743+ "@types/ws" "~8.5.10"1744+ "@types/node" "~20.12.8"1745+1746 cac@^6.7.14:1747 version "6.7.14"1748 resolved "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz"1749 integrity sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==1359 unmodified lines3109 version "1.5.0"3110 resolved "https://registry.npmjs.org/github-url-from-git/-/github-url-from-git-1.5.0.tgz"3111 integrity sha512-WWOec4aRI7YAykQ9+BHmzjyNlkfJFG8QLXnDTsLz/kZefq7qkzdfo4p6fkYYMIq1aj+gZcQs/1HQhQh3DPPxlQ==3112 3091-glob@7.2.3, glob@^7.1.3:3113+glob@^7.1.3:3114 version "7.2.3"3115 resolved "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz"3116 integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==3117 dependencies:26 unmodified lines3144 path-scurry "^1.11.1"3145 foreground-child "^3.1.0"3146 package-json-from-dist "^1.0.0"3147 3148+glob@^11.0.0:3149+ version "11.0.0"3150+ resolved "https://registry.npmjs.org/glob/-/glob-11.0.0.tgz"3151+ integrity sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g==3152+ dependencies:3153+ minipass "^7.1.2"3154+ jackspeak "^4.0.1"3155+ minimatch "^10.0.0"3156+ path-scurry "^2.0.0"3157+ foreground-child "^3.1.0"3158+ package-json-from-dist "^1.0.0"3159+3160 glob-parent@^5.1.2, glob-parent@~5.1.2:3161 version "5.1.2"3162 resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz"3163 integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==634 unmodified lines3798 "@isaacs/cliui" "^8.0.2"3799 optionalDependencies:3800 "@pkgjs/parseargs" "^0.11.0"3801 3802+jackspeak@^4.0.1:3803+ version "4.0.2"3804+ resolved "https://registry.npmjs.org/jackspeak/-/jackspeak-4.0.2.tgz"3805+ integrity sha512-bZsjR/iRjl1Nk1UkjGpAzLNfQtzuijhn2g+pbZb98HQ1Gk8vM9hfbxeMBP+M2/UUdwj0RqGG3mlvk2MsAqwvEw==3806+ dependencies:3807+ "@isaacs/cliui" "^8.0.2"3808+3809 js-tokens@^4.0.0:3810 version "4.0.0"3811 resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz"3812 integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==251 unmodified lines4064 version "10.4.3"4065 resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz"4066 integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==4067 4068+lru-cache@^11.0.0:4069+ version "11.0.1"4070+ resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.1.tgz"4071+ integrity sha512-CgeuL5uom6j/ZVrg7G/+1IXqRY8JXX4Hghfy5YE0EhoYQWvndP1kufu58cmZLNIDKnRhZrXfdS9urVWx98AipQ==4072+4073 magic-string@^0.25.3:4074 version "0.25.9"4075 resolved "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz"4076 integrity sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==189 unmodified lines4266 integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==4267 dependencies:4268 brace-expansion "^2.0.1"4269 4270+minimatch@^10.0.0:4271+ version "10.0.1"4272+ resolved "https://registry.npmjs.org/minimatch/-/minimatch-10.0.1.tgz"4273+ integrity sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==4274+ dependencies:4275+ brace-expansion "^2.0.1"4276+4277 minimist@^1.2.0:4278 version "1.2.8"4279 resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz"4280 integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==519 unmodified lines4800 dependencies:4801 minipass "^5.0.0 || ^6.0.2 || ^7.0.0"4802 lru-cache "^10.2.0"4803 4804+path-scurry@^2.0.0:4805+ version "2.0.0"4806+ resolved "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz"4807+ integrity sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==4808+ dependencies:4809+ lru-cache "^11.0.0"4810+ minipass "^7.1.2"4811+4812 path-to-regexp@^6.2.0, path-to-regexp@^6.3.0:4813 version "6.3.0"4814 resolved "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz"4815 integrity sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==1480 unmodified lines