Skip to content

Commit

Permalink
chore: improve typing for scripts (#9709)
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxiangmoe committed Nov 30, 2023
1 parent 3071de4 commit 7218ab7
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 56 deletions.
50 changes: 37 additions & 13 deletions rollup.config.js
@@ -1,4 +1,5 @@
// @ts-check
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
Expand All @@ -14,6 +15,14 @@ import alias from '@rollup/plugin-alias'
import { entries } from './scripts/aliases.js'
import { inlineEnums } from './scripts/inline-enums.js'

/**
* @template T
* @template {keyof T} K
* @typedef { Omit<T, K> & Required<Pick<T, K>> } MarkRequired
*/
/** @typedef {'cjs' | 'esm-bundler' | 'global' | 'global-runtime' | 'esm-browser' | 'esm-bundler-runtime' | 'esm-browser-runtime'} PackageFormat */
/** @typedef {MarkRequired<import('rollup').OutputOptions, 'file' | 'format'>} OutputOptions */

if (!process.env.TARGET) {
throw new Error('TARGET package must be specified via --environment flag.')
}
Expand All @@ -27,34 +36,35 @@ const consolidatePkg = require('@vue/consolidate/package.json')
const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, process.env.TARGET)

const resolve = p => path.resolve(packageDir, p)
const resolve = (/** @type {string} */ p) => path.resolve(packageDir, p)
const pkg = require(resolve(`package.json`))
const packageOptions = pkg.buildOptions || {}
const name = packageOptions.filename || path.basename(packageDir)

const [enumPlugin, enumDefines] = inlineEnums()

/** @type {Record<PackageFormat, OutputOptions>} */
const outputConfigs = {
'esm-bundler': {
file: resolve(`dist/${name}.esm-bundler.js`),
format: `es`
format: 'es'
},
'esm-browser': {
file: resolve(`dist/${name}.esm-browser.js`),
format: `es`
format: 'es'
},
cjs: {
file: resolve(`dist/${name}.cjs.js`),
format: `cjs`
format: 'cjs'
},
global: {
file: resolve(`dist/${name}.global.js`),
format: `iife`
format: 'iife'
},
// runtime-only builds, for main "vue" package only
'esm-bundler-runtime': {
file: resolve(`dist/${name}.runtime.esm-bundler.js`),
format: `es`
format: 'es'
},
'esm-browser-runtime': {
file: resolve(`dist/${name}.runtime.esm-browser.js`),
Expand All @@ -66,8 +76,13 @@ const outputConfigs = {
}
}

/** @type {ReadonlyArray<PackageFormat>} */
const defaultFormats = ['esm-bundler', 'cjs']
const inlineFormats = process.env.FORMATS && process.env.FORMATS.split(',')
/** @type {ReadonlyArray<PackageFormat>} */
const inlineFormats = /** @type {any} */ (
process.env.FORMATS && process.env.FORMATS.split(',')
)
/** @type {ReadonlyArray<PackageFormat>} */
const packageFormats = inlineFormats || packageOptions.formats || defaultFormats
const packageConfigs = process.env.PROD_ONLY
? []
Expand All @@ -89,6 +104,13 @@ if (process.env.NODE_ENV === 'production') {

export default packageConfigs

/**
*
* @param {PackageFormat} format
* @param {OutputOptions} output
* @param {ReadonlyArray<import('rollup').Plugin>} plugins
* @returns {import('rollup').RollupOptions}
*/
function createConfig(format, output, plugins = []) {
if (!output) {
console.log(pico.yellow(`invalid format: "${format}"`))
Expand Down Expand Up @@ -132,6 +154,7 @@ function createConfig(format, output, plugins = []) {
}

function resolveDefine() {
/** @type {Record<string, string>} */
const replacements = {
__COMMIT__: `"${process.env.COMMIT}"`,
__VERSION__: `"${masterVersion}"`,
Expand Down Expand Up @@ -162,15 +185,16 @@ function createConfig(format, output, plugins = []) {

if (!isBundlerESMBuild) {
// hard coded dev/prod builds
// @ts-ignore
replacements.__DEV__ = String(!isProductionBuild)
}

// allow inline overrides like
//__RUNTIME_COMPILE__=true pnpm build runtime-core
Object.keys(replacements).forEach(key => {
if (key in process.env) {
replacements[key] = process.env[key]
const value = process.env[key]
assert(typeof value === 'string')
replacements[key] = value
}
})
return replacements
Expand Down Expand Up @@ -207,7 +231,6 @@ function createConfig(format, output, plugins = []) {
}

if (Object.keys(replacements).length) {
// @ts-ignore
return [replace({ values: replacements, preventAssignment: true })]
} else {
return []
Expand Down Expand Up @@ -245,6 +268,7 @@ function createConfig(format, output, plugins = []) {
function resolveNodePlugins() {
// we are bundling forked consolidate.js in compiler-sfc which dynamically
// requires a ton of template engines which should be ignored.
/** @type {ReadonlyArray<string>} */
let cjsIgnores = []
if (
pkg.name === '@vue/compiler-sfc' ||
Expand Down Expand Up @@ -304,7 +328,7 @@ function createConfig(format, output, plugins = []) {
],
output,
onwarn: (msg, warn) => {
if (!/Circular/.test(msg)) {
if (msg.code !== 'CIRCULAR_DEPENDENCY') {
warn(msg)
}
},
Expand All @@ -314,14 +338,14 @@ function createConfig(format, output, plugins = []) {
}
}

function createProductionConfig(format) {
function createProductionConfig(/** @type {PackageFormat} */ format) {
return createConfig(format, {
file: resolve(`dist/${name}.${format}.prod.js`),
format: outputConfigs[format].format
})
}

function createMinifiedConfig(format) {
function createMinifiedConfig(/** @type {PackageFormat} */ format) {
return createConfig(
format,
{
Expand Down
38 changes: 23 additions & 15 deletions rollup.dts.config.js
@@ -1,6 +1,7 @@
// @ts-check
import assert from 'node:assert/strict'
import { parse } from '@babel/parser'
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs'
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import MagicString from 'magic-string'
import dts from 'rollup-plugin-dts'

Expand Down Expand Up @@ -70,15 +71,16 @@ function patchTypes(pkg) {
if (!node.id) {
return
}
// @ts-ignore
assert(node.id.type === 'Identifier')
const name = node.id.name
if (name.startsWith('_')) {
return
}
shouldRemoveExport.add(name)
if (isExported.has(name)) {
// @ts-ignore
s.prependLeft((parentDecl || node).start, `export `)
const start = (parentDecl || node).start
assert(typeof start === 'number')
s.prependLeft(start, `export `)
}
}

Expand All @@ -102,9 +104,10 @@ function patchTypes(pkg) {
if (node.type === 'VariableDeclaration') {
processDeclaration(node.declarations[0], node)
if (node.declarations.length > 1) {
assert(typeof node.start === 'number')
assert(typeof node.end === 'number')
throw new Error(
`unhandled declare const with more than one declarators:\n${code.slice(
// @ts-ignore
node.start,
node.end
)}`
Expand All @@ -131,7 +134,7 @@ function patchTypes(pkg) {
spec.type === 'ExportSpecifier' &&
shouldRemoveExport.has(spec.local.name)
) {
// @ts-ignore
assert(spec.exported.type === 'Identifier')
const exported = spec.exported.name
if (exported !== spec.local.name) {
// this only happens if we have something like
Expand All @@ -141,19 +144,27 @@ function patchTypes(pkg) {
}
const next = node.specifiers[i + 1]
if (next) {
// @ts-ignore
assert(typeof spec.start === 'number')
assert(typeof next.start === 'number')
s.remove(spec.start, next.start)
} else {
// last one
const prev = node.specifiers[i - 1]
// @ts-ignore
s.remove(prev ? prev.end : spec.start, spec.end)
assert(typeof spec.start === 'number')
assert(typeof spec.end === 'number')
s.remove(
prev
? (assert(typeof prev.end === 'number'), prev.end)
: spec.start,
spec.end
)
}
removed++
}
}
if (removed === node.specifiers.length) {
// @ts-ignore
assert(typeof node.start === 'number')
assert(typeof node.end === 'number')
s.remove(node.start, node.end)
}
}
Expand Down Expand Up @@ -186,11 +197,8 @@ function copyMts() {
return {
name: 'copy-vue-mts',
writeBundle(_, bundle) {
writeFileSync(
'packages/vue/dist/vue.d.mts',
// @ts-ignore
bundle['vue.d.ts'].code
)
assert('code' in bundle['vue.d.ts'])
writeFileSync('packages/vue/dist/vue.d.mts', bundle['vue.d.ts'].code)
}
}
}
3 changes: 2 additions & 1 deletion scripts/aliases.js
Expand Up @@ -4,14 +4,15 @@ import { readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const resolveEntryForPkg = p =>
const resolveEntryForPkg = (/** @type {string} */ p) =>
path.resolve(
fileURLToPath(import.meta.url),
`../../packages/${p}/src/index.ts`
)

const dirs = readdirSync(new URL('../packages', import.meta.url))

/** @type {Record<string, string>} */
const entries = {
vue: resolveEntryForPkg('vue'),
'vue/compiler-sfc': resolveEntryForPkg('compiler-sfc'),
Expand Down
5 changes: 4 additions & 1 deletion scripts/build.js
Expand Up @@ -38,6 +38,7 @@ const prodOnly = !devOnly && (args.prodOnly || args.p)
const buildTypes = args.withTypes || args.t
const sourceMap = args.sourcemap || args.s
const isRelease = args.release
/** @type {boolean | undefined} */
const buildAllMatching = args.all || args.a
const writeSize = args.size
const commit = execaSync('git', ['rev-parse', '--short=7', 'HEAD']).stdout
Expand Down Expand Up @@ -102,7 +103,9 @@ async function runParallel(maxConcurrency, source, iteratorFn) {
ret.push(p)

if (maxConcurrency <= source.length) {
const e = p.then(() => executing.splice(executing.indexOf(e), 1))
const e = p.then(() => {
executing.splice(executing.indexOf(e), 1)
})
executing.push(e)
if (executing.length >= maxConcurrency) {
await Promise.race(executing)
Expand Down

0 comments on commit 7218ab7

Please sign in to comment.