rsnext/packages/next/build/swc/index.js
Maia Teegarden 0d0f34ba18
Pass code as buffer to swc minify (#29009)
This should fix this: https://github.com/vercel/next.js/pull/28883/checks?check_run_id=3560578176#step:4:353



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes
2021-09-11 00:57:01 +00:00

81 lines
2.1 KiB
JavaScript

const { loadBinding } = require('@node-rs/helper')
const path = require('path')
/**
* __dirname means load native addon from current dir
* 'next-swc' is the name of native addon
* the second arguments was decided by `napi.name` field in `package.json`
* the third arguments was decided by `name` field in `package.json`
* `loadBinding` helper will load `next-swc.[PLATFORM].node` from `__dirname` first
* If failed to load addon, it will fallback to load from `next-swc-[PLATFORM]`
*/
const bindings = loadBinding(
path.join(__dirname, '../../../native'),
'next-swc',
'@next/swc'
)
async function transform(src, options) {
const isModule = typeof src !== 'string'
options = options || {}
if (options?.jsc?.parser) {
options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
}
const { plugin, ...newOptions } = options
if (plugin) {
const m =
typeof src === 'string'
? await this.parse(src, options?.jsc?.parser)
: src
return this.transform(plugin(m), newOptions)
}
return bindings.transform(
isModule ? JSON.stringify(src) : src,
isModule,
toBuffer(newOptions)
)
}
function transformSync(src, options) {
const isModule = typeof src !== 'string'
options = options || {}
if (options?.jsc?.parser) {
options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
}
const { plugin, ...newOptions } = options
if (plugin) {
const m =
typeof src === 'string' ? this.parseSync(src, options?.jsc?.parser) : src
return this.transformSync(plugin(m), newOptions)
}
return bindings.transformSync(
isModule ? JSON.stringify(src) : src,
isModule,
toBuffer(newOptions)
)
}
function toBuffer(t) {
return Buffer.from(JSON.stringify(t))
}
export async function minify(src, opts) {
return bindings.minify(toBuffer(src), toBuffer(opts ?? {}))
}
export function minifySync(src, opts) {
return bindings.minifySync(toBuffer(src), toBuffer(opts ?? {}))
}
module.exports.transform = transform
module.exports.transformSync = transformSync
module.exports.minify = minify
module.exports.minifySync = minifySync