diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82d66df..338d9e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,9 @@ jobs: - name: Build packages run: pnpm build + - name: Check types + run: pnpm typecheck + - name: Set node version to ${{ matrix.node }} for testing uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: diff --git a/MAINTENANCE.md b/MAINTENANCE.md index a0e7fd1..24a100d 100644 --- a/MAINTENANCE.md +++ b/MAINTENANCE.md @@ -24,12 +24,12 @@ Exact version: pnpm exec bumpp --release 2.14.0 ``` -The release command is defined in [`package.json`](./package.json) and uses [`bumpp`](https://www.npmjs.com/package/bumpp) with shared settings in [`bump.config.mjs`](./bump.config.mjs). +The release command is defined in [`package.json`](./package.json) and uses [`bumpp`](https://www.npmjs.com/package/bumpp) with shared settings in [`bump.config.ts`](./bump.config.ts). It will: 1. Bump both package versions. -2. Run `pnpm build` and `pnpm test`. +2. Run `pnpm build`, `pnpm typecheck`, and `pnpm test`. 3. Create commit `vX.Y.Z`. 4. Create tag `vX.Y.Z`. 5. Push the commit and tag to `origin`. @@ -72,11 +72,12 @@ Build both packages with tsdown using Node.js 22.18+, 24.11+, or 26+: pnpm build ``` -Each package bundles its JavaScript into `dist/index.js`. Runtime dependencies remain external, and the handwritten `index.d.ts` declarations are published alongside the bundle. Packing or publishing a package runs its build automatically. +Each package bundles its TypeScript into `dist/index.js` and generates declarations in `dist/index.d.ts`. Runtime dependencies remain external. Packing or publishing a package runs its build automatically. -Run the workspace tests after building: +Check types and run the workspace tests after building: ```bash +pnpm typecheck pnpm test ``` @@ -96,5 +97,5 @@ If the GitHub Actions publish job fails: ## Files - [`package.json`](./package.json) -- [`bump.config.mjs`](./bump.config.mjs) +- [`bump.config.ts`](./bump.config.ts) - [`.github/workflows/publish.yml`](./.github/workflows/publish.yml) diff --git a/bump.config.mjs b/bump.config.ts similarity index 67% rename from bump.config.mjs rename to bump.config.ts index 5060095..591ea32 100644 --- a/bump.config.mjs +++ b/bump.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'bumpp' export default defineConfig({ recursive: true, - execute: 'pnpm build && pnpm test', + execute: 'pnpm build && pnpm typecheck && pnpm test', commit: 'v', tag: 'v', }) diff --git a/package.json b/package.json index 584df98..ce6b4a0 100644 --- a/package.json +++ b/package.json @@ -4,16 +4,19 @@ "scripts": { "build": "pnpm -r build", "test": "pnpm -r test", + "typecheck": "tsc --noEmit", "release": "bumpp", "lint": "oxlint --fix", "format": "oxfmt" }, "devDependencies": { + "@types/node": "^24.19.2", "bumpp": "^11.1.0", "lint-staged": "^17.4.1", "oxfmt": "^0.65.0", "oxlint": "^1.80.0", "tsdown": "^0.23.7", + "typescript": "^6.0.3", "vitest": "^4.1.12", "yorkie": "^2.0.0" }, @@ -21,7 +24,7 @@ "*": [ "oxfmt --no-error-on-unmatched-pattern" ], - "*.js": [ + "*.{js,ts}": [ "oxlint --fix" ] }, diff --git a/packages/launch-editor-middleware/README.md b/packages/launch-editor-middleware/README.md index 43f1a1a..14ce0f4 100644 --- a/packages/launch-editor-middleware/README.md +++ b/packages/launch-editor-middleware/README.md @@ -20,7 +20,7 @@ Both the line and column numbers are optional. `file://` URIs are also supported ## API -See [`index.d.ts`](./index.d.ts) for the full type definitions and the available arguments. +See [`index.ts`](https://github.com/vitejs/launch-editor/blob/main/packages/launch-editor-middleware/index.ts) for the full type definitions and the available arguments. ## Custom editor support diff --git a/packages/launch-editor-middleware/index.js b/packages/launch-editor-middleware/index.js deleted file mode 100644 index ac48959..0000000 --- a/packages/launch-editor-middleware/index.js +++ /dev/null @@ -1,36 +0,0 @@ -import path from 'node:path' -import launch from 'launch-editor' - -export default (specifiedEditor, srcRoot, onErrorCallback) => { - if (typeof specifiedEditor === 'function') { - onErrorCallback = specifiedEditor - specifiedEditor = undefined - } - - if (typeof srcRoot === 'function') { - onErrorCallback = srcRoot - srcRoot = undefined - } - - srcRoot = srcRoot || process.cwd() - - return function launchEditorMiddleware(req, res) { - const fullUrl = req.url.startsWith('http') ? req.url : `http://localhost${req.url}` - const url = URL.parse(fullUrl) - if (!url) { - res.statusCode = 500 - res.end(`launch-editor-middleware: invalid URL.`) - return - } - - const file = url.searchParams.get('file') - if (!file) { - res.statusCode = 500 - res.end(`launch-editor-middleware: required query param "file" is missing.`) - } else { - const resolved = file.startsWith('file://') ? file : path.resolve(srcRoot, file) - launch(resolved, specifiedEditor, onErrorCallback) - res.end() - } - } -} diff --git a/packages/launch-editor-middleware/index.test.js b/packages/launch-editor-middleware/index.test.ts similarity index 55% rename from packages/launch-editor-middleware/index.test.js rename to packages/launch-editor-middleware/index.test.ts index 0f32c49..b49bbea 100644 --- a/packages/launch-editor-middleware/index.test.js +++ b/packages/launch-editor-middleware/index.test.ts @@ -1,3 +1,5 @@ +import { IncomingMessage, ServerResponse } from 'node:http' +import { Socket } from 'node:net' import path from 'node:path' import { afterEach, describe, expect, test, vi } from 'vitest' @@ -12,87 +14,79 @@ vi.mock('launch-editor', () => ({ afterEach(() => { vi.clearAllMocks() + vi.restoreAllMocks() }) -const STATUS_NOT_ALTERED = -1 -class MockResponse { - constructor() { - this.statusCode = STATUS_NOT_ALTERED - this.body = '' - } +const STATUS_NOT_ALTERED = 200 - end(body) { - this.body = body || '' - } -} - -class MockRequest { - constructor(url) { - this.url = url - } +function createRequestResponse(url: string) { + const req = new IncomingMessage(new Socket()) + req.url = url + const res = new ServerResponse(req) + const end = vi.spyOn(res, 'end').mockReturnValue(res) + return { req, res, end } } describe('launchEditorMiddleware', () => { test('returns a 500 if no file query param', async () => { const middleware = launchEditorMiddleware('vim', undefined, noop) - const req = new MockRequest('https://localhost/') - const res = new MockResponse(null) + const { req, res, end } = createRequestResponse('https://localhost/') middleware(req, res) expect(res.statusCode).toBe(500) - expect(res.body).toBe('launch-editor-middleware: required query param "file" is missing.') + expect(end).toHaveBeenCalledExactlyOnceWith( + 'launch-editor-middleware: required query param "file" is missing.', + ) }) test('launches editor with specified file', async () => { const middleware = launchEditorMiddleware('vim', undefined, noop) const file = 'mock/file:100' - const req = new MockRequest(`https://localhost/?file=${file}`) - const res = new MockResponse(null) + const { req, res, end } = createRequestResponse(`https://localhost/?file=${file}`) middleware(req, res) expect(launch).toHaveBeenCalledExactlyOnceWith(path.resolve(file), 'vim', noop) expect(res.statusCode).toBe(STATUS_NOT_ALTERED) - expect(res.body).toBe('') + expect(end).toHaveBeenCalledExactlyOnceWith() }) test('falsy file parameter returns 500', async () => { const middleware = launchEditorMiddleware('vim', undefined, noop) - const req = new MockRequest('https://localhost/?file=') - const res = new MockResponse(null) + const { req, res, end } = createRequestResponse('https://localhost/?file=') middleware(req, res) expect(res.statusCode).toBe(500) - expect(res.body).toBe('launch-editor-middleware: required query param "file" is missing.') + expect(end).toHaveBeenCalledExactlyOnceWith( + 'launch-editor-middleware: required query param "file" is missing.', + ) }) test('returns 500 on invalid URL', async () => { const middleware = launchEditorMiddleware('vim', undefined, noop) - const req = new MockRequest('some invalid URL') - const res = new MockResponse(null) + const { req, res, end } = createRequestResponse('some invalid URL') middleware(req, res) expect(res.statusCode).toBe(500) - expect(res.body).toBe('launch-editor-middleware: invalid URL.') + expect(end).toHaveBeenCalledExactlyOnceWith('launch-editor-middleware: invalid URL.') }) test('correctly parse the url even if it contains only the path', async () => { const middleware = launchEditorMiddleware('vim', undefined, noop) const file = 'mock/file:100' - const req = new MockRequest(`/__open-in-editor?file=${file}`) - const res = new MockResponse(null) + const { req, res, end } = createRequestResponse(`/__open-in-editor?file=${file}`) middleware(req, res) expect(res.statusCode).toBe(STATUS_NOT_ALTERED) - expect(res.body).toBe('') + expect(end).toHaveBeenCalledExactlyOnceWith() }) }) diff --git a/packages/launch-editor-middleware/index.d.ts b/packages/launch-editor-middleware/index.ts similarity index 55% rename from packages/launch-editor-middleware/index.d.ts rename to packages/launch-editor-middleware/index.ts index c872ee5..5981e28 100644 --- a/packages/launch-editor-middleware/index.d.ts +++ b/packages/launch-editor-middleware/index.ts @@ -1,4 +1,6 @@ import type * as http from 'node:http' +import path from 'node:path' +import launch from 'launch-editor' type Middleware = (req: http.IncomingMessage, res: http.ServerResponse) => void type ErrorCallback = (fileName: string, errorMessage: string | null) => void @@ -10,7 +12,7 @@ type ErrorCallback = (fileName: string, errorMessage: string | null) => void * * @param onErrorCallback Optional callback for handling errors. */ -declare function launchEditorMiddleware(onErrorCallback?: ErrorCallback): Middleware +function launchEditorMiddleware(onErrorCallback?: ErrorCallback): Middleware /** * A middleware to launch an editor to open a file at a specific line and column. @@ -21,7 +23,7 @@ declare function launchEditorMiddleware(onErrorCallback?: ErrorCallback): Middle * parsed using `shell-quote`. * @param onErrorCallback Optional callback for handling errors. */ -declare function launchEditorMiddleware( +function launchEditorMiddleware( specifiedEditor?: string, onErrorCallback?: ErrorCallback, ): Middleware @@ -36,10 +38,48 @@ declare function launchEditorMiddleware( * @param srcRoot Optional source root directory to resolve relative file paths. * @param onErrorCallback Optional callback for handling errors. */ -declare function launchEditorMiddleware( +function launchEditorMiddleware( specifiedEditor?: string, srcRoot?: string, onErrorCallback?: ErrorCallback, ): Middleware +function launchEditorMiddleware( + specifiedEditor?: string | ErrorCallback, + srcRoot?: string | ErrorCallback, + onErrorCallback?: ErrorCallback, +): Middleware { + if (typeof specifiedEditor === 'function') { + onErrorCallback = specifiedEditor + specifiedEditor = undefined + } + + if (typeof srcRoot === 'function') { + onErrorCallback = srcRoot + srcRoot = undefined + } + + srcRoot = srcRoot || process.cwd() + + return function middleware(req, res) { + const requestUrl = req.url ?? '' + const fullUrl = requestUrl.startsWith('http') ? requestUrl : `http://localhost${requestUrl}` + const url = URL.parse(fullUrl) + if (!url) { + res.statusCode = 500 + res.end(`launch-editor-middleware: invalid URL.`) + return + } + + const file = url.searchParams.get('file') + if (!file) { + res.statusCode = 500 + res.end(`launch-editor-middleware: required query param "file" is missing.`) + } else { + const resolved = file.startsWith('file://') ? file : path.resolve(srcRoot, file) + launch(resolved, specifiedEditor, onErrorCallback) + res.end() + } + } +} export default launchEditorMiddleware diff --git a/packages/launch-editor-middleware/package.json b/packages/launch-editor-middleware/package.json index bf00c2e..6b0b638 100644 --- a/packages/launch-editor-middleware/package.json +++ b/packages/launch-editor-middleware/package.json @@ -18,14 +18,13 @@ "url": "git+https://github.com/vitejs/launch-editor.git" }, "files": [ - "dist", - "index.d.ts" + "dist" ], "type": "module", "main": "dist/index.js", - "types": "index.d.ts", + "types": "dist/index.d.ts", "scripts": { - "build": "tsdown index.js --no-fixed-extension --no-dts", + "build": "tsdown index.ts --no-fixed-extension --dts", "prepack": "pnpm run build", "test": "vitest run" }, diff --git a/packages/launch-editor/construct-windows-launch-command.test.js b/packages/launch-editor/construct-windows-launch-command.test.ts similarity index 99% rename from packages/launch-editor/construct-windows-launch-command.test.js rename to packages/launch-editor/construct-windows-launch-command.test.ts index e850bfd..51e5a0c 100644 --- a/packages/launch-editor/construct-windows-launch-command.test.js +++ b/packages/launch-editor/construct-windows-launch-command.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest' -import constructWindowsLaunchCommand from './construct-windows-launch-command.js' +import constructWindowsLaunchCommand from './construct-windows-launch-command.ts' describe('constructWindowsLaunchCommand', () => { test('joins the editor and arguments', () => { diff --git a/packages/launch-editor/construct-windows-launch-command.js b/packages/launch-editor/construct-windows-launch-command.ts similarity index 94% rename from packages/launch-editor/construct-windows-launch-command.js rename to packages/launch-editor/construct-windows-launch-command.ts index b1b73e3..32b2524 100644 --- a/packages/launch-editor/construct-windows-launch-command.js +++ b/packages/launch-editor/construct-windows-launch-command.ts @@ -22,7 +22,7 @@ // // `"` cannot appear in Windows paths, so it is outside the untrusted path input // this sanitization protects. -function escapeCmdArgs(cmdArgs) { +function escapeCmdArgs(cmdArgs: string) { return cmdArgs.replace(/([&|<>,;=^])/g, '^$1') } @@ -31,7 +31,7 @@ function escapeCmdArgs(cmdArgs) { // However, there's a case that it's concatenated with line number and column number // which is separated by `:`. We need to double quote the whole string in this case. // Also, if the string contains the escape character `^`, it needs to be quoted, too. -function doubleQuoteIfNeeded(str) { +function doubleQuoteIfNeeded(str: string) { if (str.includes('^')) { // If a string includes an escaped character, not only does it need to be quoted, // but the quotes need to be escaped too. @@ -42,7 +42,7 @@ function doubleQuoteIfNeeded(str) { return str } -function constructWindowsLaunchCommand(editor, args) { +function constructWindowsLaunchCommand(editor: string, args: string[]) { // CMD treats line breaks as command separators. They cannot appear in regular Windows // file names, but NTFS alternate data stream names may contain control characters. if (args.some((arg) => /[\r\n]/.test(arg))) { diff --git a/packages/launch-editor/editor-info/linux.js b/packages/launch-editor/editor-info/linux.ts similarity index 100% rename from packages/launch-editor/editor-info/linux.js rename to packages/launch-editor/editor-info/linux.ts diff --git a/packages/launch-editor/editor-info/macos.js b/packages/launch-editor/editor-info/macos.ts similarity index 100% rename from packages/launch-editor/editor-info/macos.js rename to packages/launch-editor/editor-info/macos.ts diff --git a/packages/launch-editor/editor-info/windows.js b/packages/launch-editor/editor-info/windows.ts similarity index 100% rename from packages/launch-editor/editor-info/windows.js rename to packages/launch-editor/editor-info/windows.ts diff --git a/packages/launch-editor/get-args.test.js b/packages/launch-editor/get-args.test.ts similarity index 98% rename from packages/launch-editor/get-args.test.js rename to packages/launch-editor/get-args.test.ts index 8651646..aee89ee 100644 --- a/packages/launch-editor/get-args.test.js +++ b/packages/launch-editor/get-args.test.ts @@ -2,7 +2,7 @@ import os from 'node:os' import path from 'node:path' import { afterEach, describe, expect, test, vi } from 'vitest' -import getArgumentsForFile from './get-args.js' +import getArgumentsForFile from './get-args.ts' const absoluteFileName = path.resolve('file') describe('getArgumentsForFile', () => { @@ -203,7 +203,7 @@ describe('getArgumentsForFile', () => { test(`${editor} protects an option-like file name ${position}`, () => { const args = getArgumentsForFile(editor, fileName, lineNumber, 5) - const fileArgument = args.at(-1) + const fileArgument = args.at(-1) as string expect(path.resolve(fileArgument)).toBe(path.resolve(fileName)) expect( diff --git a/packages/launch-editor/get-args.js b/packages/launch-editor/get-args.ts similarity index 93% rename from packages/launch-editor/get-args.js rename to packages/launch-editor/get-args.ts index d5ff2b0..434bbaf 100644 --- a/packages/launch-editor/get-args.js +++ b/packages/launch-editor/get-args.ts @@ -2,7 +2,12 @@ import os from 'node:os' import path from 'node:path' // normalize a file and optional line/column numbers into command line args for specific editors -export default function getArgumentsForFile(editor, fileName, lineNumber, columnNumber = 1) { +export default function getArgumentsForFile( + editor: string, + fileName: string, + lineNumber?: string | number | null, + columnNumber: string | number = 1, +): (string | number)[] { fileName = path.resolve(fileName) if ( diff --git a/packages/launch-editor/guess.test.js b/packages/launch-editor/guess.test.ts similarity index 99% rename from packages/launch-editor/guess.test.js rename to packages/launch-editor/guess.test.ts index 38f7529..610fa3c 100644 --- a/packages/launch-editor/guess.test.js +++ b/packages/launch-editor/guess.test.ts @@ -4,7 +4,7 @@ import { getEditorFromMacProcesses, getEditorFromWindowsProcesses, getEditorFromLinuxProcesses, -} from './guess.js' +} from './guess.ts' describe('getEditorFromMacProcesses', () => { test('maps an exact process path to its CLI command', () => { diff --git a/packages/launch-editor/guess.js b/packages/launch-editor/guess.ts similarity index 87% rename from packages/launch-editor/guess.js rename to packages/launch-editor/guess.ts index 4576af5..94ba204 100644 --- a/packages/launch-editor/guess.js +++ b/packages/launch-editor/guess.ts @@ -5,11 +5,11 @@ import childProcess from 'node:child_process' // Map from full process name to binary that starts the process // We can't just re-use full process name, because it will spawn a new instance // of the app every time -import COMMON_EDITORS_MACOS from './editor-info/macos.js' -import COMMON_EDITORS_LINUX from './editor-info/linux.js' -import COMMON_EDITORS_WIN from './editor-info/windows.js' +import COMMON_EDITORS_MACOS from './editor-info/macos.ts' +import COMMON_EDITORS_LINUX from './editor-info/linux.ts' +import COMMON_EDITORS_WIN from './editor-info/windows.ts' -function getEditorFromMacProcesses(output) { +function getEditorFromMacProcesses(output: string) { const processList = output.split('\n') for (const [processName, editor] of Object.entries(COMMON_EDITORS_MACOS)) { // Find editor by exact match. @@ -36,7 +36,7 @@ function getEditorFromMacProcesses(output) { return undefined } -function getEditorFromWindowsProcesses(output) { +function getEditorFromWindowsProcesses(output: string) { const runningProcesses = output.split('\r\n') for (const runningProcess of runningProcesses) { const fullProcessPath = runningProcess.trim() @@ -49,7 +49,7 @@ function getEditorFromWindowsProcesses(output) { return undefined } -function getEditorFromLinuxProcesses(output) { +function getEditorFromLinuxProcesses(output: string) { for (const [processName, editor] of Object.entries(COMMON_EDITORS_LINUX)) { if (output.includes(processName)) { return editor @@ -58,9 +58,10 @@ function getEditorFromLinuxProcesses(output) { return undefined } -function guessEditor(specifiedEditor) { +function guessEditor(specifiedEditor?: string): [string | null, ...string[]] { if (specifiedEditor) { - return shellQuote.parse(specifiedEditor) + const [editor, ...args] = shellQuote.parse(specifiedEditor).map(String) + return [editor ?? null, ...args] } if (process.env.LAUNCH_EDITOR) { diff --git a/packages/launch-editor/index.d.ts b/packages/launch-editor/index.d.ts deleted file mode 100644 index b5ccf75..0000000 --- a/packages/launch-editor/index.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -type ErrorCallback = (fileName: string, errorMessage: string | null) => void - -/** - * Launch an editor to open a file at a specific line and column. - * - * @param file File path with optional line and column numbers (e.g. - * "/path/to/file.js:10:2"). - * @param onErrorCallback Optional callback for handling errors. - */ -declare function launchEditor(file: string, onErrorCallback?: ErrorCallback): void - -/** - * Launch an editor to open a file at a specific line and column. - * - * @param file File path with optional line and column numbers (e.g. - * "/path/to/file.js:10:2"). - * @param specifiedEditor Optional editor command or path to use. Will be - * parsed using `shell-quote`. - * @param onErrorCallback Optional callback for handling errors. - */ -declare function launchEditor( - file: string, - specifiedEditor?: string, - onErrorCallback?: ErrorCallback, -): void - -export default launchEditor diff --git a/packages/launch-editor/index.test.js b/packages/launch-editor/index.test.ts similarity index 90% rename from packages/launch-editor/index.test.js rename to packages/launch-editor/index.test.ts index 65dde9c..46f781e 100644 --- a/packages/launch-editor/index.test.js +++ b/packages/launch-editor/index.test.ts @@ -7,7 +7,7 @@ const UNC_ERROR = 'UNC paths are not supported on Windows to avoid security issu describe('launchEditor UNC path guard', () => { if (process.platform === 'win32') { test('rejects UNC paths on Windows via the error callback', () => { - const onError = vi.fn() + const onError = vi.fn<(fileName: string, errorMessage: string | null) => void>() launchEditor('\\\\server\\share\\file.js', 'vim', onError) @@ -18,7 +18,7 @@ describe('launchEditor UNC path guard', () => { }) test('strips the position suffix before reporting the rejected UNC path', () => { - const onError = vi.fn() + const onError = vi.fn<(fileName: string, errorMessage: string | null) => void>() launchEditor('\\\\server\\share\\file.js:10:5', 'vim', onError) diff --git a/packages/launch-editor/index.js b/packages/launch-editor/index.ts similarity index 56% rename from packages/launch-editor/index.js rename to packages/launch-editor/index.ts index a65149b..52a62c4 100644 --- a/packages/launch-editor/index.js +++ b/packages/launch-editor/index.ts @@ -11,14 +11,16 @@ import fs from 'node:fs' import path from 'node:path' import colors from 'picocolors' -import childProcess from 'node:child_process' +import childProcess, { type ChildProcess } from 'node:child_process' -import guessEditor from './guess.js' -import getArgumentsForFile from './get-args.js' -import constructWindowsLaunchCommand from './construct-windows-launch-command.js' -import parseFile from './parse-file.js' +import guessEditor from './guess.ts' +import getArgumentsForFile from './get-args.ts' +import constructWindowsLaunchCommand from './construct-windows-launch-command.ts' +import parseFile from './parse-file.ts' -function wrapErrorCallback(cb) { +type ErrorCallback = (fileName: string, errorMessage: string | null) => void + +function wrapErrorCallback(cb?: ErrorCallback): ErrorCallback { return (fileName, errorMessage) => { console.log() console.log(colors.red('Could not open ' + path.basename(fileName) + ' in the editor.')) @@ -33,7 +35,7 @@ function wrapErrorCallback(cb) { } } -function isTerminalEditor(editor) { +function isTerminalEditor(editor: string) { switch (editor) { case 'vim': case 'emacs': @@ -43,9 +45,32 @@ function isTerminalEditor(editor) { return false } -let currentChildProcess = null +let currentChildProcess: ChildProcess | null = null + +/** + * Launch an editor to open a file at a specific line and column. + * + * @param file File path with optional line and column numbers (e.g. + * "/path/to/file.js:10:2"). + * @param onErrorCallback Optional callback for handling errors. + */ +function launchEditor(file: string, onErrorCallback?: ErrorCallback): void -function launchEditor(file, specifiedEditor, onErrorCallback) { +/** + * Launch an editor to open a file at a specific line and column. + * + * @param file File path with optional line and column numbers (e.g. + * "/path/to/file.js:10:2"). + * @param specifiedEditor Optional editor command or path to use. Will be + * parsed using `shell-quote`. + * @param onErrorCallback Optional callback for handling errors. + */ +function launchEditor(file: string, specifiedEditor?: string, onErrorCallback?: ErrorCallback): void +function launchEditor( + file: string, + specifiedEditor?: string | ErrorCallback, + onErrorCallback?: ErrorCallback, +): void { const { fileName, lineNumber, columnNumber } = parseFile(file) if (typeof specifiedEditor === 'function') { @@ -53,10 +78,10 @@ function launchEditor(file, specifiedEditor, onErrorCallback) { specifiedEditor = undefined } - onErrorCallback = wrapErrorCallback(onErrorCallback) + const onError = wrapErrorCallback(onErrorCallback) if (process.platform === 'win32' && fileName.startsWith('\\\\')) { - return onErrorCallback( + return onError( fileName, 'UNC paths are not supported on Windows to avoid security issues. ' + 'See https://github.com/vitejs/launch-editor/tree/main/packages/launch-editor#unc-paths-on-windows for details.', @@ -69,19 +94,24 @@ function launchEditor(file, specifiedEditor, onErrorCallback) { const [editor, ...args] = guessEditor(specifiedEditor) if (!editor) { - onErrorCallback(fileName, null) + onError(fileName, null) return } - const extraArgs = getArgumentsForFile(editor, fileName, lineNumber, columnNumber) + const extraArgs = getArgumentsForFile( + editor, + fileName, + lineNumber, + columnNumber ?? undefined, + ).map(String) args.push(...extraArgs) - let launchCommand + let launchCommand: string | undefined if (process.platform === 'win32') { try { launchCommand = constructWindowsLaunchCommand(editor, args) } catch (error) { - onErrorCallback(fileName, error.message) + onError(fileName, (error as Error).message) return } } @@ -93,11 +123,8 @@ function launchEditor(file, specifiedEditor, onErrorCallback) { currentChildProcess.kill('SIGKILL') } - if (process.platform === 'win32') { - currentChildProcess = childProcess.exec(launchCommand, { - stdio: 'inherit', - shell: true, - }) + if (launchCommand !== undefined) { + currentChildProcess = childProcess.exec(launchCommand) } else { currentChildProcess = childProcess.spawn(editor, args, { stdio: 'inherit' }) } @@ -105,16 +132,16 @@ function launchEditor(file, specifiedEditor, onErrorCallback) { currentChildProcess = null if (errorCode) { - onErrorCallback(fileName, '(code ' + errorCode + ')') + onError(fileName, '(code ' + errorCode + ')') } }) - currentChildProcess.on('error', function (error) { + currentChildProcess.on('error', function (error: NodeJS.ErrnoException) { let { code, message } = error if ('ENOENT' === code) { message = `${message} ('${editor}' command does not exist in 'PATH')` } - onErrorCallback(fileName, message) + onError(fileName, message) }) } diff --git a/packages/launch-editor/package.json b/packages/launch-editor/package.json index 9f2d52e..766b309 100644 --- a/packages/launch-editor/package.json +++ b/packages/launch-editor/package.json @@ -17,14 +17,13 @@ "url": "git+https://github.com/vitejs/launch-editor.git" }, "files": [ - "dist", - "index.d.ts" + "dist" ], "type": "module", "main": "dist/index.js", - "types": "index.d.ts", + "types": "dist/index.d.ts", "scripts": { - "build": "tsdown index.js --no-fixed-extension --no-dts", + "build": "tsdown index.ts --no-fixed-extension --dts", "prepack": "pnpm run build", "test": "vitest run" }, @@ -32,6 +31,9 @@ "picocolors": "^1.1.1", "shell-quote": "^1.10.0" }, + "devDependencies": { + "@types/shell-quote": "^1.7.5" + }, "engines": { "node": "^20.19.0 || >=22.12.0" } diff --git a/packages/launch-editor/parse-file.test.js b/packages/launch-editor/parse-file.test.ts similarity index 95% rename from packages/launch-editor/parse-file.test.js rename to packages/launch-editor/parse-file.test.ts index 9c2a5ff..133a377 100644 --- a/packages/launch-editor/parse-file.test.js +++ b/packages/launch-editor/parse-file.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'vitest' import path from 'node:path' -import parseFile from './parse-file.js' +import parseFile from './parse-file.ts' describe('launchEditor path resolution', () => { test('does not resolve an empty file name to the working directory', () => { diff --git a/packages/launch-editor/parse-file.js b/packages/launch-editor/parse-file.ts similarity index 91% rename from packages/launch-editor/parse-file.js rename to packages/launch-editor/parse-file.ts index 7131d18..ad42a12 100644 --- a/packages/launch-editor/parse-file.js +++ b/packages/launch-editor/parse-file.ts @@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url' const positionRE = /:(\d+)(:(\d+))?$/ -export default function parseFile(file) { +export default function parseFile(file: string) { // support `file://` protocol if (file.startsWith('file://')) { file = fileURLToPath(file) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 37afc94..afb2560 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: devDependencies: + '@types/node': + specifier: ^24.19.2 + version: 24.19.2 bumpp: specifier: ^11.1.0 version: 11.1.0 @@ -22,10 +25,13 @@ importers: version: 1.80.0 tsdown: specifier: ^0.23.7 - version: 0.23.7 + version: 0.23.7(typescript@6.0.3) + typescript: + specifier: ^6.0.3 + version: 6.0.3 vitest: specifier: ^4.1.12 - version: 4.1.12(vite@8.3.8(jiti@2.6.1)(yaml@2.9.0)) + version: 4.1.12(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0)) yorkie: specifier: ^2.0.0 version: 2.0.0 @@ -38,6 +44,10 @@ importers: shell-quote: specifier: ^1.10.0 version: 1.11.0 + devDependencies: + '@types/shell-quote': + specifier: ^1.7.5 + version: 1.7.5 packages/launch-editor-middleware: dependencies: @@ -539,6 +549,12 @@ packages: '@types/estree@1.0.10': resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + '@types/node@24.19.2': + resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==} + + '@types/shell-quote@1.7.5': + resolution: {integrity: sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==} + '@vitest/expect@4.1.12': resolution: {integrity: sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==} @@ -1025,12 +1041,20 @@ packages: tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + unconfig-core@7.5.0: resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} unconfig@7.5.0: resolution: {integrity: sha512-oi8Qy2JV4D3UQ0PsopR28CzdQ3S/5A1zwsUwp/rosSbfhJ5z7b90bIyTwi/F7hCLD4SGcZVjDzd4XoUQcEanvA==} + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + verkit@0.5.0: resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} engines: {node: '>=18.12.0'} @@ -1420,6 +1444,12 @@ snapshots: '@types/estree@1.0.10': {} + '@types/node@24.19.2': + dependencies: + undici-types: 7.24.6 + + '@types/shell-quote@1.7.5': {} + '@vitest/expect@4.1.12': dependencies: '@standard-schema/spec': 1.1.0 @@ -1429,13 +1459,13 @@ snapshots: chai: 6.3.0 tinyrainbow: 3.2.0 - '@vitest/mocker@4.1.12(vite@8.3.8(jiti@2.6.1)(yaml@2.9.0))': + '@vitest/mocker@4.1.12(vite@8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0))': dependencies: '@vitest/spy': 4.1.12 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.3.8(jiti@2.6.1)(yaml@2.9.0) + vite: 8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0) '@vitest/pretty-format@4.1.12': dependencies: @@ -1716,13 +1746,15 @@ snapshots: resolve-pkg-maps@1.0.0: {} - rolldown-plugin-dts@0.30.2(rolldown@1.3.2): + rolldown-plugin-dts@0.30.2(rolldown@1.3.2)(typescript@6.0.3): dependencies: dts-resolver: 3.0.0 get-tsconfig: 5.0.0-beta.6 obug: 3.0.0 rolldown: 1.3.2 yuku: 0.28.0 + optionalDependencies: + typescript: 6.0.3 transitivePeerDependencies: - '@yuku-toolchain/wasm' - oxc-resolver @@ -1819,7 +1851,7 @@ snapshots: tinyrainbow@3.2.0: {} - tsdown@0.23.7: + tsdown@0.23.7(typescript@6.0.3): dependencies: cac: 7.1.0 defu: 6.1.7 @@ -1829,12 +1861,14 @@ snapshots: obug: 3.0.0 picomatch: 4.0.7 rolldown: 1.3.2 - rolldown-plugin-dts: 0.30.2(rolldown@1.3.2) + rolldown-plugin-dts: 0.30.2(rolldown@1.3.2)(typescript@6.0.3) tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyps: 0.5.2 unconfig-core: 7.5.0 verkit: 0.5.0 + optionalDependencies: + typescript: 6.0.3 transitivePeerDependencies: - '@volar/typescript' - '@vue/language-core' @@ -1846,6 +1880,8 @@ snapshots: tslib@2.9.1: optional: true + typescript@6.0.3: {} + unconfig-core@7.5.0: dependencies: '@quansync/fs': 1.0.0 @@ -1859,9 +1895,11 @@ snapshots: quansync: 1.0.0 unconfig-core: 7.5.0 + undici-types@7.24.6: {} + verkit@0.5.0: {} - vite@8.3.8(jiti@2.6.1)(yaml@2.9.0): + vite@8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -1869,14 +1907,15 @@ snapshots: rolldown: 1.2.19 tinyglobby: 0.2.17 optionalDependencies: + '@types/node': 24.19.2 fsevents: 2.3.3 jiti: 2.6.1 yaml: 2.9.0 - vitest@4.1.12(vite@8.3.8(jiti@2.6.1)(yaml@2.9.0)): + vitest@4.1.12(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.12 - '@vitest/mocker': 4.1.12(vite@8.3.8(jiti@2.6.1)(yaml@2.9.0)) + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0)) '@vitest/pretty-format': 4.1.12 '@vitest/runner': 4.1.12 '@vitest/snapshot': 4.1.12 @@ -1893,8 +1932,10 @@ snapshots: tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyrainbow: 3.2.0 - vite: 8.3.8(jiti@2.6.1)(yaml@2.9.0) + vite: 8.3.8(@types/node@24.19.2)(jiti@2.6.1)(yaml@2.9.0) why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.19.2 transitivePeerDependencies: - msw diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..98d0c9f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["packages/**/*.ts", "bump.config.ts"], + "exclude": ["**/dist", "node_modules"] +}