Skip to content

Commit

Permalink
esm/cjs compilation
Browse files Browse the repository at this point in the history
  • Loading branch information
shazarre committed Nov 30, 2023
1 parent 8d341ab commit 90a16c9
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/publish-contracts-abi-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
run: |
cat package.json
npm publish $RELEASE_TYPE $DRY_RUN
working-directory: packages/protocol/abis/src-generated
working-directory: packages/protocol/abis
env:
RELEASE_TYPE: --tag ${{ env.RELEASE_TYPE != '' && env.RELEASE_TYPE || 'canary' }}
RELEASE_VERSION: ${{ env.RELEASE_VERSION }}
Expand Down
3 changes: 3 additions & 0 deletions packages/protocol/abis/package-cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
3 changes: 3 additions & 0 deletions packages/protocol/abis/package-esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
"author": "cLabs",
"license": "LGPL-3.0",
"repository": {
"type": "git",
"url": "https://github.com/celo-org/celo-monorepo.git",
"url": "git+https://github.com/celo-org/celo-monorepo.git",
"directory": "packages/protocol/abis"
},
"scripts": {},
"dependencies": {},
"types": "./types/wagmi/index.d.ts"
"peerDependencies": {},
"files": [
"./dist"
]
}
8 changes: 8 additions & 0 deletions packages/protocol/abis/tsconfig-cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"outDir": "./dist/cjs"
},
"references": [{ "path": "../../sdk/utils" }]
}
25 changes: 25 additions & 0 deletions packages/protocol/abis/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"compileOnSave": false,
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"baseUrl": ".",
"strict": true,
"moduleResolution": "node",
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"skipLibCheck": true,
"sourceMap": true,
"target": "ES2020",
"downlevelIteration": true,
"resolveJsonModule": true,
"declaration": true,
"module": "ES2020",
"rootDir": "./src-generated",
"outDir": "./dist/esm"
},
"include": ["./src-generated"],
"exclude": ["./src-generated/types/ethers"],
"references": [{ "path": "../../sdk/utils" }]
}
9 changes: 8 additions & 1 deletion packages/protocol/scripts/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ export const ROOT_DIR = path.join(__dirname, '../')
export const CONTRACTS_PACKAGE_SRC_DIR = path.join(__dirname, '../contracts')
export const ABIS_PACKAGE_SRC_DIR = path.join(__dirname, '../abis')
export const ABIS_BUILD_DIR = path.join(ABIS_PACKAGE_SRC_DIR, 'src-generated')
export const ABIS_DIST_DIR = path.join(ABIS_PACKAGE_SRC_DIR, 'dist')
export const BUILD_EXECUTABLE = path.join(__dirname, 'build.ts')
export const TSCONFIG_PATH = path.join(ROOT_DIR, 'tsconfig.json')

const PROXY_CONTRACT = 'Proxy'

export const ProxyContracts = [
'AccountsProxy',
'AttestationsProxy',
Expand Down Expand Up @@ -73,7 +76,7 @@ export const CoreContracts = [
]

export const OtherContracts = [
'Proxy',
PROXY_CONTRACT,
'Migrations',
// abstract
'Initializable',
Expand All @@ -85,3 +88,7 @@ export const contractPackages = [MENTO_PACKAGE, SOLIDITY_08_PACKAGE].filter(Bool
export const Interfaces = ['ICeloToken', 'IERC20', 'ICeloVersionedContract']

export const ImplContracts = OtherContracts.concat(ProxyContracts).concat(CoreContracts)

export const PublishContracts = CoreContracts.concat(Interfaces)
.concat(PROXY_CONTRACT)
.concat(MENTO_PACKAGE.contracts)
140 changes: 110 additions & 30 deletions packages/protocol/scripts/prepare-contracts-and-abis-publishing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { sync as rmrfSync } from 'rimraf'
import { MENTO_PACKAGE, SOLIDITY_08_PACKAGE } from '../contractPackages'
import {
ABIS_BUILD_DIR,
ABIS_DIST_DIR,
ABIS_PACKAGE_SRC_DIR,
BUILD_EXECUTABLE,
CONTRACTS_PACKAGE_SRC_DIR,
CoreContracts,
Interfaces,
PublishContracts,
TSCONFIG_PATH,
} from './consts'

Expand All @@ -25,8 +25,9 @@ try {
fs.writeFileSync(TSCONFIG_PATH, JSON.stringify(tsconfig, null, 4))

// Start from scratch
rmrfSync([ABIS_BUILD_DIR, path.join(ABIS_PACKAGE_SRC_DIR, 'lib')])
rmrfSync([ABIS_BUILD_DIR, ABIS_DIST_DIR])
fs.mkdirSync(ABIS_BUILD_DIR, { recursive: true })
fs.mkdirSync(ABIS_DIST_DIR, { recursive: true })

// Generate all ABIs
build(`--solidity ${path.join(ABIS_BUILD_DIR)}`)
Expand All @@ -35,7 +36,6 @@ try {
build(`--ethersTypes ${path.join(ABIS_BUILD_DIR, 'types/ethers')}`)

// Generate web3 typings
// TODO web3 is generating nested dir structure
build(`--web3Types ${path.join(ABIS_BUILD_DIR, 'types/web3')}`)

// Merge contracts-0.8, contracts-mento, etc.. at the root of the build dir
Expand All @@ -52,32 +52,37 @@ try {
const name = path.basename(filePath)
const baseName = name.replace(/.(sol|d.ts|json)$/, '')

if (
baseName !== 'index' &&
baseName !== 'Proxy' &&
!CoreContracts.includes(baseName) &&
!Interfaces.includes(baseName)
) {
if (baseName !== 'index' && !PublishContracts.includes(baseName)) {
rmrfSync(path.join(ABIS_BUILD_DIR, `${baseName}.json`))
rmrfSync(path.join(ABIS_BUILD_DIR, `${baseName}.ts`))
rmrfSync(path.join(ABIS_BUILD_DIR, '**', `${baseName}.d.ts`))
rmrfSync(path.join(ABIS_BUILD_DIR, '**', `${baseName}.ts`))
}
})

removeExtraneousFieldsFromGeneratedJsons()
let exports = processRawJsonsAndPrepareExports()

// Generate wagmi friendly ts files
log('Running yarn wagmi generate')
child_process.execSync(`yarn wagmi generate`, { stdio: 'inherit' })

fs.copyFileSync(
path.join(ABIS_PACKAGE_SRC_DIR, 'README.md'),
path.join(ABIS_BUILD_DIR, 'README.md')
)
log('Compiling esm')
child_process.execSync(`yarn tsc -b ${path.join(ABIS_PACKAGE_SRC_DIR, 'tsconfig.json')}`, {
stdio: 'inherit',
})

log('Compiling cjs')
child_process.execSync(`yarn tsc -b ${path.join(ABIS_PACKAGE_SRC_DIR, 'tsconfig-cjs.json')}`, {
stdio: 'inherit',
})

exports = {
...exports,
...prepareTargetTypesExports(),
}

// Change the packages version to what CI is providing from environment variables
prepareAbisPackageJson()
prepareAbisPackageJson(exports)
prepareContractsPackageJson()
} finally {
// Cleanup
Expand All @@ -88,24 +93,89 @@ try {
}

// Helper functions
function removeExtraneousFieldsFromGeneratedJsons() {
function prepareTargetTypesExports() {
const exports = {}
const targets = ['esm', 'cjs']

targets.forEach((target) => {
fs.copyFileSync(
path.join(ABIS_PACKAGE_SRC_DIR, `package-${target}.json`),
path.join(ABIS_DIST_DIR, target, 'package.json')
)

const filePaths = lsRecursive(path.join(ABIS_DIST_DIR, target))

filePaths.forEach((filePath) => {
const parsedPath = path.parse(filePath)

if (PublishContracts.includes(parsedPath.name)) {
const relativePath = path.join(
path.relative(ABIS_PACKAGE_SRC_DIR, parsedPath.dir),
parsedPath.name
)
const exportKey = `./${path.join(
path.relative(path.join(ABIS_DIST_DIR, target), parsedPath.dir),
parsedPath.name
)}`

if (!exports.hasOwnProperty(exportKey)) {
exports[exportKey] = {}
}

if (target == 'esm') {
const typesPath = `./${relativePath}.d.ts`
const importPath = `./${relativePath}.js`

expectFileExists(typesPath)
expectFileExists(importPath)

exports[exportKey] = {
...exports[exportKey],
types: typesPath,
import: importPath,
}
} else {
const requirePath = `./${relativePath}.js`

expectFileExists(requirePath)

exports[exportKey] = {
...exports[exportKey],
require: `./${relativePath}.js`,
}
}
}
})
})

return exports
}

function expectFileExists(relativePath: string) {
if (!fs.existsSync(path.join(ABIS_PACKAGE_SRC_DIR, relativePath))) {
throw new Error(`Expected file ${relativePath} to exist`)
}
}

function processRawJsonsAndPrepareExports() {
const exports = {}

log('Removing extraneous fields from generated json files')
const fileNames = fs.readdirSync(ABIS_BUILD_DIR)

fileNames.forEach((fileName) => {
const filePath = path.join(ABIS_BUILD_DIR, fileName)
const parsedPath = path.parse(filePath)

// TODO create a single const for all contracts
if (
Interfaces.includes(parsedPath.name) ||
CoreContracts.includes(parsedPath.name) ||
parsedPath.name === 'Proxy'
) {
if (PublishContracts.includes(parsedPath.name)) {
const json = JSON.parse(fs.readFileSync(filePath).toString())
const defaultPath = path.join(
path.relative(ABIS_PACKAGE_SRC_DIR, ABIS_DIST_DIR),
`${parsedPath.name}.json`
)

fs.writeFileSync(
filePath,
path.join(ABIS_DIST_DIR, fileName),
JSON.stringify(
{
contractName: json.contractName,
Expand All @@ -115,25 +185,35 @@ function removeExtraneousFieldsFromGeneratedJsons() {
2
)
)

expectFileExists(defaultPath)

exports[`./${parsedPath.name}.json`] = {
default: `./${defaultPath}`,
}
}
})

return exports
}

function prepareAbisPackageJson() {
function prepareAbisPackageJson(exports) {
log('Preparing @celo/abis package.json')
const sourcePackageJson = path.join(ABIS_PACKAGE_SRC_DIR, 'package.json.dist')
const destinationPackageJson = path.join(ABIS_BUILD_DIR, 'package.json')
let contents = fs.readFileSync(sourcePackageJson).toString()
const packageJsonPath = path.join(ABIS_PACKAGE_SRC_DIR, 'package.json')
let json = JSON.parse(fs.readFileSync(packageJsonPath).toString())

if (process.env.RELEASE_VERSION) {
log('Replacing @celo/abis version with provided RELEASE_VERSION')

contents = contents.replace('0.0.0-template.version', process.env.RELEASE_VERSION)
json.version = process.env.RELEASE_VERSION
} else {
log('No RELEASE_VERSION provided')
}

fs.writeFileSync(destinationPackageJson, contents)
log('Setting @celo/abis exports')
json.exports = exports

fs.writeFileSync(packageJsonPath, JSON.stringify(json, null, 2))
}

function prepareContractsPackageJson() {
Expand Down

0 comments on commit 90a16c9

Please sign in to comment.