Skip to content

Commit

Permalink
better support for exports. fixed issue with workers with ESM version
Browse files Browse the repository at this point in the history
  • Loading branch information
juanelas committed Apr 14, 2023
1 parent 7a25b3b commit ee2a0c1
Show file tree
Hide file tree
Showing 288 changed files with 13,293 additions and 3,597 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ coverage
# Test temporal files
.mocha-ts
.tsconfig.json
.types

# docs temporal files
.nojekyll
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ src/docs
# Test temporal files
.mocha-ts
.tsconfig.json
.types

# docs temporal files
.nojekyll
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import * as nonRepudiationLibrary from '@i3m/non-repudiation-library'

The appropriate version for browser or node is automatically exported.

You can also download the [IIFE bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundles/iife.js), the [ESM bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundles/esm.min.js) or the [UMD bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundles/umd.js) and manually add it to your project, or, if you have already installed `@i3m/non-repudiation-library` in your project, just get the bundles from `node_modules/@i3m/non-repudiation-library/dist/bundles/`.
You can also download the [IIFE bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundle.iife.js), the [ESM bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundle.esm.min.js) or the [UMD bundle](https://raw.githubusercontent.com/i3-Market-V2-Public-Repository/SP3-SCGBSSW-CR-NonRepudiationLibrary/main/dist/bundle.umd.js) and manually add it to your project, or, if you have already installed `@i3m/non-repudiation-library` in your project, just get the bundles from `node_modules/@i3m/non-repudiation-library/dist/bundles/`.

### Example for an i3-MARKET Provider running the Non-Repudiation Protocol

Expand Down
8 changes: 5 additions & 3 deletions build/bin/mocha-ts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const minimatch = require('minimatch')
const minimatch = require('minimatch').minimatch
const rimraf = require('rimraf')
const runScript = require('../run-script.cjs')

Expand Down Expand Up @@ -58,9 +58,11 @@ function parse () {
process.exit(1)
}

let testsGlob = (args.pop() ?? '').replace(/^['"]/, '').replace(/['"]$/, '') // Let us remove surrounding quotes in string (it gives issues in windows)
if (testsGlob === '') {
let testsGlob = args.pop()
if (testsGlob === undefined) {
testsGlob = '{src/ts/**/*.spec.ts,test/**/*.ts}'
} else {
testsGlob = testsGlob.replace(/^['"]/, '').replace(/['"]$/, '') // Let us remove surrounding quotes in string (it gives issues in windows)
}

const mochaArgs = []
Expand Down
7 changes: 1 addition & 6 deletions build/build.docs.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ async function typedoc () {
const tsConfig = json5.parse(fs.readFileSync(tsConfigPath, 'utf8'))
tsConfig.include = ['src/ts/**/*', 'build/typings/**/*.d.ts']
tsConfig.exclude = ['src/**/*.spec.ts']
delete tsConfig.compilerOptions.outDir
// delete tsConfig.exclude
fs.writeFileSync(tempTsConfigPath, JSON.stringify(tsConfig, undefined, 2))

// If you want TypeDoc to load tsconfig.json / typedoc.json files
Expand All @@ -68,10 +66,7 @@ async function typedoc () {
excludePrivate: true
})

// This is the part that seems to skip compile errors
// (normally we would call `app.convert()` here)
const project = app.converter.convert(app.getEntryPoints() ?? [])
// const project = app.convert()
const project = app.convert()

if (project) {
// Project may not have converted correctly
Expand Down
44 changes: 21 additions & 23 deletions build/rollup-plugin-dts.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdirSync, readFileSync, writeFileSync } from 'fs'
import { mkdirSync, writeFileSync } from 'fs'
import ts from 'typescript'
import { join, dirname, extname } from 'path'
import { sync } from 'rimraf'
Expand All @@ -8,9 +8,7 @@ const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
const { readJsonConfigFile, sys, parseJsonSourceFileConfigFileContent, createCompilerHost, createProgram } = ts

const rootDir = join(__dirname, '..')
const pkgJson = JSON.parse(readFileSync(join(rootDir, 'package.json')))
const srcFile = join(rootDir, 'src/ts/index.ts')
const outDir = dirname(join(rootDir, pkgJson.types))

const tsConfigPath = join(rootDir, 'tsconfig.json')

Expand All @@ -20,31 +18,31 @@ const configFile = readJsonConfigFile(tsConfigPath, (file) => {

const tsConfig = parseJsonSourceFileConfigFileContent(configFile, sys, dirname(tsConfigPath))

const compilerOptions = {
...tsConfig.options,
declaration: true,
declarationMap: true,
emitDeclarationOnly: true,
outDir
}
export const compile = (outDir) => {
const compilerOptions = {
...tsConfig.options,
declaration: true,
declarationMap: true,
emitDeclarationOnly: true,
outDir
}

const host = createCompilerHost(compilerOptions)
const host = createCompilerHost(compilerOptions)

host.writeFile = (fileName, contents) => {
mkdirSync(dirname(fileName), { recursive: true })
writeFileSync(fileName, contents)
host.writeFile = (fileName, contents) => {
mkdirSync(dirname(fileName), { recursive: true })
writeFileSync(fileName, contents)

// we also write the .d.cts types
let fileName2 = ''
if (extname(fileName) === '.ts') {
fileName2 = fileName.slice(0, -2) + 'cts'
} else { // ext is .d.ts.map
fileName2 = fileName.slice(0, -6) + 'cts.map'
// we also write the .d.cts types
let fileName2 = ''
if (extname(fileName) === '.ts') {
fileName2 = fileName.slice(0, -2) + 'cts'
} else { // ext is .d.ts.map
fileName2 = fileName.slice(0, -6) + 'cts.map'
}
writeFileSync(fileName2, contents)
}
writeFileSync(fileName2, contents)
}

export const compile = () => {
// Clear the types dir
sync(outDir)
// Prepare and emit the d.ts files
Expand Down
144 changes: 99 additions & 45 deletions build/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,50 @@
'use strict'

import commonjs from '@rollup/plugin-commonjs'
import inject from '@rollup/plugin-inject'
import json from '@rollup/plugin-json'
import { nodeResolve as resolve } from '@rollup/plugin-node-resolve'
import replace from '@rollup/plugin-replace'
import terser from '@rollup/plugin-terser'
import typescriptPlugin from '@rollup/plugin-typescript'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'

import { dirname, join } from 'path'
import rollupPluginTs from '@rollup/plugin-typescript'
import { existsSync, readFileSync } from 'fs'

// import { browser, name as _name, exports } from '../package.json' assert { type: 'json' }
import { builtinModules } from 'module'
import { join } from 'path'
import dts from 'rollup-plugin-dts'
import { compile } from './rollup-plugin-dts.js'

import * as url from 'url'
const __dirname = url.fileURLToPath(new URL('.', import.meta.url))

const rootDir = join(__dirname, '..')
const pkgJson = JSON.parse(readFileSync(join(rootDir, 'package.json')))
// const dstDir = join(rootDir, directories.dist)
const pkgJsonLock = JSON.parse(readFileSync(join(rootDir, 'package-lock.json')))
const srcDir = join(rootDir, 'src', 'ts')

const tsConfigPath = join(rootDir, 'tsconfig.json')

function camelise (str) {
return str.replace(/-([a-z])/g,
function (m, w) {
return w.toUpperCase()
})
}

function isDevDependency (moduleName) {
const packageEntry = pkgJsonLock.packages['node_modules/' + moduleName]
return (packageEntry ?? {}).dev === true
}

const regex = /^(?:(?<scope>@.*?)\/)?(?<name>.*)/ // We are going to take only the package name part if there is a scope, e.g. @my-org/package-name
const { name } = pkgJson.name.match(regex).groups
const pkgCamelisedName = camelise(name)

const input = join(srcDir, 'index.ts')
if (existsSync(input) !== true) throw new Error('The entry point should be index.ts')

const tsBundleOptions = {
tsconfig: join(rootDir, 'tsconfig.json'),
outDir: undefined, // ignore outDir in tsconfig.json
const tsPluginOptions = {
tsconfig: tsConfigPath,
outDir: undefined,
include: ['src/ts/**/*', 'build/typings/is-browser.d.ts'],
exclude: ['src/**/*.spec.ts']
}
Expand All @@ -48,23 +54,47 @@ const sourcemapOutputOptions = {
sourcemapExcludeSources: true
}

function compileDts () {
function compileDts (outDir) {
return {
name: 'compile-dts',
closeBundle () {
compile()
compile(outDir)
}
}
}

function resolveOnly (module) { // if a dev dependency is imported we will resolve it so that the dist modules always work
const moduleNameMatch = module.match(/^(?:@[a-z0-9_-]+\/)?(?:node:)?[a-z0-9_-]+/)
if (moduleNameMatch === null || moduleNameMatch.length !== 1) {
return false
}
const moduleName = moduleNameMatch[0].replace(/^node:/, '')
// don't resolve if it is a native module
if (builtinModules.includes(moduleName)) {
return false
}

if (isDevDependency(moduleName)) {
console.warn(`\x1b[33m⚠ WARM: dev dependency \x1b[0m${module}\x1b[33m being bundled. Should it be a dependency instead?\x1b[0m`)
return true
}

return false
}

const tmpDeclarationsDir = join(rootDir, '.types')

export default [
{ // Browser ESM bundle
{ // Browser ESM
input,
output: [
{
file: join(rootDir, pkgJson.browser),
file: join(rootDir, pkgJson.exports['.'].default.default),
...sourcemapOutputOptions,
format: 'es'
format: 'es',
plugins: [
terser()
]
}
],
plugins: [
Expand All @@ -73,10 +103,15 @@ export default [
_MODULE_TYPE: "'ESM'",
preventAssignment: true
}),
typescriptPlugin(tsBundleOptions),
resolve({ resolveOnly: [/^@i3m\/.*$/] }),
commonjs({ extensions: ['.js', '.cjs', '.ts', '.jsx', '.cjsx', '.tsx'] }), // the ".ts" extension is required
json({ compact: true })
rollupPluginTs(tsPluginOptions),
commonjs({ extensions: ['.js', '.cjs', '.jsx', '.cjsx'] }),
json(),
resolve({
browser: true,
exportConditions: ['browser', 'default'],
mainFields: ['browser', 'module', 'main'],
resolveOnly
})
]
},
{ // Browser bundles
Expand Down Expand Up @@ -110,17 +145,13 @@ export default [
_MODULE_TYPE: "'BUNDLE'",
preventAssignment: true
}),
typescriptPlugin({
...tsBundleOptions,
rollupPluginTs({
...tsPluginOptions,
sourceMap: false
}),
resolve({
browser: true,
exportConditions: ['browser', 'default'],
mainFields: ['browser', 'module', 'main']
}),
commonjs({ extensions: ['.js', '.cjs', '.ts', '.jsx', '.cjsx', '.tsx'] }), // the ".ts" extension is required
json({ compact: true })
commonjs({ extensions: ['.js', '.cjs', '.jsx', '.cjsx'] }),
json(),
resolve({ browser: true })
]
},
{ // Node CJS
Expand All @@ -137,18 +168,26 @@ export default [
}
],
plugins: [
replace({
'await import(': 'require(',
delimiters: ['', ''],
preventAssignment: true
}),
replace({
IS_BROWSER: false,
_MODULE_TYPE: "'CJS'",
preventAssignment: true
}),
rollupPluginTs(tsPluginOptions),
inject({
crypto: ['crypto', 'webcrypto']
}),
typescriptPlugin(tsBundleOptions),
resolve({ resolveOnly: [/^@i3m\/.*$/] }),
commonjs({ extensions: ['.js', '.cjs', '.ts', '.jsx', '.cjsx', '.tsx'] }), // the ".ts" extension is required
json({ compact: true })
commonjs({ extensions: ['.js', '.cjs', '.jsx', '.cjsx'] }),
json(),
resolve({
exportConditions: ['node'],
resolveOnly
})
]
},
{ // Node ESM and type declarations
Expand All @@ -167,22 +206,37 @@ export default [
replace({
IS_BROWSER: false,
_MODULE_TYPE: "'ESM'",
__filename: `'${pkgJson.exports['.'].node.import.default}'`,
__dirname: `'${dirname(pkgJson.exports['.'].node.import.default)}'`,
__filename: 'fileURLToPath(import.meta.url)',
__dirname: 'fileURLToPath(new URL(\'.\', import.meta.url))',
preventAssignment: true
}),
rollupPluginTs(tsPluginOptions),
compileDts(tmpDeclarationsDir),
inject({
crypto: ['crypto', 'webcrypto']
crypto: ['crypto', 'webcrypto'],
fileURLToPath: ['url', 'fileURLToPath']
}),
typescriptPlugin(tsBundleOptions),
// resolve({
// browser: false,
// exportConditions: ['node']
// }),
resolve({ resolveOnly: [/^@i3m\/.*$/] }),
compileDts(),
commonjs({ extensions: ['.js', '.cjs', '.ts', '.jsx', '.cjsx', '.tsx'] }), // the ".ts" extension is required
json({ compact: true })
commonjs({ extensions: ['.js', '.cjs', '.jsx', '.cjsx'] }),
json(),
resolve({
exportConditions: ['node'],
resolveOnly
})
]
},
{
input: join(tmpDeclarationsDir, 'index.d.ts'),
output: [{ file: 'dist/index.d.ts', format: 'es' }],
plugins: [
dts({
respectExternal: true
})
],
external: (module) => {
if (/^[./]/.test(module)) {
return false
}
return !resolveOnly(module)
}
}
]
2 changes: 1 addition & 1 deletion build/testing/browser/index.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const path = require('path')

const puppeteer = require('puppeteer')
const minimatch = require('minimatch')
const minimatch = require('minimatch').minimatch
const glob = require('glob')
const rootDir = path.join(__dirname, '../../..')
const pkgJson = require(path.join(rootDir, 'package.json'))
Expand Down
Loading

0 comments on commit ee2a0c1

Please sign in to comment.