@d1g1tal/tsnode 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 D1g1talEntr0py
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # tsnode
2
+
3
+ `tsnode` is a CLI-first TypeScript runner for modern Node.js. It registers synchronous loader hooks and runs local `.ts` entrypoints directly, without requiring loader flags at invocation time.
4
+
5
+ ## Status
6
+
7
+ This package currently supports the `tsnode` CLI as its public interface. The loader hook implementation is not yet a documented import API.
8
+
9
+ ## Requirements
10
+
11
+ - Node.js `>=22.15.0`
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add -D tsnode
17
+ ```
18
+
19
+ You can also install it globally:
20
+
21
+ ```bash
22
+ pnpm add -g tsnode
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ Run a TypeScript entrypoint directly:
28
+
29
+ ```bash
30
+ tsnode ./src/index.ts
31
+ ```
32
+
33
+ Arguments after the entry file are passed through to the loaded program:
34
+
35
+ ```bash
36
+ tsnode ./scripts/build.ts --watch
37
+ ```
38
+
39
+ ## What It Resolves
40
+
41
+ The loader supports these local resolution patterns:
42
+
43
+ - Relative imports such as `./helper.js` resolving to `./helper.ts`
44
+ - Relative paths without an extension resolving to `.ts`
45
+ - Directory imports resolving to `index.ts`
46
+ - `src/` aliases resolving from the nearest project root containing `tsconfig.json` or `package.json`
47
+
48
+ ## Cache Behavior
49
+
50
+ - Transpiled output is cached under `~/.cache/tsnode/<typescript-version>`
51
+ - Cache keys include the source path, file metadata, current Node version, and TypeScript version
52
+ - Cache writes are asynchronous so a cold compile does not block repeated loads in the same process
53
+
54
+ ## Known Limitations
55
+
56
+ - The package is currently CLI-first; importing loader hooks directly is not yet a supported API
57
+ - The transpiler targets modern ESM output for Node.js rather than older runtimes
58
+ - Stage 3 decorators are downleveled during transpilation because current Node.js releases still do not execute that syntax directly
59
+
60
+ ## Development
61
+
62
+ ```bash
63
+ pnpm run build
64
+ pnpm run test
65
+ pnpm run type-check
66
+ pnpm run release:check
67
+ ```
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { registerHooks } from 'node:module';
5
+ import { resolve as resolvePath } from 'node:path';
6
+ import { loaderLifecycle, load, resolve } from './hooks.js';
7
+ // Use top-level await to ensure the loader is registered before importing the target.
8
+ await using _loader = loaderLifecycle;
9
+ // Register the TypeScript loader hooks synchronously before importing the target.
10
+ registerHooks({ load, resolve });
11
+ const entry = process.argv[2];
12
+ if (entry === undefined) {
13
+ process.stderr.write('Usage: tsnode <file.ts> [...args]\n');
14
+ process.exit(1);
15
+ }
16
+ // Shift argv so the target file looks like the main script to the loaded module.
17
+ process.argv.splice(1, 1);
18
+ await import(entry.startsWith('file:') ? entry : pathToFileURL(resolvePath(entry)).href);
@@ -0,0 +1,8 @@
1
+ import type { ResolveHookSync, LoadHookSync } from 'node:module';
2
+ export declare const loaderLifecycle: {
3
+ [Symbol.dispose](): void;
4
+ [Symbol.asyncDispose](): Promise<void>;
5
+ };
6
+ export declare const resolve: ResolveHookSync;
7
+ export declare const load: LoadHookSync;
8
+ export declare function disposeLoader(): Promise<void>;
package/dist/hooks.js ADDED
@@ -0,0 +1,217 @@
1
+ import process from 'node:process';
2
+ import { homedir } from 'node:os';
3
+ import { createHash } from 'node:crypto';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { dirname, resolve as resolvePath } from 'node:path';
6
+ import { mkdirSync, readFileSync, statSync } from 'node:fs';
7
+ import { rename, rm, writeFile } from 'node:fs/promises';
8
+ import { transpileModule, ScriptTarget, ModuleKind, version as typescriptVersion } from 'typescript';
9
+ const cacheDir = resolvePath(homedir(), '.cache', 'tsnode', typescriptVersion);
10
+ mkdirSync(cacheDir, { recursive: true });
11
+ const transpileTarget = ScriptTarget.ES2022;
12
+ const loaderCacheVersion = 'target-es2022';
13
+ const cachedEntries = new Set();
14
+ const cacheVersion = `${process.versions.node}-${typescriptVersion}-${loaderCacheVersion}`;
15
+ const resolveCache = new Map();
16
+ const statCache = new Map();
17
+ const pathHashCache = new Map();
18
+ const projectRootCache = new Map();
19
+ const pendingCacheWrites = new Map();
20
+ let cacheWriteSequence = 0;
21
+ function clearLoaderCaches() {
22
+ cachedEntries.clear();
23
+ resolveCache.clear();
24
+ statCache.clear();
25
+ pathHashCache.clear();
26
+ projectRootCache.clear();
27
+ }
28
+ async function flushPendingCacheWrites() {
29
+ const writes = [...pendingCacheWrites.values()];
30
+ if (writes.length === 0) {
31
+ return;
32
+ }
33
+ await Promise.allSettled(writes);
34
+ }
35
+ export const loaderLifecycle = {
36
+ [Symbol.dispose]() {
37
+ clearLoaderCaches();
38
+ },
39
+ async [Symbol.asyncDispose]() {
40
+ await flushPendingCacheWrites();
41
+ clearLoaderCaches();
42
+ }
43
+ };
44
+ function hashPath(path) {
45
+ const cached = pathHashCache.get(path);
46
+ if (cached !== undefined) {
47
+ return cached;
48
+ }
49
+ const hash = createHash('sha256').update(path).digest('hex').slice(0, 16);
50
+ pathHashCache.set(path, hash);
51
+ return hash;
52
+ }
53
+ function getStat(path) {
54
+ const cached = statCache.get(path);
55
+ if (cached !== undefined) {
56
+ return cached;
57
+ }
58
+ const stat = statSync(path, { throwIfNoEntry: false });
59
+ if (stat === undefined || !stat.isFile()) {
60
+ return undefined;
61
+ }
62
+ const info = { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, ino: stat.ino, size: stat.size };
63
+ statCache.set(path, info);
64
+ return info;
65
+ }
66
+ function fileExists(path) {
67
+ return getStat(path) !== undefined;
68
+ }
69
+ function scheduleCacheWrite(cacheFileName, cachePath, source) {
70
+ if (cachedEntries.has(cacheFileName) || pendingCacheWrites.has(cacheFileName)) {
71
+ return;
72
+ }
73
+ const temporaryCachePath = cachePath + '.' + process.pid + '.' + cacheWriteSequence++ + '.tmp';
74
+ const writePromise = writeFile(temporaryCachePath, source)
75
+ .then(() => rename(temporaryCachePath, cachePath))
76
+ .then(() => {
77
+ cachedEntries.add(cacheFileName);
78
+ })
79
+ .catch(error => {
80
+ rm(temporaryCachePath, { force: true }).catch(() => undefined);
81
+ process.stderr.write('[tsnode] cache write failed: ' + String(error) + '\n');
82
+ })
83
+ .finally(() => {
84
+ pendingCacheWrites.delete(cacheFileName);
85
+ });
86
+ pendingCacheWrites.set(cacheFileName, writePromise);
87
+ }
88
+ function directoryExists(path) {
89
+ const stat = statSync(path, { throwIfNoEntry: false });
90
+ return stat !== undefined && stat.isDirectory();
91
+ }
92
+ function readCachedSource(cacheFileName, cachePath) {
93
+ try {
94
+ const source = readFileSync(cachePath, 'utf8');
95
+ cachedEntries.add(cacheFileName);
96
+ return source;
97
+ }
98
+ catch (error) {
99
+ const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined;
100
+ cachedEntries.delete(cacheFileName);
101
+ if (code !== 'ENOENT') {
102
+ process.stderr.write('[tsnode] cache read failed: ' + String(error) + '\n');
103
+ }
104
+ return undefined;
105
+ }
106
+ }
107
+ function findProjectRoot(startDirectory) {
108
+ const cached = projectRootCache.get(startDirectory);
109
+ if (cached !== undefined) {
110
+ return cached;
111
+ }
112
+ let currentDirectory = startDirectory;
113
+ for (;;) {
114
+ if (fileExists(resolvePath(currentDirectory, 'tsconfig.json')) || fileExists(resolvePath(currentDirectory, 'package.json'))) {
115
+ projectRootCache.set(startDirectory, currentDirectory);
116
+ return currentDirectory;
117
+ }
118
+ const parentDirectory = dirname(currentDirectory);
119
+ if (parentDirectory === currentDirectory) {
120
+ const fallbackDirectory = process.cwd();
121
+ projectRootCache.set(startDirectory, fallbackDirectory);
122
+ return fallbackDirectory;
123
+ }
124
+ currentDirectory = parentDirectory;
125
+ }
126
+ }
127
+ function resolveSrcRoot(parentURL) {
128
+ if (parentURL !== undefined && parentURL.startsWith('file:')) {
129
+ const parentDirectory = dirname(fileURLToPath(parentURL));
130
+ const projectRoot = findProjectRoot(parentDirectory);
131
+ const candidateSrcRoot = resolvePath(projectRoot, 'src');
132
+ if (directoryExists(candidateSrcRoot)) {
133
+ return candidateSrcRoot;
134
+ }
135
+ }
136
+ return resolvePath(process.cwd(), 'src');
137
+ }
138
+ function resolveTsPath(absPath) {
139
+ if (absPath.endsWith('.ts') && fileExists(absPath)) {
140
+ return absPath;
141
+ }
142
+ if (absPath.endsWith('.js')) {
143
+ const tsPath = absPath.slice(0, -3) + '.ts';
144
+ if (fileExists(tsPath)) {
145
+ return tsPath;
146
+ }
147
+ }
148
+ const withTs = absPath + '.ts';
149
+ if (fileExists(withTs)) {
150
+ return withTs;
151
+ }
152
+ const indexTs = absPath + '/index.ts';
153
+ return fileExists(indexTs) ? indexTs : null;
154
+ }
155
+ export const resolve = function (specifier, context, nextResolve) {
156
+ const firstChar = specifier.charCodeAt(0);
157
+ const isRelative = firstChar === 46 /* . */;
158
+ const isSrcAlias = firstChar === 115 /* s */ && specifier.startsWith('src/');
159
+ if (!isRelative && !isSrcAlias) {
160
+ return nextResolve(specifier, context);
161
+ }
162
+ const cacheKey = context.parentURL !== undefined ? specifier + '\0' + context.parentURL : specifier;
163
+ const cached = resolveCache.get(cacheKey);
164
+ if (cached !== undefined) {
165
+ return cached;
166
+ }
167
+ let absPath = null;
168
+ if (isSrcAlias) {
169
+ absPath = resolvePath(resolveSrcRoot(context.parentURL), specifier.slice(4));
170
+ }
171
+ else if (context.parentURL !== undefined && context.parentURL.startsWith('file:')) {
172
+ absPath = resolvePath(dirname(fileURLToPath(context.parentURL)), specifier);
173
+ }
174
+ if (absPath !== null) {
175
+ const tsPath = resolveTsPath(absPath);
176
+ if (tsPath !== null) {
177
+ const result = { url: pathToFileURL(tsPath).href, format: 'module', shortCircuit: true };
178
+ resolveCache.set(cacheKey, result);
179
+ return result;
180
+ }
181
+ }
182
+ return nextResolve(specifier, context);
183
+ };
184
+ export const load = function (url, context, nextLoad) {
185
+ if (!url.startsWith('file:') || !url.endsWith('.ts')) {
186
+ return nextLoad(url, context);
187
+ }
188
+ const path = fileURLToPath(url);
189
+ const info = getStat(path);
190
+ if (info === undefined) {
191
+ return nextLoad(url, context);
192
+ }
193
+ const cacheFileName = hashPath(path) + '-' + info.mtimeMs + '-' + info.ctimeMs + '-' + info.ino + '-' + info.size + '-' + cacheVersion + '.js';
194
+ const cachePath = resolvePath(cacheDir, cacheFileName);
195
+ let source = readCachedSource(cacheFileName, cachePath);
196
+ if (source === undefined) {
197
+ const sourceCode = readFileSync(path, 'utf8');
198
+ const result = transpileModule(sourceCode, {
199
+ compilerOptions: {
200
+ // Downlevel stage 3 decorators because current Node still can't execute
201
+ // the syntax directly even though TypeScript can parse and type-check it.
202
+ target: transpileTarget,
203
+ module: ModuleKind.ESNext,
204
+ jsx: undefined,
205
+ declaration: false,
206
+ sourceMap: false
207
+ },
208
+ reportDiagnostics: true
209
+ });
210
+ source = result.outputText;
211
+ scheduleCacheWrite(cacheFileName, cachePath, source);
212
+ }
213
+ return { format: 'module', source, shortCircuit: true };
214
+ };
215
+ export async function disposeLoader() {
216
+ await loaderLifecycle[Symbol.asyncDispose]();
217
+ }
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@d1g1tal/tsnode",
3
+ "author": "D1g1talEntr0py",
4
+ "version": "0.1.0",
5
+ "license": "MIT",
6
+ "description": "Zero-flag Node.js TypeScript loader — run .ts files directly with `tsnode foo.ts`.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/D1g1talEntr0py/tsnode.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/D1g1talEntr0py/tsnode/issues"
13
+ },
14
+ "maintainers": [
15
+ {
16
+ "name": "D1g1talEntr0py",
17
+ "email": "jason.dimeo@gmail.com"
18
+ }
19
+ ],
20
+ "engines": {
21
+ "node": ">=22.15.0"
22
+ },
23
+ "packageManager": "pnpm@11.8.0",
24
+ "publishConfig": {
25
+ "registry": "https://registry.npmjs.org",
26
+ "access": "public"
27
+ },
28
+ "type": "module",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/hooks.d.ts",
32
+ "default": "./dist/hooks.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "bin": {
41
+ "tsnode": "./dist/cli.js"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json && node -e \"import('node:fs').then(({chmodSync})=>chmodSync('./dist/cli.js',0o755))\"",
45
+ "clean": "rm -rf dist",
46
+ "prepack": "pnpm run clean && pnpm run build",
47
+ "release:check": "pnpm run clean && pnpm run build && pnpm run test && pnpm run type-check && npm pack --dry-run",
48
+ "test": "vitest run",
49
+ "test:watch": "vitest",
50
+ "type-check": "tsc -p tsconfig.json --noEmit"
51
+ },
52
+ "dependencies": {
53
+ "typescript": "^6.0.3"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^25.9.3",
57
+ "vitest": "^4.1.8"
58
+ },
59
+
60
+ "keywords": [
61
+ "typescript",
62
+ "node",
63
+ "loader",
64
+ "esm",
65
+ "cli",
66
+ "transpile"
67
+ ]
68
+ }