Skip to content

Commit

Permalink
feat: toggle package type
Browse files Browse the repository at this point in the history
- evanw/esbuild#2026
- https://github.com/flex-development/toggle-pkg-type

Signed-off-by: Lexus Drumgold <unicornware@flexdevelopment.llc>
  • Loading branch information
unicornware committed Feb 24, 2023
1 parent fc2d542 commit 755b9a7
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 51 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"@flex-development/mlly": "1.0.0-alpha.13",
"@flex-development/pathe": "1.0.3",
"@flex-development/pkg-types": "2.0.0",
"@flex-development/toggle-pkg-type": "1.1.1",
"@flex-development/tsconfig-utils": "1.1.2",
"@flex-development/tutils": "6.0.0-alpha.10",
"colorette": "2.0.19",
Expand Down
9 changes: 5 additions & 4 deletions src/__tests__/make.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@

import { ErrorCode, type NodeError } from '@flex-development/errnode'
import pathe from '@flex-development/pathe'
import consola from 'consola'
import testSubject from '../make'

vi.mock('#src/utils/fs')

describe('unit:make', () => {
let configfile: boolean

beforeAll(() => {
consola.mockTypes(() => vi.fn())
configfile = false
})

it('should return build results', async () => {
// Act
const results = await testSubject({ configfile: false })
const results = await testSubject({ configfile })

// Expect
expect(results).to.be.an('array').that.is.not.empty
Expand All @@ -33,7 +34,7 @@ describe('unit:make', () => {

// Act
try {
await testSubject({ configfile: false, cwd, write: true })
await testSubject({ configfile, cwd })
assert.fail('expected exception not thrown')
} catch (e: unknown) {
error = e as typeof error
Expand Down
24 changes: 12 additions & 12 deletions src/internal/__snapshots__/esbuilder.integration.snap
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
exports[`integration:internal/esbuilder > esbuild > cjs > should create bundle in cjs format 1`] = `
[
{
"entryPoint": "find-uniq.cts",
"entryPoint": "buddy.js",
"errors": [],
"outfile": "dist/find-uniq.cjs",
"path": "\${process.cwd()}/__fixtures__/pkg/find-uniq/dist/find-uniq.cjs",
"outfile": "dist/buddy.cjs",
"path": "\${process.cwd()}/__fixtures__/pkg/buddy/dist/buddy.cjs",
"warnings": [],
},
]
Expand All @@ -15,10 +15,10 @@ exports[`integration:internal/esbuilder > esbuild > cjs > should create bundle i
exports[`integration:internal/esbuilder > esbuild > cjs > should do transpilation in cjs format 1`] = `
[
{
"entryPoint": "find-uniq.cts",
"entryPoint": "buddy.js",
"errors": [],
"outfile": "dist/find-uniq.cjs",
"path": "\${process.cwd()}/__fixtures__/pkg/find-uniq/dist/find-uniq.cjs",
"outfile": "dist/buddy.cjs",
"path": "\${process.cwd()}/__fixtures__/pkg/buddy/dist/buddy.cjs",
"warnings": [],
},
]
Expand Down Expand Up @@ -107,10 +107,10 @@ exports[`integration:internal/esbuilder > esbuild > esm > should do transpilatio
exports[`integration:internal/esbuilder > esbuild > iife > should create bundle in iife format 1`] = `
[
{
"entryPoint": "buddy.js",
"entryPoint": "find-uniq.cts",
"errors": [],
"outfile": "dist/buddy.js",
"path": "\${process.cwd()}/__fixtures__/pkg/buddy/dist/buddy.js",
"outfile": "dist/find-uniq.js",
"path": "\${process.cwd()}/__fixtures__/pkg/find-uniq/dist/find-uniq.js",
"warnings": [],
},
]
Expand All @@ -119,10 +119,10 @@ exports[`integration:internal/esbuilder > esbuild > iife > should create bundle
exports[`integration:internal/esbuilder > esbuild > iife > should do transpilation in iife format 1`] = `
[
{
"entryPoint": "buddy.js",
"entryPoint": "find-uniq.cts",
"errors": [],
"outfile": "dist/buddy.js",
"path": "\${process.cwd()}/__fixtures__/pkg/buddy/dist/buddy.js",
"outfile": "dist/find-uniq.js",
"path": "\${process.cwd()}/__fixtures__/pkg/find-uniq/dist/find-uniq.js",
"warnings": [],
},
]
Expand Down
27 changes: 17 additions & 10 deletions src/internal/__tests__/esbuilder.integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
import type { Entry } from '#src/interfaces'
import loaders from '#src/utils/loaders'
import type { Mock } from '#tests/interfaces'
import getPackageJson from '#tests/utils/get-package-json'
import * as mlly from '@flex-development/mlly'
import * as pathe from '@flex-development/pathe'
import type { PackageJson } from '@flex-development/pkg-types'
import * as esbuild from 'esbuild'
import testSubject from '../esbuilder'

vi.mock('#src/plugins/write/plugin')
vi.mock('#src/utils/fs')
vi.mock('esbuild')

describe('integration:internal/esbuilder', () => {
Expand All @@ -34,20 +36,22 @@ describe('integration:internal/esbuilder', () => {
let absWorkingDir: string
let entry: Partial<Entry>
let format: esbuild.Format
let pkg: PackageJson

beforeAll(() => {
entry = { cwd: '__fixtures__/pkg/find-uniq' }
beforeAll(async () => {
entry = { cwd: '__fixtures__/pkg/buddy' }
absWorkingDir = pathe.resolve(entry.cwd!) + pathe.sep
format = entry.format = 'cjs'
pkg = await getPackageJson(pathe.join(absWorkingDir, 'package.json'))
})

it('should create bundle in cjs format', async () => {
// Arrange
const bundle: boolean = true
const source: string = 'find-uniq.cts'
const source: string = 'buddy.js'

// Act
const [, results] = await testSubject({ ...entry, bundle, source })
const [, results] = await testSubject({ ...entry, bundle, source }, pkg)

// Expect
expect(results).toMatchSnapshot()
Expand All @@ -74,11 +78,14 @@ describe('integration:internal/esbuilder', () => {

it('should do transpilation in cjs format', async () => {
// Arrange
const pattern: string = 'find-uniq.cts'
const pattern: string = 'buddy.js'
const source: string = '.'

// Act
const [, results] = await testSubject({ ...entry, pattern, source })
const [, results] = await testSubject(
{ ...entry, pattern, source },
pkg
)

// Expect
expect(results).toMatchSnapshot()
Expand Down Expand Up @@ -214,15 +221,15 @@ describe('integration:internal/esbuilder', () => {
let format: esbuild.Format

beforeAll(() => {
entry = { cwd: '__fixtures__/pkg/buddy' }
entry = { cwd: '__fixtures__/pkg/find-uniq' }
absWorkingDir = pathe.resolve(entry.cwd!) + pathe.sep
format = entry.format = 'iife'
})

it('should create bundle in iife format', async () => {
// Arrange
const bundle: boolean = true
const source: string = 'buddy.js'
const source: string = 'find-uniq.cts'

// Act
const [, results] = await testSubject({ ...entry, bundle, source })
Expand Down Expand Up @@ -252,7 +259,7 @@ describe('integration:internal/esbuilder', () => {

it('should do transpilation in iife format', async () => {
// Arrange
const pattern: string = 'buddy.js'
const pattern: string = 'find-uniq.cts'
const source: string = '.'

// Act
Expand Down
2 changes: 1 addition & 1 deletion src/internal/__tests__/esbuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import type { Entry } from '#src'
import testSubject from '../esbuilder'

vi.mock('#src/plugins/write/plugin')
vi.mock('#src/utils/fs')

describe('unit:internal/esbuilder', () => {
let entry: Entry
Expand Down
23 changes: 22 additions & 1 deletion src/internal/esbuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import loaders from '#src/utils/loaders'
import { EXT_DTS_REGEX } from '@flex-development/ext-regex'
import * as mlly from '@flex-development/mlly'
import * as pathe from '@flex-development/pathe'
import type { PackageJson } from '@flex-development/pkg-types'
import togglePkgType from '@flex-development/toggle-pkg-type'
import * as esbuild from 'esbuild'
import regexp from 'escape-string-regexp'
import fg from 'fast-glob'
Expand All @@ -25,12 +27,14 @@ import { omit } from 'radash'
* @async
*
* @param {Partial<Entry>} entry - Build entry object
* @param {Partial<FileSystemAdapter>} [fs=fsa] - Custom file system methods
* @param {PackageJson?} [pkg={}] - Relevant `package.json`
* @param {Partial<FileSystemAdapter>?} [fs=fsa] - Custom file system methods
* @return {Promise<[esbuild.Metafile, Result[]]>} Metafile and build results
* @throws {esbuild.BuildFailure}
*/
const esbuilder = async (
entry: Partial<Entry>,
pkg: PackageJson = {},
fs: Partial<FileSystemAdapter> = fsa
): Promise<[esbuild.Metafile, Result[]]> => {
const {
Expand Down Expand Up @@ -66,6 +70,17 @@ const esbuilder = async (
const absWorkingDir: string =
pathe.resolve(cwd).replace(/\/$/, '') + pathe.sep

/**
* Boolean indicating {@linkcode pkg.type} should be disabled before building
* source files.
*
* @see https://github.com/evanw/esbuild/issues/2026
* @see https://github.com/flex-development/toggle-pkg-type
*
* @const {boolean} pkgtype
*/
const pkgtype: boolean = pkg.type === 'module' && format === 'cjs'

/**
* Relative paths to source files.
*
Expand Down Expand Up @@ -126,6 +141,9 @@ const esbuilder = async (
Reflect.deleteProperty(options, 'stdin')
Reflect.deleteProperty(options, 'watch')

// disable package type
pkgtype && togglePkgType(null, absWorkingDir)

// build source files
const { errors, metafile, outputFiles, warnings } = await esbuild.build({
...options,
Expand Down Expand Up @@ -167,6 +185,9 @@ const esbuilder = async (
write: false
})

// reset package type
pkgtype && togglePkgType(null, absWorkingDir)

return [
metafile,
outputFiles
Expand Down
33 changes: 14 additions & 19 deletions src/make.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,26 +116,21 @@ async function make({
/**
* `package.json` data.
*
* @var {Nullable<PackageJson>} pkg
* @const {Nullable<PackageJson>} pkg
*/
let pkg: Nullable<PackageJson> = null

// get package.json
if (options.write) {
pkg = mlly.readPackageJson(cwd)

// throw if package.json was not found
if (!pkg) {
throw new ERR_MODULE_NOT_FOUND(
pathe.join(cwd, 'package.json'),
fileURLToPath(import.meta.url),
'module'
)
}
const pkg: Nullable<PackageJson> = mlly.readPackageJson(cwd)

// throw if package.json was not found
if (!pkg) {
throw new ERR_MODULE_NOT_FOUND(
pathe.join(cwd, 'package.json'),
fileURLToPath(import.meta.url),
'module'
)
}

// print build start info
options.write && consola.info(color.cyan(`Building ${pkg!.name}`))
options.write && consola.info(color.cyan(`Building ${pkg.name}`))

// push empty object to infer entry from config if initial array is empty
if (entries.length === 0) entries.push({})
Expand All @@ -146,7 +141,7 @@ async function make({
* @const {Entry[]} tasks
*/
const tasks: Entry[] = entries.map(entry => {
const { peerDependencies = {} } = pkg ?? /* c8 ignore next */ {}
const { peerDependencies = {} } = pkg

const {
bundle = options.bundle,
Expand Down Expand Up @@ -208,7 +203,7 @@ async function make({
build.set(index, [])

// build source files
const [, results] = await esbuilder(entry, fs)
const [, results] = await esbuilder(entry, pkg, fs)

// add build results to build results map
for (const result of results) build.get(index)!.push(result)
Expand All @@ -224,7 +219,7 @@ async function make({
let bytes: number = 0

// print build done info
consola.success(color.green(`Build succeeded for ${pkg!.name}`))
consola.success(color.green(`Build succeeded for ${pkg.name}`))

// print build analysis
for (const [index, outputs] of build.entries()) {
Expand Down
22 changes: 18 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1229,6 +1229,7 @@ __metadata:
"@flex-development/mlly": "npm:1.0.0-alpha.13"
"@flex-development/pathe": "npm:1.0.3"
"@flex-development/pkg-types": "npm:2.0.0"
"@flex-development/toggle-pkg-type": "npm:1.1.1"
"@flex-development/tsconfig-utils": "npm:1.1.2"
"@flex-development/tutils": "npm:6.0.0-alpha.10"
"@graphql-eslint/eslint-plugin": "npm:3.16.0"
Expand Down Expand Up @@ -1367,6 +1368,19 @@ __metadata:
languageName: node
linkType: hard

"@flex-development/toggle-pkg-type@npm:1.1.1":
version: 1.1.1
resolution: "@flex-development/toggle-pkg-type@npm:1.1.1::__archiveUrl=https%3A%2F%2Fnpm.pkg.github.com%2Fdownload%2F%40flex-development%2Ftoggle-pkg-type%2F1.1.1%2F536f86b58a650e7b830ee3d88c750c3771b6dbc5"
dependencies:
"@flex-development/mlly": "npm:1.0.0-alpha.13"
"@flex-development/pathe": "npm:1.0.3"
"@flex-development/tutils": "npm:6.0.0-alpha.10"
bin:
toggle-pkg-type: dist/cli.mjs
checksum: 6ae31dfc2a193139b52fba42d9424eca4b4fdf6eb74621fd29d20508ae0148f7fae141f122995d1ec864dade8fd847a747cc24525ea6ad203e766e5692d3311a
languageName: node
linkType: hard

"@flex-development/tsconfig-types@npm:3.2.0":
version: 3.2.0
resolution: "@flex-development/tsconfig-types@npm:3.2.0::__archiveUrl=https%3A%2F%2Fnpm.pkg.github.com%2Fdownload%2F%40flex-development%2Ftsconfig-types%2F3.2.0%2Fe49eb5faa42583a340fdff7c9ec64ac5feaf4529"
Expand Down Expand Up @@ -8792,13 +8806,13 @@ __metadata:
languageName: node
linkType: hard

"typescript@npm:5.0.0-dev.20230222":
version: 5.0.0-dev.20230222
resolution: "typescript@npm:5.0.0-dev.20230222"
"typescript@npm:5.0.0-dev.20230224":
version: 5.0.0-dev.20230224
resolution: "typescript@npm:5.0.0-dev.20230224"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: e22533927607fb9a52c7dbd2d2f530f268f2a7a03596ed9f76e5b20e9a49fe093c55441650d9d0f566e5f850be4a15d0e3f193aa987e62788d2860f7a909f1a2
checksum: 2c30ee32a78f64844b877032db0a974e1666033b867181158770b0283c210f6e2ba8576f5dca5c2e8e95a4239c6733bd5a9d15d67fbade3580d38125606ce26d
languageName: node
linkType: hard

Expand Down

0 comments on commit 755b9a7

Please sign in to comment.