Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create amaro loader #47

Merged
merged 3 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,19 @@ Stack traces are preserved, by replacing removed types with white spaces.

```javascript
const amaro = require('amaro');
const { code } = amaro.transformSync("const foo: string = 'bar';");
const { code } = amaro.transformSync("const foo: string = 'bar';", { mode: "strip-only" });
console.log(code); // "const foo = 'bar';"
```

### Loader

It is possible to use Amaro as an external loader to execute TypeScript files.
This allows the installed Amaro to override the Amaro version used by Node.js.

```bash
node --experimental-strip-types --import="amaro/register" script.ts
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
```

### How to update SWC

To update the SWC version, run:
Expand Down
18 changes: 18 additions & 0 deletions esbuild.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { copy } = require("esbuild-plugin-copy");
const esbuild = require("esbuild");

esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
platform: "node",
target: "node20",
outdir: "dist",
plugins: [
copy({
assets: {
from: ["./src/register/register.mjs"],
to: ["."],
},
}),
],
});
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,22 @@
"ci:fix": "biome check --write",
"prepack": "npm run build",
"postpack": "npm run clean",
"build": "rspack build",
"build": "node esbuild.config.js",
"typecheck": "tsc --noEmit",
"test": "node --test --experimental-test-snapshots \"**/*.test.js\"",
"test:regenerate": "node --test --experimental-test-snapshots --test-update-snapshots \"**/*.test.js\""
},
"devDependencies": {
"@biomejs/biome": "1.8.3",
"@rspack/cli": "^0.7.5",
"@rspack/core": "^0.7.5",
"@types/node": "^20.14.11",
"esbuild": "^0.23.0",
"esbuild-plugin-copy": "^2.1.1",
"rimraf": "^6.0.1",
"typescript": "^5.5.3"
},
"exports": {
".": "./dist/index.js",
"./register": "./dist/register.mjs"
},
"files": ["dist", "LICENSE.md"]
}
31 changes: 0 additions & 31 deletions rspack.config.js

This file was deleted.

20 changes: 2 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,2 @@
import type { Options, TransformOutput } from "../lib/wasm";
import swc from "../lib/wasm.js";

const DEFAULT_OPTIONS: Options = {
mode: "strip-only",
};

export function transformSync(
source: string,
options: Options,
): TransformOutput {
// Ensure that the source code is a string
const input = `${source ?? ""}`;
return swc.transformSync(input, {
...DEFAULT_OPTIONS,
...options,
});
}
export { transformSync } from "./transform.ts";
export { load } from "./loader.ts";
32 changes: 32 additions & 0 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import assert from "node:assert";
import type { LoadFnOutput, LoadHookContext } from "node:module";
import { transformSync } from "./index.ts";

type NextLoad = (
url: string,
context?: LoadHookContext,
) => LoadFnOutput | Promise<LoadFnOutput>;

export async function load(
url: string,
context: LoadHookContext,
nextLoad: NextLoad,
) {
const { format } = context;
if (format.endsWith("-typescript")) {
// Use format 'module' so it returns the source as-is, without stripping the types.
// Format 'commonjs' would not return the source for historical reasons.
const { source } = await nextLoad(url, {
...context,
format: "module",
});
if (source == null)
throw new Error("Source code cannot be null or undefined");
const { code } = transformSync(source.toString(), { mode: "strip-only" });
marco-ippolito marked this conversation as resolved.
Show resolved Hide resolved
return {
format: format.replace("-typescript", ""),
source: code,
};
}
return nextLoad(url, context);
}
3 changes: 3 additions & 0 deletions src/register/register.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { register } from "node:module";

register("./index.js", import.meta.url);
18 changes: 18 additions & 0 deletions src/transform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Options, TransformOutput } from "../lib/wasm";
import swc from "../lib/wasm.js";

const DEFAULT_OPTIONS: Options = {
mode: "strip-only",
};

export function transformSync(
source: string,
marco-ippolito marked this conversation as resolved.
Show resolved Hide resolved
options?: Options,
): TransformOutput {
// Ensure that the source code is a string
const input = `${source ?? ""}`;
return swc.transformSync(input, {
...DEFAULT_OPTIONS,
...options,
});
}
4 changes: 4 additions & 0 deletions test/fixtures/enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
enum Foo {
A = "Hello, TypeScript!",
}
console.log(Foo.A);
1 change: 1 addition & 0 deletions test/fixtures/hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("Hello, TypeScript!");
29 changes: 29 additions & 0 deletions test/loader.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { spawnPromisified, fixturesPath } = require("./util/util.js");
const { test } = require("node:test");
const { match, strictEqual } = require("node:assert");

test("should work as a loader", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
marco-ippolito marked this conversation as resolved.
Show resolved Hide resolved
"--no-warnings",
"--import=./dist/register.mjs",
fixturesPath("hello.ts"),
]);

strictEqual(result.stderr, "");
match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.code, 0);
});

test("should work with enums", async () => {
const result = await spawnPromisified(process.execPath, [
"--experimental-strip-types",
"--no-warnings",
"--import=./dist/register.mjs",
fixturesPath("enum.ts"),
]);

strictEqual(result.stdout, "");
match(result.stderr, /TypeScript enum is not supported in strip-only mode/);
strictEqual(result.code, 1);
});
44 changes: 44 additions & 0 deletions test/util/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const { spawn } = require("node:child_process");
const path = require("node:path");

function spawnPromisified(...args) {
let stderr = "";
let stdout = "";

const child = spawn(...args);
child.stderr.setEncoding("utf8");
child.stderr.on("data", (data) => {
stderr += data;
});
child.stdout.setEncoding("utf8");
child.stdout.on("data", (data) => {
stdout += data;
});

return new Promise((resolve, reject) => {
child.on("close", (code, signal) => {
resolve({
code,
signal,
stderr,
stdout,
});
});
child.on("error", (code, signal) => {
reject({
code,
signal,
stderr,
stdout,
});
});
});
}

const fixturesDir = path.join(__dirname, "..", "fixtures");

function fixturesPath(...args) {
return path.join(fixturesDir, ...args);
}

module.exports = { spawnPromisified, fixturesPath };
Loading