Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
toyobayashi committed Dec 1, 2023
1 parent 158676e commit a9909f3
Show file tree
Hide file tree
Showing 29 changed files with 395 additions and 31 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ jobs:
shell: bash
run: npm run build --workspaces --if-present

- name: Test Emscripten ESM library
shell: bash
run: npm run test -w packages/ts-transform-emscripten-esm-library

# - name: Lint
# run: npm run lint

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"test": "npm run test -w packages/test",
"test:version": "node ./packages/test/script/test-build-all-napi-version.js",
"release": "node ./script/release.js",
"bump": "npm version -w packages/emnapi -w packages/runtime -w packages/core -w packages/node",
"bump": "npm version -w packages/emnapi -w packages/runtime -w packages/core -w packages/node -w packages/ts-transform-emscripten-parse-tools",
"lint": "eslint \"packages/**/*.ts\""
},
"author": "toyobayashi",
Expand Down
30 changes: 2 additions & 28 deletions packages/rollup-plugin-emscripten-esm-library/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,13 @@
import { EOL } from 'os'
import ts = require('typescript')
import type { Plugin } from 'rollup'
import { createTransformerFactory } from '@emnapi/ts-transform-emscripten-esm-library'
import { transform } from '@emnapi/ts-transform-emscripten-esm-library'

export interface PluginOptions {
defaultLibraryFuncsToInclude?: string[]
exportedRuntimeMethods?: string[]
modifyOutput?: (output: string) => string
}

function transform (fileName: string, sourceText: string): string {
const compilerOptions = {
allowJs: true,
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
noEmit: true
}
const source = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS)
const host = ts.createCompilerHost(compilerOptions, true)
host.getSourceFile = filePath => filePath === fileName ? source : undefined
const program = ts.createProgram({
rootNames: [fileName],
options: compilerOptions,
host
})

const transformerFactory = createTransformerFactory(program)

const transformResult = ts.transform(source, [transformerFactory])
const printer = ts.createPrinter({
newLine: process.platform === 'win32' ? ts.NewLineKind.CarriageReturnLineFeed : ts.NewLineKind.LineFeed
})
return printer.printNode(ts.EmitHint.SourceFile, transformResult.transformed[0], transformResult.transformed[0])
}

export default function (options?: PluginOptions): Plugin {
const defaultLibraryFuncsToInclude = options?.defaultLibraryFuncsToInclude ?? []
const exportedRuntimeMethods = options?.exportedRuntimeMethods ?? []
Expand All @@ -52,7 +26,7 @@ export default function (options?: PluginOptions): Plugin {
.map(sym => `{{{ ((EXPORTED_RUNTIME_METHODS.indexOf("${sym}") === -1 ? EXPORTED_RUNTIME_METHODS.push("${sym}") : undefined), "") }}}`)
].join(EOL)

return modifyOutput(prefix + EOL + result.replace(/(\r?\n)\s*\/\/\s+(#((if)|(else)|(elif)|(endif)))/g, '$1$2'))
return modifyOutput(prefix + (prefix ? EOL : '') + result.replace(/(\r?\n)\s*\/\/\s+(#((if)|(else)|(elif)|(endif)))/g, '$1$2'))
}
}
}
1 change: 1 addition & 0 deletions packages/ts-transform-emscripten-esm-library/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/lib
/test/actual
1 change: 1 addition & 0 deletions packages/ts-transform-emscripten-esm-library/.npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ node_modules
.npmignore
tsconfig.json
*.map
/test
6 changes: 5 additions & 1 deletion packages/ts-transform-emscripten-esm-library/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"scripts": {
"build": "tsc"
"build": "tsc",
"test": "node --test ./test/index.js"
},
"repository": {
"type": "git",
Expand All @@ -20,5 +21,8 @@
"homepage": "https://github.com/toyobayashi/emnapi/tree/main/packages/ts-transform-emscripten-esm-library#readme",
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"typescript": ">= 5.0.0"
}
}
27 changes: 26 additions & 1 deletion packages/ts-transform-emscripten-esm-library/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,4 +336,29 @@ function createTransformerFactory (program: Program): TransformerFactory<SourceF
}
}

export { createTransformerFactory }
function transform (fileName: string, sourceText: string): string {
const compilerOptions = {
allowJs: true,
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
noEmit: true
}
const source = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS)
const host = ts.createCompilerHost(compilerOptions, true)
host.getSourceFile = filePath => filePath === fileName ? source : undefined
const program = ts.createProgram({
rootNames: [fileName],
options: compilerOptions,
host
})

const transformerFactory = createTransformerFactory(program)

const transformResult = ts.transform(source, [transformerFactory])
const printer = ts.createPrinter({
newLine: process.platform === 'win32' ? ts.NewLineKind.CarriageReturnLineFeed : ts.NewLineKind.LineFeed
})
return printer.printNode(ts.EmitHint.SourceFile, transformResult.transformed[0], transformResult.transformed[0])
}

export { createTransformerFactory, transform }
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const _exportedVar = 10;
function f() {
console.log(_exportedVar);
}
function _exportedFunc() {
f();
console.log(_exportedVar);
}
mergeInto(LibraryManager.library, {
exportedVar: "10",
$f: f,
$f__deps: ["exportedVar"],
exportedFunc: _exportedFunc,
exportedFunc__deps: ["$f", "exportedVar"]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const fortyTwo = 42;
function _x() {
console.log(fortyTwo);
}
const _y = () => fortyTwo;
mergeInto(LibraryManager.library, {
$fortyTwo: "42",
x: _x,
x__deps: ["$fortyTwo"],
y: _y,
y__deps: ["$fortyTwo"]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/** @__deps $external */
function _x() { }
/**
* @__deps emscripten_resize_heap
* @__deps $runtimeKeepalivePush
* @__deps $runtimeKeepalivePop
* @__sig v
* @__postset
* ```
* console.log(42);
* console.log(_y);
* ```
*
* @returns {void}
*/
function _y() {
runtimeKeepalivePush();
runtimeKeepalivePop();
_emscripten_resize_heap();
return _x();
}
mergeInto(LibraryManager.library, {
x: _x,
x__deps: ["$external"],
y: _y,
y__deps: ["x", "emscripten_resize_heap", "$runtimeKeepalivePush", "$runtimeKeepalivePop"],
y__sig: "v",
y__postset: "console.log(42);\nconsole.log(_y);"
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
function _x() {
return 42;
}
mergeInto(LibraryManager.library, {
x: _x
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const _x = getX();
function getX() {
return 42;
}
mergeInto(LibraryManager.library, {
$getX: getX,
x: "getX()",
x__deps: ["$getX"]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const fortyTwo = 42;
const arr = new Uint8Array(fortyTwo);
function _x(param) {
const ret = arr;
return param + ret;
}
mergeInto(LibraryManager.library, {
$fortyTwo: "42",
$arr: "new Uint8Array(fortyTwo)",
$arr__deps: ["$fortyTwo"],
x: _x,
x__deps: ["$arr"]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const fortyTwo = 42;
const bar = fortyTwo;
function x() {
return fortyTwo;
}
function foo() {
return fortyTwo;
}
function _z() {
return foo();
}
mergeInto(LibraryManager.library, {
$fortyTwo: "42",
$x: x,
$x__deps: ["$fortyTwo"],
$foo: foo,
$foo__deps: ["$fortyTwo"],
z: _z,
z__deps: ["$foo"],
$bar: "fortyTwo",
$bar__deps: ["$fortyTwo"]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const fortyTwo = 42;
/**
* @__sig ii
* @param {number} _
*/
const _bar = _ => _;
/**
* @__postset
* ```
* console.log(obj)
* ```
*/
const obj = {
foo: fortyTwo,
bar(param) {
_bar(param);
}
};
const arr = [fortyTwo];
/**
* @__sig i
*/
const _fe = function () {
return obj.foo === arr[0];
};
/**
* @__sig ii
* @param {number} param
*/
const _af = (param) => {
obj.bar(param);
};
mergeInto(LibraryManager.library, {
bar: _bar,
bar__sig: "ii",
$fortyTwo: "42",
$obj: obj,
$obj__deps: ["$fortyTwo", "bar"],
$obj__postset: "console.log(obj)",
$arr: arr,
$arr__deps: ["$fortyTwo"],
fe: _fe,
fe__deps: ["$obj", "$arr"],
fe__sig: "i",
af: _af,
af__deps: ["$obj"],
af__sig: "ii"
});
51 changes: 51 additions & 0 deletions packages/ts-transform-emscripten-esm-library/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const test = require('node:test')
const { strictEqual } = require('assert')
const { readFileSync, writeFileSync, mkdirSync } = require('fs')
const { join, dirname } = require('path')
const { rollup } = require('rollup')
const { transform } = require('..')

function testTransform (file) {
const exportedFunction = join(__dirname, `input/${file}.js`)
const exportedFunctionExpected = join(__dirname, `expected/${file}.js`)
const actualFunctionExpected = join(__dirname, `actual/${file}.js`)
const transformed = transform(exportedFunction, readFileSync(exportedFunction, 'utf8'))
mkdirSync(dirname(actualFunctionExpected), { recursive: true })
writeFileSync(actualFunctionExpected, transformed, 'utf8')
strictEqual(transformed, readFileSync(exportedFunctionExpected, 'utf8'))
}

test('exported function', () => {
testTransform('exported-function')
})

test('external variable', () => {
testTransform('external-variable')
})

test('exported function referenced by another one', () => {
testTransform('exported-function-ref')
})

test('exported local variable using a local function', () => {
testTransform('exported-var')
})

test('exporting a variable and a function with custom names', () => {
testTransform('alias')
})

test('object literal dependencies', () => {
testTransform('object-literal')
})

test('internal', () => {
testTransform('internal')
})

test('rollup', async () => {
const config = (await import('./rollup/rollup.config.mjs')).default
const build = await rollup(config)
await build.write(config.output)
strictEqual(readFileSync(config.output.file, 'utf8'), readFileSync(join(__dirname, './expected/bundle.js'), 'utf8'))
})
15 changes: 15 additions & 0 deletions packages/ts-transform-emscripten-esm-library/test/input/alias.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const localVar = 10

function f () {
console.log(localVar)
}

function localFunc() {
f()
console.log(localVar)
}

export {
localVar as exportedVar,
localFunc as exportedFunc
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/** @__deps $external */
export function x() {}

/**
* @__deps emscripten_resize_heap
* @__deps $runtimeKeepalivePush
* @__deps $runtimeKeepalivePop
* @__sig v
* @__postset
* ```
* console.log(42);
* console.log(_y);
* ```
*
* @returns {void}
*/
export function y() {
runtimeKeepalivePush()
runtimeKeepalivePop()
_emscripten_resize_heap()
return x()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function x () {
return 42
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const x = getX()

function getX() {
return 42
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const fortyTwo = 42
const arr = new Uint8Array(fortyTwo)

export function x (param) {
const ret = arr
return param + ret
}
Loading

0 comments on commit a9909f3

Please sign in to comment.