Skip to content

Commit

Permalink
refactor: migrate @emnapi/core to typescript (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
toyobayashi authored Jan 2, 2024
1 parent 0660480 commit 9037460
Show file tree
Hide file tree
Showing 13 changed files with 468 additions and 98 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ node_modules
/test/CMakeFiles
/packages/runtime/lib
/packages/emnapi/lib
/packages/core/src/module.js
/packages/core/src/emnapi
/packages/**/test/**/input
/packages/**/test/**/actual
/packages/**/test/**/expected
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"eslint-plugin-n": "^16.6.0",
"eslint-plugin-promise": "^6.1.1",
"fs-extra": "^11.2.0",
"glob": "^10.3.10",
"rollup": "^4.9.1",
"typescript": "~5.3.3"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/core/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/lib
node_modules
/dist
/src/module.js
/src/emnapi/**/*.js
115 changes: 115 additions & 0 deletions packages/core/api-extractor.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",

// "extends": "./shared/api-extractor-base.json"
// "extends": "my-package/include/api-extractor-base.json"

"projectFolder": ".",

"mainEntryPointFilePath": "<projectFolder>/lib/typings/index.d.ts",

"bundledPackages": [],

"compiler": {
"tsconfigFilePath": "<projectFolder>/tsconfig.json"

// "overrideTsconfig": {
// . . .
// }

// "skipLibCheck": true,
},

"apiReport": {
"enabled": false

// "reportFileName": "<unscopedPackageName>.api.md",

// "reportFolder": "<projectFolder>/etc/",

// "reportTempFolder": "<projectFolder>/api/temp/"
},

"docModel": {
"enabled": false

// "apiJsonFilePath": "<projectFolder>/temp/<unscopedPackageName>.api.json"
},

"dtsRollup": {
"enabled": true,

"untrimmedFilePath": "",

// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",

"publicTrimmedFilePath": "<projectFolder>/dist/emnapi-core.d.ts"

// "omitTrimmingComments": true
},

"tsdocMetadata": {
"enabled": false,

"tsdocMetadataFilePath": "<projectFolder>/dist/tsdoc-metadata.json"
},

// "newlineKind": "crlf",

"messages": {
/**
* Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing
* the input .d.ts files.
*
* TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"compilerMessageReporting": {
"default": {
"logLevel": "warning"

// "addToApiReportFile": false
}

// "TS2551": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},

"extractorMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
},
"ae-missing-release-tag": {
"logLevel": "none",
"addToApiReportFile": false
}

// "ae-extra-release-tag": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},

"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
}

// "tsdoc-link-tag-unescaped-text": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
}
}
}
50 changes: 45 additions & 5 deletions packages/core/script/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,36 @@ const rollupTypescript = require('@rollup/plugin-typescript').default
const rollupNodeResolve = require('@rollup/plugin-node-resolve').default
const rollupReplace = require('@rollup/plugin-replace').default
const rollupTerser = require('@rollup/plugin-terser').default
const rollupAlias = require('@rollup/plugin-alias').default
const { compile } = require('@tybys/tsapi')
const { globSync } = require('glob')
const dist = path.join(__dirname, '../dist')

function build () {
compile(path.join(__dirname, '../tsconfig.json'), {
optionsToExtend: {
target: require('typescript').ScriptTarget.ES2019,
emitDeclarationOnly: true,
declaration: true,
declarationDir: path.join(__dirname, '../lib/typings')
}
})

globSync('**/*.d.ts', { cwd: path.join(__dirname, '../src/emnapi') }).forEach(file => {
const from = path.join(path.join(__dirname, '../src/emnapi', file))
const to = path.join(path.join(__dirname, '../lib/typings/emnapi', file))
fs.mkdirSync(path.dirname(to), { recursive: true })
fs.copyFileSync(from, to)
})

/**
* @param {ts.ScriptTarget} esversion
* @param {boolean=} minify
* @returns {rollup.RollupOptions}
*/
function createInput (esversion, minify, external) {
return {
input: path.join(__dirname, '../src/index.js'),
input: path.join(__dirname, '../src/index.ts'),
external,
plugins: [
rollupTypescript({
Expand All @@ -38,6 +57,11 @@ function build () {
]
}
}),
rollupAlias({
entries: [
{ find: '@', replacement: path.join(__dirname, '../src') }
]
}),
rollupNodeResolve({
mainFields: ['module', 'main']
}),
Expand Down Expand Up @@ -136,16 +160,32 @@ function build () {
]).map(conf => {
return rollup.rollup(conf.input).then(bundle => bundle.write(conf.output))
})).then(() => {
const dts = path.join(__dirname, '../index.d.ts')
const dest = path.join(__dirname, '../dist/emnapi-core.d.ts')
const {
Extractor,
ExtractorConfig
} = require('@microsoft/api-extractor')
const apiExtractorJsonPath = path.join(__dirname, '../api-extractor.json')
const extractorConfig = ExtractorConfig.loadFileAndPrepare(apiExtractorJsonPath)
const extractorResult = Extractor.invoke(extractorConfig, {
localBuild: true,
showVerboseMessages: true
})
if (extractorResult.succeeded) {
console.log('API Extractor completed successfully')
} else {
const errmsg = `API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings`
return Promise.reject(new Error(errmsg))
}

const dts = extractorConfig.publicTrimmedFilePath

const mDts = path.join(__dirname, '../dist/emnapi-core.d.mts')
const cjsMinDts = path.join(__dirname, '../dist/emnapi-core.cjs.min.d.ts')
const mjsMinDts = path.join(__dirname, '../dist/emnapi-core.min.d.mts')
fs.copyFileSync(dts, dest)
fs.copyFileSync(dts, mDts)
fs.copyFileSync(dts, cjsMinDts)
fs.copyFileSync(dts, mjsMinDts)
fs.appendFileSync(dest, '\nexport as namespace emnapiCore;\n', 'utf8')
fs.appendFileSync(dts, '\nexport as namespace emnapiCore;\n', 'utf8')
})
}

Expand Down
90 changes: 90 additions & 0 deletions packages/core/src/emnapi/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { Context } from '@emnapi/runtime'

/** @public */
export declare interface PointerInfo {
address: number
ownership: 0 | 1
runtimeAllocated: 0 | 1
}

/** @public */
export declare interface InitOptions {
instance: WebAssembly.Instance
module: WebAssembly.Module
memory?: WebAssembly.Memory
table?: WebAssembly.Table
}

/** @public */
export declare interface NapiModule {
imports: {
env: any
napi: any
emnapi: any
}
exports: any
loaded: boolean
filename: string
childThread: boolean
emnapi: {
syncMemory<T extends ArrayBuffer | ArrayBufferView> (
js_to_wasm: boolean,
arrayBufferOrView: T,
offset?: number,
len?: number
): T
getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo
}

init (options: InitOptions): any
spawnThread (startArg: number, errorOrTid?: number): number
startThread (tid: number, startArg: number): void
initWorker (arg: number): void
executeAsyncWork (work: number): void
postMessage?: (msg: any) => any
}

/** @public */
export declare interface NodeBinding {
node: {
emitAsyncInit: Function
emitAsyncDestroy: Function
makeCallback: Function
}
napi: {
asyncInit: Function
asyncDestroy: Function
makeCallback: Function
}
}

/** @public */
export declare interface CreateWorkerInfo {
type: 'thread' | 'async-work'
}

/** @public */
export declare type BaseCreateOptions = {
filename?: string
nodeBinding?: NodeBinding
reuseWorker?: boolean
asyncWorkPoolSize?: number
onCreateWorker?: (info: CreateWorkerInfo) => any
print?: (str: string) => void
printErr?: (str: string) => void
postMessage?: (msg: any) => any
}

/** @public */
export declare type CreateOptions = BaseCreateOptions & ({
context: Context
childThread?: boolean
} | {
context?: Context
childThread: true
})

/** @public */
export declare function createNapiModule (
options: CreateOptions
): NapiModule
11 changes: 0 additions & 11 deletions packages/core/src/index.js

This file was deleted.

38 changes: 38 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export { createNapiModule } from './emnapi/index'
export {
loadNapiModule,
loadNapiModuleSync,
instantiateNapiModule,
instantiateNapiModuleSync
} from './load'

export { MessageHandler } from './worker'

declare const __VERSION__: string
export const version = __VERSION__

export type {
PointerInfo,
InitOptions,
NapiModule,
NodeBinding,
CreateWorkerInfo,
BaseCreateOptions,
CreateOptions
} from './emnapi/index'

export type {
LoadOptions,
InstantiateOptions,
InstantiatedSource,
ReactorWASI
} from './load'

export type {
OnLoadData,
HandleOptions
} from './worker'

export type {
InputType
} from './util'
Loading

0 comments on commit 9037460

Please sign in to comment.