first commit

This commit is contained in:
2026-09-08 20:28:54 +08:00
commit 2ada8d3d5a
37380 changed files with 4886169 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+3
View File
@@ -0,0 +1,3 @@
# @dcloudio/vue-cli-plugin-uni
> uni-app plugin for vue-cli
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env node
const yargsParser = require('yargs-parser')
const argv = yargsParser(process.argv.slice(2))
const action = argv._[0]
if (action === 'custom') {
require('../lib/commands/custom')(argv)
} else if (action === 'invoke') {
require('../lib/commands/invoke')(argv)
} else {
process.exit(0)
}
+297
View File
@@ -0,0 +1,297 @@
const path = require('path')
const webpack = require('webpack')
const {
runByHBuilderX,
isInHBuilderX,
parseJson,
parsePagesJson,
parseManifestJson,
showRunPrompt
} = require('@dcloudio/uni-cli-shared')
const uniI18n = require('@dcloudio/uni-cli-i18n')
const defaults = {
clean: true,
target: 'app',
'unsafe-inline': true
}
const modifyConfig = (config, fn) => {
if (Array.isArray(config)) {
config.forEach(c => fn(c))
} else {
fn(config)
}
}
module.exports = (api, options) => {
api.registerCommand('uni-build', {
description: 'build for production',
usage: 'vue-cli-service uni-build [options]',
options: {
'--watch': 'watch for changes',
'--minimize': 'Tell webpack to minimize the bundle using the TerserPlugin.',
'--auto-host': 'specify automator host',
'--auto-port': 'specify automator port',
'--subpackage': 'specify subpackage',
'--plugin': 'specify mp plugin',
'--manifest': 'build manifest.json',
'--sourcemap': 'generate sourcemap'
}
}, async (args) => {
for (const key in defaults) {
if (args[key] == null) {
args[key] = defaults[key]
}
}
if (args.manifest && process.env.UNI_PLATFORM === 'app-plus') {
return buildManifestJson()
}
const platforms = ['mp-weixin', 'mp-qq', 'mp-jd', 'mp-baidu', 'mp-alipay', 'mp-toutiao', 'mp-lark']
if (args.subpackage && platforms.includes(process.env.UNI_PLATFORM)) {
process.env.UNI_SUBPACKGE = args.subpackage
}
const mpPluginPlatforms = ['mp-weixin', 'mp-alipay']
if (args.plugin) {
if (mpPluginPlatforms.includes(process.env.UNI_PLATFORM)) {
process.env.UNI_MP_PLUGIN = args.plugin
analysisPluginDir()
} else {
console.log()
console.error(uniI18n.__('pluginUni.compileToMpPluginOnlySupportPlatform'))
console.log()
process.exit(0)
}
}
require('./util').initAutomator(args)
args.entry = args.entry || args._[0]
process.env.VUE_CLI_BUILD_TARGET = args.target
if (args.sourcemap) process.env.SOURCEMAP = args.sourcemap
await build(args, api, options)
delete process.env.VUE_CLI_BUILD_TARGET
})
}
function getWebpackConfig (api, args, options) {
const validateWebpackConfig = require('@vue/cli-service/lib/util/validateWebpackConfig')
// resolve raw webpack config
const webpackConfig = require('@vue/cli-service/lib/commands/build/resolveAppConfig')(api, args, options)
// check for common config errors
validateWebpackConfig(webpackConfig, api, options, args.target)
if (args.watch) {
modifyConfig(webpackConfig, config => {
config.watch = true
})
}
if (args.minimize && process.env.NODE_ENV !== 'production') {
modifyConfig(webpackConfig, config => {
config.optimization.minimize = true
if (webpack.version[0] <= 4) {
config.optimization.namedModules = false
}
})
} else {
modifyConfig(webpackConfig, config => {
if (!config.optimization) {
config.optimization = {}
}
if (webpack.version[0] <= 4) {
config.optimization.namedModules = false
}
})
}
return webpackConfig
}
function getWebpackConfigs (api, args, options) {
if (!process.env.UNI_USING_V3) {
return [getWebpackConfig(api, args, options)]
}
const pluginOptions = (options.pluginOptions || (options.pluginOptions = {}))
pluginOptions['uni-app-plus'] = {
service: true
}
options.publicPath = '/'
const serviceWebpackConfig = getWebpackConfig(api, args, options)
delete pluginOptions['uni-app-plus'].service
pluginOptions['uni-app-plus'].view = true
options.publicPath = './'
const viewWebpackConfig = getWebpackConfig(api, args, options)
return [serviceWebpackConfig, viewWebpackConfig]
}
async function build (args, api, options) {
const fs = require('fs-extra')
const chalk = require('chalk')
const {
log,
done,
logWithSpinner,
stopSpinner
} = require('@vue/cli-shared-utils')
const runByAliIde = process.env.BUILD_ENV === 'ali-ide'
log()
if (!runByHBuilderX && !runByAliIde) {
logWithSpinner(uniI18n.__('pluginUni.startCompileProjectToPlatform', {
0: process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM,
1: process.env.UNI_MP_PLUGIN ? uniI18n.__('plugin') : uniI18n.__('platform')
}))
}
const targetDir = api.resolve(options.outputDir)
const webpackConfigs = getWebpackConfigs(api, args, options)
if (process.env.NODE_ENV === 'production') {
try {
fs.emptyDir(path.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules/.cache'))
} catch (e) {}
}
if (args.clean || process.env.UNI_PLATFORM === 'app-plus') {
await fs.emptyDir(targetDir)
}
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
webpackConfigs.length = 0
}
if (
process.env.UNI_USING_NATIVE ||
process.env.UNI_USING_V3_NATIVE ||
(process.UNI_NVUE_ENTRY && Object.keys(process.UNI_NVUE_ENTRY).length)
) {
webpackConfigs.push(require('@dcloudio/vue-cli-plugin-hbuilderx/build/webpack.nvue.conf.js')(process
.UNI_NVUE_ENTRY))
}
return new Promise((resolve, reject) => {
webpack(webpackConfigs, (err, stats) => {
if (!runByHBuilderX && !runByAliIde) {
stopSpinner(false)
}
if (err) {
return reject(err)
}
if (stats.hasErrors()) {
/* eslint-disable prefer-promise-reject-errors */
return reject('Build failed with errors.')
}
if (!args.silent && (process.env.UNI_PLATFORM !== 'app-plus' || process.env
.UNI_AUTOMATOR_WS_ENDPOINT)) {
const targetDirShort = path.relative(
api.service.context,
process.env.UNI_OUTPUT_DIR
)
if (!args.watch) {
const dirMsg = runByHBuilderX ? ''
: `The ${chalk.cyan(targetDirShort)} directory is ready to be deployed.`
done(`Build complete. ${dirMsg}`)
if (process.env.UNI_PLATFORM !== 'h5') {
showRunPrompt()
}
if (process.env.UNI_PLATFORM === 'h5' && !isInHBuilderX) {
console.log()
console.log('欢迎将web站点部署到uniCloud前端网页托管平台,高速、免费、安全、省心,详见:https://uniapp.dcloud.io/uniCloud/hosting')
}
} else {
const dirMsg = runByHBuilderX ? ''
: `The ${chalk.cyan(targetDirShort)} directory is ready. `
done(`Build complete. ${dirMsg}Watching for changes...`)
showRunPrompt()
}
}
resolve()
})
})
}
module.exports.defaultModes = {
'uni-build': process.env.NODE_ENV
}
/**
* 编译到微信小程序插件 文件校验
*/
function analysisPluginDir () {
const fs = require('fs-extra')
// plugin.json 是否存在
const pluginJsonName = 'plugin.json'
const pluginJsonPath = path.resolve(process.env.UNI_INPUT_DIR, pluginJsonName)
if (!fs.pathExistsSync(pluginJsonPath)) {
console.log()
console.error(uniI18n.__('pluginUni.fileNoExistsCheckAfterRetry', {
0: pluginJsonName
}))
console.log()
process.exit(0)
}
const pluginJson = parseJson(fs.readFileSync(pluginJsonPath, 'utf-8'), true)
// main 入口文件是否存在
if (pluginJson.main) {
process.env.UNI_MP_PLUGIN_MAIN = pluginJson.main
const UNI_MP_PLUGIN_MAIN = process.env.UNI_MP_PLUGIN_MAIN
const mainFilePath = path.resolve(process.env.UNI_INPUT_DIR, UNI_MP_PLUGIN_MAIN)
if (UNI_MP_PLUGIN_MAIN && !fs.pathExistsSync(mainFilePath)) {
console.log()
console.error(uniI18n.__('pluginUni.entryDileNoExistsCheckAfterRetry', {
0: UNI_MP_PLUGIN_MAIN
}))
console.log()
process.exit(0)
}
}
}
function buildManifestJson () {
const fs = require('fs-extra')
const inputDir = process.env.UNI_INPUT_DIR
const outputDir = process.env.UNI_OUTPUT_DIR
const pagesJsonPath = path.resolve(inputDir, 'pages.json')
const manifestJsonPath = path.resolve(inputDir, 'manifest.json')
const pagesJson = parsePagesJson(fs.readFileSync(pagesJsonPath, 'utf8'))
const manifestJson = parseManifestJson(fs.readFileSync(manifestJsonPath, 'utf8'))
const res = require('@dcloudio/webpack-uni-pages-loader/lib/platforms/app-plus/index.js')(pagesJson,
manifestJson,
false)
if (res && res[0]) {
fs.outputFileSync(
path.resolve(outputDir, 'manifest.json'),
res[0].content
)
}
const {
done
} = require('@vue/cli-shared-utils')
done('Build complete.')
}
+14
View File
@@ -0,0 +1,14 @@
console.log('uni-app v' + require('@dcloudio/webpack-uni-pages-loader/package.json')['uni-app'].compilerVersion)
console.log('uni-app cli v' + require('../package.json').version)
console.log(require('chalk').bold('\nEnvironment Info:'))
require('envinfo').run({
System: ['OS', 'CPU'],
Binaries: ['Node', 'Yarn', 'npm'],
Browsers: ['Chrome', 'Edge', 'Firefox', 'Safari'],
npmPackages: '/**/{*vue*,@vue/*/,@dcloudio/*/}',
npmGlobalPackages: ['@vue/cli']
}, {
showNotFound: true,
duplicates: true,
fullTree: true
}).then(console.log)
+395
View File
@@ -0,0 +1,395 @@
const {
info,
openBrowser,
IpcMessenger
} = require('@vue/cli-shared-utils')
const defaults = {
host: '0.0.0.0',
port: 8080,
https: false
}
module.exports = (api, options) => {
api.registerCommand('uni-serve', {
description: 'start development server',
usage: 'vue-cli-service uni-serve [options] [entry]',
options: {
'--open': 'open browser on server start',
'--copy': 'copy url to clipboard on server start',
'--mode': 'specify env mode (default: development)',
'--host': `specify host (default: ${defaults.host})`,
'--port': `specify port (default: ${defaults.port})`,
'--https': `use https (default: ${defaults.https})`,
'--public': 'specify the public network URL for the HMR client',
'--auto-host': 'specify automator host',
'--auto-port': 'specify automator port'
}
}, async function serve (args) {
info('Starting development server...')
require('./util').initAutomator(args)
// although this is primarily a dev server, it is possible that we
// are running it in a mode with a production env, e.g. in E2E tests.
const isInContainer = checkInContainer()
const isProduction = process.env.NODE_ENV === 'production'
const url = require('url')
const path = require('path')
const { chalk } = require('@vue/cli-shared-utils')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const portfinder = require('portfinder')
const prepareURLs = require('@vue/cli-service/lib/util/prepareURLs')
const prepareProxy = require('@vue/cli-service/lib/util/prepareProxy')
const launchEditorMiddleware = require('launch-editor-middleware')
const validateWebpackConfig = require('@vue/cli-service/lib/util/validateWebpackConfig')
const isAbsoluteUrl = require('@vue/cli-service/lib/util/isAbsoluteUrl')
// resolve webpack config
const webpackConfig = api.resolveWebpackConfig()
// check for common config errors
validateWebpackConfig(webpackConfig, api, options)
// load user devServer options with higher priority than devServer
// in webpck config
const projectDevServerOptions = Object.assign(
webpackConfig.devServer || {},
options.devServer
)
// expose advanced stats
if (args.dashboard) {
const DashboardPlugin = require('@vue/cli-service/lib/webpack/DashboardPlugin');
(webpackConfig.plugins = webpackConfig.plugins || []).push(new DashboardPlugin({
type: 'serve'
}))
}
// entry arg
const entry = args._[0]
if (entry) {
webpackConfig.entry = {
app: api.resolve(entry)
}
}
// resolve server options
const useHttps = args.https || projectDevServerOptions.https || defaults.https
const protocol = useHttps ? 'https' : 'http'
const host = args.host || process.env.HOST || projectDevServerOptions.host || defaults.host
portfinder.basePort = args.port || process.env.PORT || projectDevServerOptions.port || defaults
.port
const port = await portfinder.getPortPromise()
const rawPublicUrl = args.public || projectDevServerOptions.public
const publicUrl = rawPublicUrl
? /^[a-zA-Z]+:\/\//.test(rawPublicUrl)
? rawPublicUrl
: `${protocol}://${rawPublicUrl}`
: null
const urls = prepareURLs(
protocol,
host,
port,
isAbsoluteUrl(options.publicPath) ? '/' : options.publicPath
)
const proxySettings = prepareProxy(
projectDevServerOptions.proxy,
api.resolve('public')
)
// inject dev & hot-reload middleware entries
if (!isProduction) {
const sockjsUrl = publicUrl
// explicitly configured via devServer.public
? `?${publicUrl}/sockjs-node`
: isInContainer
// can't infer public netowrk url if inside a container...
// use client-side inference (note this would break with non-root publicPath)
? ''
// otherwise infer the url
: '?' + url.format({
protocol,
port,
hostname: urls.lanUrlForConfig || 'localhost',
pathname: '/sockjs-node'
})
const devClients = [
// dev server client
require.resolve('webpack-dev-server/client') + sockjsUrl,
// hmr client
require.resolve(projectDevServerOptions.hotOnly
? 'webpack/hot/only-dev-server'
: 'webpack/hot/dev-server')
// TODO custom overlay client
// `@vue/cli-overlay/dist/client`
]
if (process.env.APPVEYOR) {
devClients.push('webpack/hot/poll?500')
}
// inject dev/hot client
addDevClientToEntry(webpackConfig, devClients)
}
// create compiler
const compiler = webpack(webpackConfig)
// create server
let server
if (webpack.version[0] > 4) {
server = new WebpackDevServer(Object.assign({
historyApiFallback: {
disableDotRule: true,
rewrites: [{
from: /./,
to: path.posix.join(options.publicPath, 'index.html')
}]
},
hot: !isProduction,
compress: isProduction,
static: {
directory: api.resolve('public'),
publicPath: options.publicPath,
watch: !isProduction,
...projectDevServerOptions.static
},
client: {
logging: 'none',
overlay: isProduction // TODO disable this
? false
: { warnings: false, errors: true },
progress: !process.env.VUE_CLI_TEST,
...projectDevServerOptions.client
}
}, projectDevServerOptions, {
https: useHttps,
proxy: proxySettings,
setupMiddlewares (middlewares, devServer) {
// launch editor support.
// this works with vue-devtools & @vue/cli-overlay
devServer.app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
'To specify an editor, specify the EDITOR env variable or ' +
'add "editor" field to your Vue project config.\n'
)))
// allow other plugins to register middlewares, e.g. PWA
// todo: migrate to the new API interface
api.service.devServerConfigFns.forEach(fn => fn(devServer.app, devServer))
if (projectDevServerOptions.setupMiddlewares) {
return projectDevServerOptions.setupMiddlewares(middlewares, devServer)
}
return middlewares
}
}), compiler)
} else {
server = new WebpackDevServer(compiler, Object.assign({
clientLogLevel: 'none',
historyApiFallback: {
disableDotRule: true,
rewrites: [{
from: /./,
to: path.posix.join(options.publicPath, 'index.html')
}]
},
contentBase: api.resolve('public'),
watchContentBase: !isProduction,
hot: !isProduction,
quiet: true,
compress: isProduction,
publicPath: options.publicPath,
overlay: isProduction // TODO disable this
? false : {
warnings: false,
errors: true
}
}, projectDevServerOptions, {
https: useHttps,
proxy: proxySettings,
before (app, server) {
// launch editor support.
// this works with vue-devtools & @vue/cli-overlay
app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
'To specify an editor, sepcify the EDITOR env variable or ' +
'add "editor" field to your Vue project config.\n'
)))
// allow other plugins to register middlewares, e.g. PWA
api.service.devServerConfigFns.forEach(fn => fn(app, server))
// apply in project middlewares
projectDevServerOptions.before && projectDevServerOptions.before(app,
server)
}
}))
}
;
['SIGINT', 'SIGTERM'].forEach(signal => {
process.on(signal, () => {
server[webpack.version[0] > 4 ? 'stopCallback' : 'close'](() => {
process.exit(0)
})
})
})
// on appveyor, killing the process with SIGTERM causes execa to
// throw error
if (process.env.VUE_CLI_TEST) {
process.stdin.on('data', data => {
if (data.toString() === 'close') {
console.log('got close signal!')
server[webpack.version[0] > 4 ? 'stopCallback' : 'close'](() => {
process.exit(0)
})
}
})
}
return new Promise((resolve, reject) => {
const {
runByHBuilderX
} = require('@dcloudio/uni-cli-shared')
// log instructions & open browser on first compilation complete
let isFirstCompile = true
compiler.hooks.done.tap('vue-cli-service uni-serve', stats => {
if (stats.hasErrors()) {
return
}
let copied = ''
if (isFirstCompile && args.copy) {
require('clipboardy').write(urls.localUrlForBrowser)
copied = chalk.dim('(copied to clipboard)')
}
const networkUrl = publicUrl
? publicUrl.replace(/([^/])$/, '$1/')
: urls.lanUrlForTerminal
const printRunningAt = !runByHBuilderX || (runByHBuilderX && isFirstCompile)
printRunningAt && console.log()
printRunningAt && console.log(' App running at:')
printRunningAt && console.log(
` - Local: ${chalk.cyan(urls.localUrlForTerminal)} ${copied}`
)
if (!printRunningAt) {
console.log('Build complete. Watching for changes...')
}
if (!isInContainer) {
printRunningAt && console.log(` - Network: ${chalk.cyan(networkUrl)}`)
} else {
console.log()
console.log(chalk.yellow(
' It seems you are running Vue CLI inside a container.'
))
if (!publicUrl && options.publicPath && options.publicPath !== '/') {
console.log()
console.log(chalk.yellow(
' Since you are using a non-root publicPath, the hot-reload socket'
))
console.log(chalk.yellow(
' will not be able to infer the correct URL to connect. You should'
))
console.log(chalk.yellow(
` explicitly specify the URL via ${chalk.blue('devServer.public')}.`
))
console.log()
}
console.log(chalk.yellow(
` Access the dev server via ${chalk.cyan(
`${protocol}://localhost:<your container's external mapped port>${options.publicPath}`
)}`
))
}
console.log()
if (isFirstCompile) {
isFirstCompile = false
if (!isProduction) {
// const buildCommand = hasProjectYarn(api.getCwd()) ? `yarn build` : `npm run build`
// console.log(` Note that the development build is not optimized.`)
// console.log(` To create a production build, run ${chalk.cyan(buildCommand)}.`)
} else {
console.log(' App is served in production mode.')
console.log(' Note this is for preview or E2E testing only.')
}
console.log()
if (args.open || projectDevServerOptions.open) {
const pageUri = (projectDevServerOptions.openPage && typeof projectDevServerOptions
.openPage === 'string')
? projectDevServerOptions.openPage
: ''
openBrowser(urls.localUrlForBrowser + pageUri)
}
// Send final app URL
if (args.dashboard) {
const ipc = new IpcMessenger()
ipc.send({
vueServe: {
url: urls.localUrlForBrowser
}
})
}
// resolve returned Promise
// so other commands can do api.service.run('serve').then(...)
resolve({
server,
url: urls.localUrlForBrowser
})
} else if (process.env.VUE_CLI_TEST) {
// signal for test to check HMR
console.log('App updated')
}
})
if (server.showStatus) {
server.showStatus = function () {}
}
if (webpack.version[0] > 4) {
server.start().catch(err => reject(err))
} else {
server.listen(port, host, err => {
if (err) {
reject(err)
}
})
}
})
})
}
function addDevClientToEntry (config, devClient) {
const {
entry
} = config
if (typeof entry === 'object' && !Array.isArray(entry)) {
Object.keys(entry).forEach((key) => {
entry[key] = devClient.concat(entry[key])
})
} else if (typeof entry === 'function') {
config.entry = entry(devClient)
} else {
config.entry = devClient.concat(entry)
}
}
// https://stackoverflow.com/a/20012536
function checkInContainer () {
const fs = require('fs')
if (fs.existsSync('/proc/1/cgroup')) {
const content = fs.readFileSync('/proc/1/cgroup', 'utf-8')
return /:\/(lxc|docker|kubepods)\//.test(content)
}
}
module.exports.defaultModes = {
serve: 'development'
}
+15
View File
@@ -0,0 +1,15 @@
module.exports = {
initAutomator (args) {
const port = args['auto-port'] || process.env.UNI_AUTOMATOR_PORT
if (port) {
const host = args['auto-host'] || process.env.UNI_AUTOMATOR_HOST || '0.0.0.0'
const prepareURLs = require('@vue/cli-service/lib/util/prepareURLs')
const urls = prepareURLs('ws', host, port, '')
if (urls.lanUrlForConfig) {
process.env.UNI_AUTOMATOR_WS_ENDPOINT = 'ws://' + urls.lanUrlForConfig + ':' + port
} else {
process.env.UNI_AUTOMATOR_WS_ENDPOINT = urls.localUrlForBrowser
}
}
}
}
+102
View File
@@ -0,0 +1,102 @@
module.exports = (api, options, rootOptions) => {
const mainVersion = require('./package.json').version
const version = '^' + mainVersion
api.extendPackage(pkg => {
delete pkg.postcss
delete pkg.browserslist
return {
scripts: {
info: 'node node_modules/@dcloudio/vue-cli-plugin-uni/commands/info.js',
serve: 'npm run dev:h5',
build: 'npm run build:h5',
'serve:quickapp-native': 'node node_modules/@dcloudio/uni-quickapp-native/bin/serve.js',
'dev:h5': 'cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-serve',
'dev:mp-qq': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-qq vue-cli-service uni-build --watch',
'dev:mp-weixin': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-weixin vue-cli-service uni-build --watch',
'dev:mp-baidu': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-baidu vue-cli-service uni-build --watch',
'dev:mp-alipay': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-alipay vue-cli-service uni-build --watch',
'dev:mp-toutiao': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-toutiao vue-cli-service uni-build --watch',
'dev:mp-kuaishou': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-kuaishou vue-cli-service uni-build --watch',
'dev:mp-lark': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-lark vue-cli-service uni-build --watch',
'dev:mp-jd': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-jd vue-cli-service uni-build --watch',
'dev:mp-xhs': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-xhs vue-cli-service uni-build --watch',
'dev:mp-harmony': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-harmony vue-cli-service uni-build --watch',
'dev:quickapp-native': 'cross-env NODE_ENV=development UNI_PLATFORM=quickapp-native vue-cli-service uni-build --watch',
'dev:quickapp-webview': 'cross-env NODE_ENV=development UNI_PLATFORM=quickapp-webview vue-cli-service uni-build --watch',
'dev:quickapp-webview-huawei': 'cross-env NODE_ENV=development UNI_PLATFORM=quickapp-webview-huawei vue-cli-service uni-build --watch',
'dev:quickapp-webview-union': 'cross-env NODE_ENV=development UNI_PLATFORM=quickapp-webview-union vue-cli-service uni-build --watch',
'build:h5': 'cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build',
'build:mp-qq': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-qq vue-cli-service uni-build',
'build:mp-weixin': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build',
'build:mp-baidu': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-baidu vue-cli-service uni-build',
'build:mp-alipay': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-alipay vue-cli-service uni-build',
'build:mp-toutiao': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-toutiao vue-cli-service uni-build',
'build:mp-kuaishou': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-kuaishou vue-cli-service uni-build',
'build:mp-lark': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-lark vue-cli-service uni-build',
'build:mp-jd': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-jd vue-cli-service uni-build',
'build:mp-xhs': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-xhs vue-cli-service uni-build',
'build:mp-harmony': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-harmony vue-cli-service uni-build',
'build:quickapp-native': 'cross-env NODE_ENV=production UNI_PLATFORM=quickapp-native vue-cli-service uni-build',
'build:quickapp-webview': 'cross-env NODE_ENV=production UNI_PLATFORM=quickapp-webview vue-cli-service uni-build',
'build:quickapp-webview-huawei': 'cross-env NODE_ENV=production UNI_PLATFORM=quickapp-webview-huawei vue-cli-service uni-build',
'build:quickapp-webview-union': 'cross-env NODE_ENV=production UNI_PLATFORM=quickapp-webview-union vue-cli-service uni-build',
'dev:mp-360': 'cross-env NODE_ENV=development UNI_PLATFORM=mp-360 vue-cli-service uni-build --watch',
'build:mp-360': 'cross-env NODE_ENV=production UNI_PLATFORM=mp-360 vue-cli-service uni-build',
'dev:custom': 'cross-env NODE_ENV=development uniapp-cli custom',
'build:custom': 'cross-env NODE_ENV=production uniapp-cli custom',
'test:h5': 'cross-env UNI_PLATFORM=h5 jest -i',
'test:ios': 'cross-env UNI_PLATFORM=app-plus UNI_OS_NAME=ios jest -i',
'test:android': 'cross-env UNI_PLATFORM=app-plus UNI_OS_NAME=android jest -i',
'test:mp-weixin': 'cross-env UNI_PLATFORM=mp-weixin jest -i',
'test:mp-baidu': 'cross-env UNI_PLATFORM=mp-baidu jest -i'
},
'uni-app': {
scripts: {}
},
dependencies: {
'@dcloudio/uni-app': version,
'@dcloudio/uni-app-plus': version,
'@dcloudio/uni-h5': version,
'@dcloudio/uni-mp-vue': version,
'@dcloudio/uni-mp-qq': version,
'@dcloudio/uni-mp-weixin': version,
'@dcloudio/uni-mp-baidu': version,
'@dcloudio/uni-mp-alipay': version,
'@dcloudio/uni-mp-toutiao': version,
'@dcloudio/uni-mp-lark': version,
'@dcloudio/uni-mp-jd': version,
'@dcloudio/uni-mp-xhs': version,
'@dcloudio/uni-mp-harmony': version,
'@dcloudio/uni-mp-360': version,
'@dcloudio/uni-mp-kuaishou': version,
'@dcloudio/uni-quickapp-native': version,
'@dcloudio/uni-quickapp-webview': version,
'@dcloudio/uni-stat': version,
'@dcloudio/uni-i18n': version,
'@dcloudio/uni-stacktracey': version,
'@vue/shared': '^3.0.0',
flyio: '^0.6.2',
vuex: '^3.2.0'
},
devDependencies: {
'@dcloudio/uni-automator': version,
'@dcloudio/uni-cli-i18n': version,
'@dcloudio/uni-cli-shared': version,
'@dcloudio/uni-migration': version,
'@dcloudio/uni-template-compiler': version,
'@dcloudio/vue-cli-plugin-hbuilderx': version,
'@dcloudio/vue-cli-plugin-uni': version,
'@dcloudio/vue-cli-plugin-uni-optimize': version,
'@dcloudio/webpack-uni-mp-loader': version,
'@dcloudio/webpack-uni-pages-loader': version,
'babel-plugin-import': '^1.11.0',
'cross-env': '^7.0.2',
jest: '^25.4.0'
},
browserslist: [
'Android >= 4.4',
'ios >= 9'
]
}
})
}
+107
View File
@@ -0,0 +1,107 @@
const path = require('path')
const crypto = require('crypto')
/**
* The MD4 algorithm is not available anymore in Node.js 17+ (because of library SSL 3).
* In that case, silently replace MD4 by the MD5 algorithm.
*/
try {
crypto.createHash('md4')
} catch (e) {
// console.warn('Crypto "MD4" is not supported anymore by this Node.js version');
const origCreateHash = crypto.createHash
crypto.createHash = (alg, opts) => {
return origCreateHash(alg === 'md4' ? 'md5' : alg, opts)
}
}
const {
manifestPlatformOptions
} = require('./lib/env')
const {
assetsDir
} = require('./lib/copy-webpack-options')
require('./lib/check-update')()
const initBuildCommand = require('./commands/build')
const initServeCommand = require('./commands/serve')
module.exports = (api, options) => {
initServeCommand(api, options)
initBuildCommand(api, options)
if (process.env.UNI_PLATFORM === 'quickapp-native') {
process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, 'build')
Object.assign(options, {
assetsDir,
parallel: false,
outputDir: process.env.UNI_OUTPUT_DIR
})
require('./lib/options')(options)
const platformOptions = {
webpackConfig: {},
chainWebpack () {}
}
const manifestPlatformOptions = {}
api.configureWebpack(require('./lib/configure-webpack')(platformOptions, manifestPlatformOptions, options, api))
api.chainWebpack(require('./lib/chain-webpack')(platformOptions, options, api))
const vueConfig = require('@dcloudio/uni-quickapp-native/lib/vue.config.js')
api.configureWebpack(vueConfig.configureWebpack)
api.chainWebpack(vueConfig.chainWebpack)
return
}
const type = ['app-plus', 'h5'].includes(process.env.UNI_PLATFORM)
? process.env.UNI_PLATFORM
: 'mp'
const platformOptions = require('./lib/' + type)
let vueConfig = platformOptions.vueConfig
if (typeof vueConfig === 'function') {
vueConfig = vueConfig(options, api)
}
if (options.pages) {
// h5平台 允许 vue.config.js pages 覆盖,其他平台移除 pages 配置
if (process.env.UNI_PLATFORM === 'h5') {
delete vueConfig.pages
} else {
delete options.pages
}
}
Object.assign(options, { // TODO 考虑非 HBuilderX 运行时,可以支持自定义输出目录
outputDir: process.env.UNI_OUTPUT_TMP_DIR || process.env.UNI_OUTPUT_DIR,
assetsDir
}, vueConfig) // 注意,此处目前是覆盖关系,后续考虑改为webpack merge逻辑
require('./lib/options')(options)
api.configureWebpack(require('./lib/configure-webpack')(platformOptions, manifestPlatformOptions, options, api))
api.chainWebpack(require('./lib/chain-webpack')(platformOptions, options, api))
global.uniPlugin.configureWebpack.forEach(configureWebpack => {
api.configureWebpack(function (webpackConfig) {
return configureWebpack(webpackConfig, options)
})
})
global.uniPlugin.chainWebpack.forEach(chainWebpack => {
api.chainWebpack(function (webpackConfig) {
return chainWebpack(webpackConfig, options)
})
})
}
const args = require('minimist')(process.argv.slice(2))
module.exports.defaultModes = {
'uni-serve': args.mode || 'development',
'uni-build': args.mode || process.env.NODE_ENV
}
+41
View File
@@ -0,0 +1,41 @@
'use strict'
module.exports = function (url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {}
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url
var isAbsoluteFile = false
if (typeof url !== 'string') {
if (url.protocol && url.protocol === 'file:' && url.pathname) {
isAbsoluteFile = true
url = url.pathname
} else {
return url
}
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1)
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return '"'.concat(url.replace(/"/g, '\\"').replace(/\n/g, '\\n'), '"')
}
if (isAbsoluteFile) {
return url
}
if (url.indexOf('/') === 0) {
return url.substr(1)
}
return url
}
+296
View File
@@ -0,0 +1,296 @@
const path = require('path')
const webpack = require('webpack')
const {
getMainEntry,
getPlatformStat,
getPlatformPush,
getPlatformUniCloud,
getDevUniConsoleCode
} = require('@dcloudio/uni-cli-shared')
const vueLoader = require('@dcloudio/uni-cli-shared/lib/vue-loader')
const {
getGlobalUsingComponentsCode
} = require('@dcloudio/uni-cli-shared/lib/pages')
const WebpackUniAppPlugin = require('../../packages/webpack-uni-app-loader/plugin/index')
const {
getPartialIdentifier
} = require('../util')
// const {
// createTemplateCacheLoader
// } = require('../cache-loader')
const runtimePath = '@dcloudio/uni-mp-weixin/dist/mp.js'
const wxsPath = '@dcloudio/uni-mp-weixin/dist/wxs.js'
const uniCloudPath = path.resolve(__dirname, '../../packages/uni-cloud/dist/index.js')
const cryptoPath = path.resolve(__dirname, '../crypto.js')
function getProvides (isAppService) {
if (isAppService) {
return { // app-service
__f__: [path.resolve(__dirname, '../format-log.js'), 'default'],
wx: [runtimePath, 'default'],
'wx.nextTick': [runtimePath, 'nextTick'],
Page: [runtimePath, 'Page'],
Component: [runtimePath, 'Component'],
Behavior: [runtimePath, 'Behavior'],
getDate: [wxsPath, 'getDate'],
getRegExp: [wxsPath, 'getRegExp'],
uniCloud: [uniCloudPath, 'uniCloud'],
crypto: [cryptoPath, 'default'],
'window.crypto': [cryptoPath, 'default'],
'global.crypto': [cryptoPath, 'default']
}
}
return { // app-view
__f__: [path.resolve(__dirname, '../format-log.js'), 'default'],
getDate: [wxsPath, 'getDate'],
getRegExp: [wxsPath, 'getRegExp']
}
}
const v3 = {
vueConfig: {
parallel: false
},
webpackConfig (webpackConfig, vueOptions, api) {
const isAppService = !!vueOptions.pluginOptions['uni-app-plus'].service
const isAppView = !!vueOptions.pluginOptions['uni-app-plus'].view
const statCode = getPlatformStat()
const pushCode = getPlatformPush()
const uniCloudCode = getPlatformUniCloud()
const beforeCode = getDevUniConsoleCode() + 'import \'uni-pages\';'
if (!webpackConfig.optimization) {
webpackConfig.optimization = {}
}
// disable noEmitOnErrors
if (webpack.version[0] > 4) {
webpackConfig.optimization.emitOnErrors = true
} else {
webpackConfig.optimization.noEmitOnErrors = false
}
if (isAppService) {
webpackConfig.optimization.runtimeChunk = {
name: 'app-config'
}
webpackConfig.optimization.splitChunks = require('../split-chunks')()
} else if (isAppView) {
webpackConfig.optimization.runtimeChunk = false
webpackConfig.optimization.splitChunks = false
}
const rules = []
const scriptLoaders = []
if (isAppView) {
scriptLoaders.push({
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/view/script')
})
}
scriptLoaders.push({
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/using-components')
})
rules.push({ // 解析组件,css 等
resourceQuery: /vue&type=script/,
use: scriptLoaders
})
// TODO 临时方案,将 wxs 也编译至 service
rules.push({
resourceQuery: [/lang=wxs/, /blockType=wxs/],
use: [{
loader: path.resolve(__dirname, '../../packages/webpack-uni-filter-loader')
}]
})
if (isAppService) {
rules.push({
test: [/\.css$/, /\.p(ost)?css$/, /\.scss$/, /\.sass$/, /\.less$/, /\.styl(us)?$/],
use: [{
loader: path.resolve(__dirname, '../../packages/webpack-uni-app-loader/service/style.js')
}]
})
}
const entry = {}
if (isAppService) {
entry['app-service'] = path.resolve(process.env.UNI_INPUT_DIR, getMainEntry())
} else if (isAppView) {
entry['app-view'] = path.resolve(process.env.UNI_INPUT_DIR, getMainEntry())
}
const plugins = [
new WebpackUniAppPlugin(),
new webpack.ProvidePlugin(getProvides(isAppService))
]
if (isAppService) {
const {
WebpackUTSPlugin
} = require('@dcloudio/uni-cli-shared/lib/uts/uts-webpack-plugin.js')
plugins.push(new WebpackUTSPlugin())
}
return {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
externals: {
vue: 'Vue'
},
entry () {
return entry
},
output: {
filename: '[name].js',
chunkFilename: '[id].js',
// webpack5 use strict
globalObject: webpack.version[0] > 4 ? '(new Function("return this")())' : 'this'
},
performance: {
hints: false
},
resolve: {
extensions: ['.nvue']
},
resolveLoader: {
alias: {
'vue-style-loader': path.resolve(__dirname, '../../packages/app-vue-style-loader')
}
},
module: {
rules: [{
test: path.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
use: [{
loader: isAppService
? path.resolve(__dirname, '../../packages/wrap-loader') : path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/view/main.js'),
options: {
compiler: vueLoader.compiler,
before: [
beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode +
getGlobalUsingComponentsCode()
]
}
}]
},
{
resourceQuery: /vue&type=template/,
use: [{
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/filter-modules-template.js')
}, {
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/page-meta')
}]
},
{
type: 'javascript/auto',
resourceQuery: /uts-proxy/,
use: [{
loader: require.resolve('@dcloudio/uni-cli-shared/lib/uts/uts-loader.js')
}]
},
...rules
// v3 暂不支持 cache
// createTemplateCacheLoader(api,
// isAppService
// ? 'uni-template-compiler-service'
// : 'uni-template-compiler-view'
// )
]
},
plugins
}
},
chainWebpack (webpackConfig, vueOptions, api) {
webpackConfig.entryPoints.delete('app')
const isAppService = !!vueOptions.pluginOptions['uni-app-plus'].service
const isAppView = !!vueOptions.pluginOptions['uni-app-plus'].view
const cacheConfig = {
cacheDirectory: false,
cacheIdentifier: false
}
if (process.env.UNI_USING_CACHE) {
Object.assign(cacheConfig, api.genCacheConfig(
'vue-template-compiler/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
))
}
const compilerOptions = {
preserveWhitespace: false,
service: isAppService,
view: isAppView
}
// disable vue cache-loader
webpackConfig.module
.rule('vue')
.test(vueLoader.test)
.use('vue-loader') // service 层移除 style 节点,view 层返回固定 script
.loader(vueLoader.loader)
.tap(options => Object.assign(options, vueLoader.options({
isAppService,
isAppView
}, compilerOptions), cacheConfig))
.end()
// 是否启用 cache
if (process.env.UNI_USING_CACHE) {
webpackConfig.module
.rule('vue')
.use('cache-loader')
.tap(options => Object.assign(options, api.genCacheConfig(
'vue-loader/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
)))
} else {
webpackConfig.module
.rule('vue')
.uses
.delete('cache-loader')
}
if (isAppView) {
if (process.env.UNI_USING_V3_SCOPED) {
webpackConfig.module
.rule('vue')
.use('uniapp-app-style-scoped')
.loader(path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/view/style'))
}
if (process.env.NODE_ENV === 'production') {
require('../h5/cssnano-options')(webpackConfig)
}
}
if (isAppService) { // service 层移除 css 相关
['css', 'postcss', 'scss', 'sass', 'less', 'stylus'].forEach(cssLang => {
webpackConfig.module.rules.delete(cssLang)
})
}
webpackConfig.plugin('vue-loader').use(require(vueLoader.loader).VueLoaderPlugin)
webpackConfig.plugins.delete('hmr')
webpackConfig.plugins.delete('html')
webpackConfig.plugins.delete('copy')
webpackConfig.plugins.delete('preload')
webpackConfig.plugins.delete('prefetch')
}
}
if (process.env.UNI_USING_V3) {
module.exports = v3
} else {
module.exports = require('../mp')
}
+81
View File
@@ -0,0 +1,81 @@
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const BJSON = require('buffer-json')
const {
getPartialIdentifier
} = require('./util')
const directories = new Set()
function write (key, data, callback) {
const dirname = path.dirname(key)
// template,缓存 mp template
if (
data.remainingRequest.indexOf('vue&type=template') !== -1 &&
process.UNI_CACHE_TEMPLATES
) {
data.mpTemplates = process.UNI_CACHE_TEMPLATES
delete process.UNI_CACHE_TEMPLATES
}
const content = BJSON.stringify(data)
if (directories.has(dirname)) {
// for performance skip creating directory
fs.writeFile(key, content, 'utf-8', callback)
} else {
mkdirp(dirname, (mkdirErr) => {
if (mkdirErr) {
callback(mkdirErr)
return
}
directories.add(dirname)
fs.writeFile(key, content, 'utf-8', callback)
})
}
}
function read (key, callback) {
fs.readFile(key, 'utf-8', (err, content) => {
if (err) {
callback(err)
return
}
try {
const data = BJSON.parse(content)
const mpTemplates = data.mpTemplates
if (mpTemplates) {
Object.keys(mpTemplates).forEach(name => {
fs.writeFileSync(name, mpTemplates[name], 'utf-8')
})
}
callback(null, data)
} catch (e) {
callback(e)
}
})
}
module.exports = {
createTemplateCacheLoader: function (api, id = 'uni-template-compiler') {
return {
resourceQuery: /type=uni-cache-loader-template/,
use: [{
loader: 'cache-loader',
ident: 'uni-cache-loader-template-options',
options: Object.assign(api.genCacheConfig(
id + '/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
), {
read,
write
})
}]
}
}
}
+251
View File
@@ -0,0 +1,251 @@
const path = require('path')
const webpack = require('webpack')
const {
getPartialIdentifier
} = require('./util')
function resolve (dir) {
return path.resolve(__dirname, '..', dir)
}
module.exports = function chainWebpack (platformOptions, vueOptions, api) {
const {
runByHBuilderX, // 使用 HBuilderX 运行
cssPreprocessOptions
} = require('@dcloudio/uni-cli-shared')
return function (webpackConfig) {
// 处理静态资源 limit
const urlLoader = require('@dcloudio/uni-cli-shared/lib/url-loader')
const staticTypes = ['images', 'media', 'fonts']
staticTypes.forEach(staticType => {
const newOptions = urlLoader.options()
if (webpack.version[0] > 4) {
if ('limit' in newOptions) {
webpackConfig.module.rule(staticType).parser({
dataUrlCondition: {
maxSize: newOptions.limit
}
})
}
if (newOptions.fallback && newOptions.fallback.options) {
const generator = {}
const options = newOptions.fallback.options
// const keys = ['publicPath', 'outputPath']
// keys.forEach(key => {
// generator[key] = pathData => {
// const outputPath = oldOptions[key](null, pathData.module.request)
// const basename = path.basename(outputPath)
// return outputPath.substring(0, outputPath.length - basename.length)
// }
// })
generator.filename = pathData => {
return options.name(pathData.module.request)
}
webpackConfig.module.rule(staticType).set('generator', generator)
}
} else {
webpackConfig.module
.rule(staticType)
.use('url-loader')
.loader(urlLoader.loader)
.tap(options => Object.assign(options, newOptions))
}
})
// 条件编译 vue 文件统一直接过滤html,js,css三种类型,单独资源文件引用各自过滤
const loaders = {
scss: 'sass-loader',
sass: 'sass-loader',
less: 'less-loader',
stylus: 'stylus-loader'
}
// 独立css,postcss,scss,sass,less,stylus
const cssLang = ['css', 'postcss', 'scss', 'sass', 'less', 'stylus']
const cssTypes = ['vue-modules', 'vue', 'normal-modules', 'normal']
cssLang.forEach(lang => {
const langRule = webpackConfig.module.rule(lang)
const loader = loaders[lang]
cssTypes.forEach(type => {
if (process.env.UNI_USING_CACHE) {
langRule.oneOf(type)
.use('uniapp-cache-css')
.loader('cache-loader')
.options(api.genCacheConfig(
'css-loader/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
))
.before('css-loader')
}
if (webpack.version[0] > 4) {
langRule.oneOf(type)
.use('css-loader')
.tap(options => {
options.url = {
filter: function (url) {
return url[0] !== '/'
}
}
return options
})
const platformExcludes = ['app-plus', 'h5', 'mp-360']
const platform = process.env.UNI_PLATFORM
if (!platformExcludes.includes(platform)) {
// remove warning https://github.com/vuejs/vue-loader/issues/1742
langRule.oneOf(type)
.use('extract-css-loader')
.tap(options => {
options.esModule = false
// 参考 https://github.com/vuejs/vue-cli/commit/b41ed76c5ce54c618587f24b9d14c35cf31a96d4
// 修复 部分平台 css 内的资源路径不正确,如uni-icons在百度小程序上引用的字体文件路径
options.publicPath = '/'
return options
})
}
} else {
if (langRule.oneOf(type).uses.has('extract-css-loader')) {
langRule.oneOf(type)
.use('extract-css-loader')
.tap(options => {
// 参考 https://github.com/vuejs/vue-cli/commit/b41ed76c5ce54c618587f24b9d14c35cf31a96d4
// 修复 部分平台 css 内的资源路径不正确,如uni-icons在百度小程序上引用的字体文件路径
if (options) options.publicPath = '/'
return options
})
}
}
langRule.oneOf(type)
.use('uniapp-preprocss')
.loader(resolve('packages/webpack-preprocess-loader'))
.options(cssPreprocessOptions)
.after('css-loader') // 在 css-loader 之前条件编译一次
if (loader) { // 在 scss,less,stylus 之前先条件编译一次(似乎没有必要了,保证css-loader处理一次即可,前提是条件编译注释都还存在)
langRule.oneOf(type)
.use('uniapp-preprocss-' + lang)
.loader(resolve('packages/webpack-preprocess-loader'))
.options(cssPreprocessOptions)
.after(loader)
}
})
})
// vue cli 3 and sass-loader 8
cssTypes.forEach(type => {
webpackConfig.module.rule('sass').oneOf(type).use('sass-loader').tap(options => {
if (options.indentedSyntax) {
if (!options.sassOptions) {
options.sassOptions = {}
}
options.sassOptions.indentedSyntax = true
delete options.indentedSyntax
}
return options
})
})
platformOptions.chainWebpack(webpackConfig, vueOptions, api)
// define
const deferredCreated = process.env.UNI_PLATFORM === 'mp-toutiao' ||
process.env.UNI_PLATFORM === 'quickapp-webview' ||
process.env.UNI_PLATFORM === 'mp-harmony'
const defines = {
// UNI_ENV好像没用
__UNI_FEATURE_PROMISE__: JSON.stringify(false),
'process.env.UNI_ENV': JSON.stringify(process.env.UNI_PLATFORM),
'process.env.UNI_APP_ID': JSON.stringify(process.env.UNI_APP_ID),
'process.env.UNI_APP_NAME': JSON.stringify(process.env.UNI_APP_NAME),
'process.env.UNI_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM),
'process.env.UNI_SUB_PLATFORM': JSON.stringify(process.env.UNI_SUB_PLATFORM),
'process.env.UNI_CLOUD_PROVIDER': process.env.UNI_CLOUD_PROVIDER,
'process.env.UNI_SECURE_NETWORK_ENABLE': process.env.UNI_SECURE_NETWORK_ENABLE,
'process.env.UNI_SECURE_NETWORK_CONFIG': process.env.UNI_SECURE_NETWORK_CONFIG || '[]',
'process.env.UNICLOUD_DEBUG': process.env.UNICLOUD_DEBUG,
'process.env.RUN_BY_HBUILDERX': process.env.RUN_BY_HBUILDERX,
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT),
'process.env.UNI_STATISTICS_CONFIG': process.env.UNI_STATISTICS_CONFIG,
'process.env.UNI_STAT_UNI_CLOUD': process.env.UNI_STAT_UNI_CLOUD,
'process.env.UNI_STAT_DEBUG': process.env.UNI_STAT_DEBUG,
'process.env.UNI_COMPILER_VERSION': JSON.stringify(process.env.UNI_COMPILER_VERSION),
'process.env.UNI_APP_VERSION_NAME': JSON.stringify(process.env.UNI_APP_VERSION_NAME),
'process.env.UNI_APP_VERSION_CODE': JSON.stringify(process.env.UNI_APP_VERSION_CODE),
__UNI_SOCKET_HOSTS__: JSON.stringify(process.env.UNI_SOCKET_HOSTS || ''),
__UNI_SOCKET_PORT__: JSON.stringify(process.env.UNI_SOCKET_PORT || ''),
__UNI_SOCKET_ID__: JSON.stringify(process.env.UNI_SOCKET_ID || ''),
__UNI_CONSOLE_KEEP_ORIGINAL__: JSON.stringify(
!(process.env.UNI_PLATFORM === 'mp-harmony' ||
process.env.UNI_PLATFORM === 'app-harmony')
)
}
if (process.env.UNI_USING_VUE3) {
Object.assign(defines, {
__UNI_WX_API__: JSON.stringify(process.env.UNI_USING_WX_API === 'true'),
__UNI_WXS_API__: JSON.stringify(process.env.UNI_USING_WXS_API === 'true'),
__UNI_PROMISE_API__: JSON.stringify(process.env.UNI_USING_PROMISE_API === 'true'),
__VUE_OPTIONS_API__: JSON.stringify(process.env.UNI_USING_VUE3_OPTIONS_API === 'true'),
__VUE_CREATED_DEFERRED__: JSON.stringify(deferredCreated),
__VUE_PROD_DEVTOOLS__: JSON.stringify(false)
})
}
if (process.env.UNI_PLATFORM === 'h5') {
// TODO manifest.json
defines.__UNI_ROUTER_MODE__ = JSON.stringify('hash')
}
if (process.env.UNI_CLOUD_PROVIDER && process.env.NODE_ENV !== 'development') {
webpackConfig.optimization.minimizer('terser').tap((args) => {
// reduce_vars 优化常量
args[0].terserOptions.compress.reduce_vars = true
return args
})
}
webpackConfig
.plugin('uni-define')
.use(require.resolve('webpack/lib/DefinePlugin'), [defines])
if (runByHBuilderX) { // 由 HBuilderX 运行时,移除进度,错误
webpackConfig.plugins.delete('progress')
webpackConfig.plugins.delete('friendly-errors')
} else {
webpackConfig.plugin('friendly-errors')
.tap(args => {
if (global.__error_reporting__) {
args[0].onErrors = function (severity, errors) {
if (severity !== 'error') {
return
}
const error = errors[0]
global.__error_reporting__ && global.__error_reporting__(error.name, error.message || '')
}
}
return args
})
}
if (process.env.BUILD_ENV === 'ali-ide') {
webpackConfig.plugins.delete('progress')
}
// webpack4 support import mjs
if (webpack.version[0] < 5) {
webpackConfig.module
.rule('mjs')
.test(/.mjs$/)
.type('javascript/auto')
}
webpackConfig.resolve.alias
.delete('@')
.set(
'@/pages.json',
path.resolve(process.env.UNI_INPUT_DIR, 'pages.json') +
'?' + JSON.stringify({
type: 'origin-pages-json'
})
)
.set('@', path.resolve(process.env.UNI_INPUT_DIR))
}
}
File diff suppressed because one or more lines are too long
+42
View File
@@ -0,0 +1,42 @@
const path = require('path')
const Service = require('@vue/cli-service')
const {
initCustomScript
} = require('@dcloudio/uni-cli-shared/lib/package')
const uniI18n = require('@dcloudio/uni-cli-i18n')
module.exports = function custom (argv) {
const script = argv._[1]
if (!script) {
console.error(uniI18n.__('pluginUni.pleaseConfigScriptName'))
process.exit(0)
}
const scriptOptions = initCustomScript(script, path.resolve(process.cwd(), 'package.json'))
if (scriptOptions && scriptOptions.title) {
// console.log('>' + scriptOptions.title)
}
// @vue/cli-service/lib/Service.js
const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())
const command = (
process.env.NODE_ENV === 'development' &&
process.env.UNI_PLATFORM === 'h5'
) ? 'uni-serve'
: 'uni-build'
service.run(command, {
watch: process.env.NODE_ENV === 'development',
minimize: process.env.UNI_MINIMIZE === 'true',
clean: false,
subpackage: argv.subpackage,
plugin: argv.plugin,
sourcemap: argv.sourcemap
}).catch(err => {
console.error(err)
process.exit(1)
})
}
+42
View File
@@ -0,0 +1,42 @@
const fs = require('fs')
const path = require('path')
const uniI18n = require('@dcloudio/uni-cli-i18n')
module.exports = async function add (argv) {
const pluginName = argv._[1]
if (!pluginName) {
console.error(uniI18n.__('pluginUni.pleaseSpecifyPluginName'))
process.exit(0)
}
const pluginPkg = require(pluginName + '/package.json')
const options = pluginPkg['uni-app']
if (!options) {
console.error(uniI18n.__('pluginUni.pluginIllegal'))
process.exit(0)
}
const name = options.name
if (!name) {
console.error(uniI18n.__('pluginUni.pluginNameNotExist'))
process.exit(0)
}
const scripts = options.scripts || {
['dev:' + name]: `cross-env NODE_ENV=development UNI_PLATFORM=${name} vue-cli-service uni-build --watch`,
['build:' + name]: `cross-env NODE_ENV=production UNI_PLATFORM=${name} vue-cli-service uni-build`
}
const pkgPath = path.resolve(process.cwd(), 'package.json')
const pkg = require(pkgPath)
if (!pkg.scripts) {
pkg.scripts = {}
}
let changed = false
Object.keys(scripts).forEach(script => {
if (!pkg.scripts[script]) {
changed = true
pkg.scripts[script] = scripts[script]
}
})
if (changed) {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2))
}
}
+410
View File
@@ -0,0 +1,410 @@
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const merge = require('webpack-merge')
const {
getPartialIdentifier
} = require('./util')
function resolve (dir) {
return path.resolve(__dirname, '..', dir)
}
module.exports = function configureWebpack (platformOptions, manifestPlatformOptions, vueOptions, api) {
const {
runByHBuilderX, // 使用 HBuilderX 运行
isInHBuilderX, // 在 HBuilderX 的插件中
hasModule,
jsPreprocessOptions,
htmlPreprocessOptions,
uts
} = require('@dcloudio/uni-cli-shared')
const {
getPlatformVue
} = require('@dcloudio/uni-cli-shared/lib/platform')
const {
getCopyWebpackPluginOptions
} = require('./copy-webpack-options')
function createMatcher (fakeFile) {
return (rule, i) => {
const clone = Object.assign({}, rule)
delete clone.include
if (webpack.version[0] > 4) {
const BasicEffectRulePlugin = require('webpack/lib/rules/BasicEffectRulePlugin')
const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin')
const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler')
const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin')
const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin('test', 'resource'),
new BasicMatcherRulePlugin('include', 'resource'),
new BasicMatcherRulePlugin('exclude', 'resource', true),
new BasicMatcherRulePlugin('resource'),
new BasicMatcherRulePlugin('conditions'),
new BasicMatcherRulePlugin('resourceQuery'),
new BasicMatcherRulePlugin('realResource'),
new BasicMatcherRulePlugin('issuer'),
new BasicMatcherRulePlugin('compiler'),
new BasicEffectRulePlugin('type'),
new BasicEffectRulePlugin('sideEffects'),
new BasicEffectRulePlugin('parser'),
new BasicEffectRulePlugin('resolve'),
new BasicEffectRulePlugin('generator'),
new UseEffectRulePlugin()
])
const ruleSet = ruleSetCompiler.compile([{
rules: [clone]
}])
const rules = ruleSet.exec({
resource: fakeFile
})
return rules.length > 0 && rule.use
} else {
const RuleSet = require('webpack/lib/RuleSet')
const normalized = RuleSet.normalizeRule(clone, {}, '')
return (
!rule.enforce &&
normalized.resource &&
normalized.resource(fakeFile)
)
}
}
}
function updateJsLoader (rawRules, fakeFile, checkLoaderRegex, loader) {
const matchRule = rawRules.find(createMatcher(fakeFile))
const matchUse = matchRule.use
const matchLoaderUseIndex = matchUse.findIndex(u => {
return checkLoaderRegex.test(u.loader)
})
if (matchLoaderUseIndex < 0) {
throw new Error(`No matching use for ${fakeFile}`)
}
matchUse.push(loader)
}
const tsLoaderOptions = require('./util').getTsLoadOptions()
function updateTsLoader (rawRules, fakeFile, loader, appendUTS = false) {
const matchRule = rawRules.find(createMatcher(fakeFile))
if (matchRule && matchRule.use) {
if (isInHBuilderX) {
matchRule.use.forEach(matchUse => {
if (matchUse.loader.includes('ts-loader')) {
Object.assign(matchUse.options, tsLoaderOptions)
if (appendUTS) {
if (!Array.isArray(matchUse.options.appendTsSuffixTo)) {
matchUse.options.appendTsSuffixTo = [matchUse.options.appendTsSuffixTo]
}
matchUse.options.appendTsSuffixTo.push(/\.uts$/)
}
}
})
}
if (appendUTS) {
if (!Array.isArray(matchRule.test)) {
matchRule.test = [matchRule.test]
}
matchRule.test.push(/\.uts$/)
}
matchRule.use.push(loader)
}
}
function removeForkTsCheckerWebpackPlugin (rawPlugins) {
if (isInHBuilderX && hasModule('fork-ts-checker-webpack-plugin')) {
const pluginIndex = rawPlugins.findIndex(rawPlugin => rawPlugin.vue && rawPlugin.typescriptVersion)
if (pluginIndex !== -1) {
// 移除fork-ts-checker-webpack-plugin
rawPlugins.splice(pluginIndex, 1)
// 恢复vue-loader的ts检查
tsLoaderOptions.transpileOnly = false
}
}
}
const babelLoaderRe = /^babel-loader|(\/|\\|@)babel-loader/
const cacheLoaderRe = /^cache-loader|(\/|\\|@)cache-loader/
return function (webpackConfig) {
// disable js cache-loader
const rawRules = webpackConfig.module.rules
for (let i = rawRules.length - 1; i >= 0; i--) {
const uses = rawRules[i].use
if (Array.isArray(uses)) {
const babelLoader = uses.find(use => babelLoaderRe.test(use.loader))
if (babelLoader) {
const options = api.genCacheConfig('babel-loader/' + process.env.UNI_PLATFORM, getPartialIdentifier())
if (webpack.version[0] > 4) {
babelLoader.options = babelLoader.options || {}
Object.assign(babelLoader.options, process.env.UNI_USING_CACHE ? options : {
cacheDirectory: false
})
} else {
const index = uses.findIndex(use => cacheLoaderRe.test(use.loader))
if (index >= 0) {
if (process.env.UNI_USING_CACHE) {
Object.assign(uses[index].options, options)
} else {
uses.splice(index, 1)
}
}
}
}
}
}
// 如果在 HBuilderX 中
removeForkTsCheckerWebpackPlugin(webpackConfig.plugins)
// js preprocess
updateJsLoader(rawRules, 'foo.js', babelLoaderRe, {
loader: resolve('packages/webpack-preprocess-loader'),
options: jsPreprocessOptions
})
// ts options and preprocess
updateTsLoader(rawRules, 'foo.ts', {
loader: resolve('packages/webpack-preprocess-loader'),
options: jsPreprocessOptions
}, true)
updateTsLoader(rawRules, 'foo.tsx', {
loader: resolve('packages/webpack-preprocess-loader'),
options: jsPreprocessOptions
})
let platformWebpackConfig = platformOptions.webpackConfig
if (typeof platformWebpackConfig === 'function') {
platformWebpackConfig = platformWebpackConfig(webpackConfig, vueOptions, api)
}
// 移除 node_modules 目录,避免受路径上的 node_modules 影响
if (require('@dcloudio/uni-cli-shared/lib/util').isInHBuilderX) {
webpackConfig.resolve.modules = webpackConfig.resolve.modules.filter(module => module !== 'node_modules')
}
const plugins = []
const isAppView = process.env.UNI_PLATFORM === 'app-plus' &&
vueOptions.pluginOptions &&
vueOptions.pluginOptions['uni-app-plus'] &&
vueOptions.pluginOptions['uni-app-plus'].view
if (!isAppView) { // app-plus view不需要copy
const patterns = getCopyWebpackPluginOptions(manifestPlatformOptions, vueOptions)
plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? {
patterns
} : patterns))
const uniExtApis = require('@dcloudio/uni-cli-shared/lib/uts/uni_modules')
.parseUniExtApis(false, process.env.UNI_UTS_PLATFORM, 'javascript')
const keys = Object.keys(uniExtApis)
if (keys.length) {
const provides = {}
keys.forEach(name => {
const provide = uniExtApis[name]
if (Array.isArray(provide) && provide.length === 3) {
provide.pop()
}
provides[name] = provide
})
plugins.push(new webpack.ProvidePlugin(provides))
}
}
if (!process.env.UNI_SUBPACKGE || !process.env.UNI_MP_PLUGIN) {
try {
const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json')
const patterns = [{
from: automatorJson,
to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) +
'/.automator.json',
transform (content) {
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return JSON.stringify({
version: require('@dcloudio/uni-automator/package.json').version,
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT
})
}
return ''
}
}]
plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? {
patterns
} : patterns))
} catch (e) {}
}
if (process.UNI_SCRIPT_ENV && Object.keys(process.UNI_SCRIPT_ENV).length) {
// custom define
const envs = Object.create(null)
Object.keys(process.UNI_SCRIPT_ENV).forEach(name => {
envs['process.env.' + name] = JSON.stringify(process.UNI_SCRIPT_ENV[name])
})
plugins.push(new webpack.DefinePlugin(envs))
}
if (runByHBuilderX) { // 使用 HBuilderX 中运行时,调整错误日志输出
const WebpackErrorsPlugin = require('../packages/webpack-errors-plugin')
const onErrors = require('../util/on-errors')
const onWarnings = require('../util/on-warnings')
plugins.push(new WebpackErrorsPlugin({
onErrors,
onWarnings
}))
}
const rules = [{
test: path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'),
use: [{
loader: 'babel-loader'
}, {
loader: '@dcloudio/webpack-uni-pages-loader'
}],
type: 'javascript/auto'
},
{
resourceQuery: /vue&type=template/,
use: [{
loader: resolve('packages/webpack-preprocess-loader'),
options: htmlPreprocessOptions
}]
}
]
if (!process.env.UNI_USING_COMPONENTS) { // 新版本,在 script-loader 中处理(为了避免 babel generator 移除部分条件编译代码)
rules.push({
resourceQuery: /vue&type=script/,
use: [{
loader: resolve('packages/webpack-preprocess-loader'),
options: jsPreprocessOptions
}]
})
}
if (process.env.NODE_ENV === 'development' || (process.env.NODE_ENV === 'production' && process.env
.SOURCEMAP === 'true')) {
const sourceMap = require('@dcloudio/uni-cli-shared/lib/source-map')
let isAppService = false
if (
process.env.UNI_PLATFORM === 'app-plus' &&
vueOptions.pluginOptions &&
vueOptions.pluginOptions['uni-app-plus']
) {
isAppService = !!vueOptions.pluginOptions['uni-app-plus'].service
}
const useEvalSourceMap = process.env.UNI_PLATFORM === 'h5' || isAppService
const useSourceMap = process.env.UNI_PLATFORM.indexOf('mp-') === 0 &&
process.env.UNI_PLATFORM !== 'mp-baidu' &&
process.env.UNI_PLATFORM !== 'mp-alipay' &&
process.env.UNI_PLATFORM !== 'quickapp-webview' &&
process.env.UNI_PLATFORM !== 'mp-harmony' // 目前 ov 的开发工具支持 eval 模式
if (process.env.NODE_ENV === 'production') {
const sourceMapOptions = {
noSources: true,
append: false
}
if (isInHBuilderX && process.env.SOURCEMAP_PATH) {
sourceMapOptions.filename = process.env.SOURCEMAP_PATH
}
if (useEvalSourceMap || useSourceMap) {
plugins.push(sourceMap.createSourceMapDevToolPlugin(!sourceMapOptions.filename, sourceMapOptions))
}
} else {
if (useEvalSourceMap) {
plugins.push(sourceMap.createEvalSourceMapDevToolPlugin())
} else if (useSourceMap) {
plugins.push(sourceMap.createSourceMapDevToolPlugin(process.env.UNI_PLATFORM === 'mp-weixin' || process
.env.UNI_PLATFORM === 'mp-toutiao'))
}
}
}
try {
if (process.env.UNI_HBUILDERX_PLUGINS) {
require(path.resolve(process.env.UNI_HBUILDERX_PLUGINS, 'uni_helpers/lib/bytenode'))
const {
W
} = require(path.resolve(process.env.UNI_HBUILDERX_PLUGINS, 'uni_helpers'))
plugins.push(new W({
dir: process.env.UNI_INPUT_DIR
}))
}
} catch (e) {}
if (!runByHBuilderX && process.env.UNI_PLATFORM === 'mp-weixin') {
const { PreprocessorWebpackPlugin } = require('@dcloudio/uni-cli-shared/lib/preprocessor')
plugins.push(new PreprocessorWebpackPlugin())
}
const resolveLoaderAlias = {}
const modules = ['@vue/cli-plugin-babel', '@vue/cli-service']
modules.forEach(m => {
const {
dependencies
} = require(`${m}/package.json`)
Object.keys(dependencies).forEach(key => {
if (/-loader$/.test(key)) {
resolveLoaderAlias[key] = require.resolve(key)
}
})
})
const alias = {
'@': path.resolve(process.env.UNI_INPUT_DIR),
'./@': path.resolve(process.env
.UNI_INPUT_DIR), // css中的'@/static/logo.png'会被转换成'./@/static/logo.png'加载
vue$: getPlatformVue(vueOptions),
'uni-pages': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'),
'uni-stat-config': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json') +
'?' +
JSON.stringify({
type: 'stat'
}),
vuex: require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex3'),
'@vue/composition-api': require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/composition-api'),
'@dcloudio/uni-console': require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-console/dist/index.esm.js')
}
if (process.env.UNI_PLATFORM.startsWith('mp')) {
const BabelRuntimeVersions = require('@babel/runtime/package.json').version.split('.')
if (BabelRuntimeVersions[0] === '7' && Number(BabelRuntimeVersions[1]) >= 18) {
alias['@babel/runtime/regenerator'] = require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/@babel/runtime/regenerator')
}
}
return merge({
devtool: false,
resolve: {
alias,
modules: [
process.env.UNI_INPUT_DIR,
path.resolve(process.env.UNI_INPUT_DIR, 'node_modules')
],
plugins: [
new uts.UTSResolverPlugin()
]
},
module: {
noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
rules
},
resolveLoader: {
alias: resolveLoaderAlias
},
plugins,
performance: {
assetFilter (assetFilename) {
return !(/\.map$/.test(assetFilename)) && !(/vendor/.test(assetFilename))
}
},
watchOptions: require('./util').getWatchOptions()
}, platformWebpackConfig)
}
}
+177
View File
@@ -0,0 +1,177 @@
const fs = require('fs')
const path = require('path')
const {
compileI18nJsonStr
} = require('@dcloudio/uni-i18n')
const {
normalizePath
} = require('@dcloudio/uni-cli-shared')
const {
initI18nOptions
} = require('@dcloudio/uni-cli-shared/lib/i18n')
const assetsDir = 'static'
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
function getAssetsCopyOption (from, options = {}) {
if (path.isAbsolute(from)) {
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR)
},
options
)
}
}
const to = from
from = path.resolve(process.env.UNI_INPUT_DIR, from)
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, to)
},
options
)
}
}
function addIgnore (ignore, assetsDir, platform, ignoreStatic) {
if (CopyWebpackPluginVersion > 5) {
if (platform === 'app-plus') {
ignore.push(normalizePath(path.resolve(process.env.UNI_INPUT_DIR, assetsDir, 'app/**/*')))
} else if (platform === 'h5') {
ignore.push(normalizePath(path.resolve(process.env.UNI_INPUT_DIR, assetsDir, 'web/**/*')))
}
ignore.push(normalizePath(path.resolve(process.env.UNI_INPUT_DIR, assetsDir, platform + '/**/*')))
} else {
if (platform === 'app-plus') {
ignore.push('app/**/*')
} else if (platform === 'h5') {
ignore.push('web/**/*')
}
ignore.push(platform + '/**/*')
}
if (platform === 'app-plus') {
ignoreStatic.push(['static', 'app'])
} else if (platform === 'h5') {
ignoreStatic.push(['static', 'web'])
}
ignoreStatic.push(['static', platform])
}
let isIgnoreChecked = false
function checkIgnoreStatic (ignoreStatic) {
if (isIgnoreChecked) {
return
}
isIgnoreChecked = true
const existIgnore = new Set()
ignoreStatic.forEach(ignore => {
const dir = path.resolve(process.env.UNI_INPUT_DIR, ...ignore)
if (fs.existsSync(dir)) {
existIgnore.add(ignore.join('/'))
}
})
if (existIgnore.size) {
console.log('已忽略静态资源目录:' + [...existIgnore].join('、') +
'。详见:https://uniapp.dcloud.net.cn/tutorial/platform.html#static')
}
}
// 暂未考虑动态添加static目录
function getAssetsCopyOptions (assetsDir) {
const ignore = []
const ignoreStatic = []
global.uniPlugin.platforms.forEach(platform => {
if (global.uniPlugin.name !== platform) {
addIgnore(ignore, assetsDir, platform, ignoreStatic)
}
})
checkIgnoreStatic(ignoreStatic)
const copyOptions = []
// 主包静态资源
const mainAssetsCopyOption = getAssetsCopyOption(assetsDir, CopyWebpackPluginVersion > 5 ? {
noErrorOnMissing: true,
globOptions: {
ignore
}
} : {
ignore
})
if (mainAssetsCopyOption) {
copyOptions.push(mainAssetsCopyOption)
}
// 分包静态资源
process.UNI_SUBPACKAGES &&
Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption(path.join(root, assetsDir), CopyWebpackPluginVersion > 5 ? {
noErrorOnMissing: true,
globOptions: {
ignore
}
} : {
ignore
})
if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption)
}
})
return copyOptions
}
function getUniModulesAssetsCopyOptions (assetsDir) {
const copyOptions = []
global.uniModules.forEach(module => {
copyOptions.push(
...getAssetsCopyOptions('uni_modules/' + module + '/' + assetsDir)
)
})
return copyOptions
}
function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
const copyOptions = getAssetsCopyOptions(assetsDir).concat(
getUniModulesAssetsCopyOptions(assetsDir)
)
global.uniPlugin.copyWebpackOptions.forEach(copyWebpackOptions => {
const platformCopyOptions =
copyWebpackOptions(platformOptions, vueOptions, copyOptions) || []
platformCopyOptions.forEach(copyOption => {
if (typeof copyOption === 'string') {
copyOption = getAssetsCopyOption(copyOption)
}
copyOption && copyOptions.push(copyOption)
})
})
// 自动化测试时,不启用androidPrivacy.json
if (process.env.UNI_PLATFORM === 'app-plus' && !process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
const fileName = 'androidPrivacy.json'
const context = path.resolve(process.env.UNI_INPUT_DIR)
if (fs.existsSync(path.join(context, fileName))) {
copyOptions.push({
from: fileName,
context,
to: fileName,
transform (content) {
const options = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
true
)
if (!options) {
return content
}
return compileI18nJsonStr(content.toString(), options)
}
})
}
}
return copyOptions
}
module.exports = {
assetsDir,
getCopyWebpackPluginOptions
}
+65
View File
@@ -0,0 +1,65 @@
var lookup = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 62, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
]
function base64Decode (source, target) {
var sourceLength = source.length
var paddingLength = (source[sourceLength - 2] === '=' ? 2 : (source[sourceLength - 1] === '=' ? 1
: 0))
var tmp
var byteIndex = 0
var baseLength = (sourceLength - paddingLength) & 0xfffffffc
for (var i = 0; i < baseLength; i += 4) {
tmp = (lookup[source.charCodeAt(i)] << 18) |
(lookup[source.charCodeAt(i + 1)] << 12) |
(lookup[source.charCodeAt(i + 2)] << 6) |
(lookup[source.charCodeAt(i + 3)])
target[byteIndex++] = (tmp >> 16) & 0xFF
target[byteIndex++] = (tmp >> 8) & 0xFF
target[byteIndex++] = (tmp) & 0xFF
}
if (paddingLength === 1) {
tmp = (lookup[source.charCodeAt(i)] << 10) |
(lookup[source.charCodeAt(i + 1)] << 4) |
(lookup[source.charCodeAt(i + 2)] >> 2)
target[byteIndex++] = (tmp >> 8) & 0xFF
target[byteIndex++] = tmp & 0xFF
}
if (paddingLength === 2) {
tmp = (lookup[source.charCodeAt(i)] << 2) | (lookup[source.charCodeAt(i + 1)] >> 4)
target[byteIndex++] = tmp & 0xFF
}
}
export default {
getRandomValues (arr) {
if (!(
arr instanceof Int8Array ||
arr instanceof Uint8Array ||
arr instanceof Int16Array ||
arr instanceof Uint16Array ||
arr instanceof Int32Array ||
arr instanceof Uint32Array ||
arr instanceof Uint8ClampedArray
)) {
throw new Error('Expected an integer array')
}
if (arr.byteLength > 65536) {
throw new Error('Can only request a maximum of 65536 bytes')
}
var crypto = uni.requireNativePlugin('DCloud-Crypto')
base64Decode(crypto.getRandomValues(arr.byteLength), new Uint8Array(arr.buffer, arr.byteOffset,
arr.byteLength))
return arr
}
}
+679
View File
@@ -0,0 +1,679 @@
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const loaderUtils = require('loader-utils')
const uniI18n = require('@dcloudio/uni-cli-i18n')
const moduleAlias = require('module-alias')
require('./error-reporting')
require('../util/console')
const hasOwnProperty = Object.prototype.hasOwnProperty
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
// 输出编译器版本等信息
const pagesPkg = require('@dcloudio/webpack-uni-pages-loader/package.json')
process.env.UNI_COMPILER_VERSION = ''
if (pagesPkg) {
process.env.UNI_COMPILER_VERSION = pagesPkg['uni-app'].compilerVersion
}
const defaultInputDir = 'src'
if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0) {
process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR)
}
process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), defaultInputDir)
const {
getManifestJson,
isEnableUniPushV1,
isEnableUniPushV2,
isUniPushOffline,
hasPushModule,
isEnableSecureNetwork
} = require('@dcloudio/uni-cli-shared/lib/manifest')
const manifestJsonObj = getManifestJson()
process.env.UNI_APP_ID = manifestJsonObj.appid || ''
process.env.UNI_APP_NAME = manifestJsonObj.name || ''
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
process.env.UNI_APP_VERSION_NAME = manifestJsonObj.versionName
process.env.UNI_APP_VERSION_CODE = manifestJsonObj.versionCode
process.env.VUE_APP_DARK_MODE = (manifestJsonObj[process.env.UNI_PLATFORM] || {}).darkmode || false
// 如果配置了 dart-sass 或者是 Mac Arm 版本
const {
isInHBuilderX
} = require('@dcloudio/uni-cli-shared/lib/util')
if (isInHBuilderX) {
const isMacArm = process.platform === 'darwin' && process.arch === 'arm64'
if (isMacArm && manifestJsonObj.sassImplementationName === 'node-sass') {
console.warn('HBuilderX Mac Arm 版本 manifest.json->sassImplementationName 仅支持 dart-sass')
}
if (manifestJsonObj.sassImplementationName !== 'node-sass' || isMacArm) {
process.env.UNI_SASS_IMPLEMENTATION_NAME = 'dart-sass'
moduleAlias.addAlias('sass', path.resolve(process.env.UNI_HBUILDERX_PLUGINS,
'compile-dart-sass/node_modules/sass'))
}
}
// 小程序 vue3 标记
if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
if (manifestJsonObj.vueVersion === '3' || manifestJsonObj.vueVersion === 3) {
process.env.UNI_USING_VUE3 = true
process.env.UNI_USING_VUE3_OPTIONS_API = true
}
}
// v2 uni-push
if (isEnableUniPushV2(manifestJsonObj, process.env.UNI_PLATFORM)) {
process.env.UNI_PUSH_V2 = true
if (process.env.UNI_PLATFORM === 'app-plus' && isUniPushOffline(manifestJsonObj)) {
process.env.UNI_PUSH_V2_OFFLINE = true
}
} else if (isEnableUniPushV1(manifestJsonObj, process.env.UNI_PLATFORM)) {
process.env.UNI_PUSH_V1 = true
}
if (hasPushModule(manifestJsonObj)) {
process.env.UNI_PUSH_MODULE = true
}
// 初始化全局插件对象
global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init()
const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {}
// 插件校验环境
global.uniPlugin.validate.forEach(validate => {
validate(platformOptions, manifestJsonObj)
})
process.UNI_MANIFEST = manifestJsonObj
process.env.VUE_APP_NAME = manifestJsonObj.name
process.env.UNI_USING_V3_SCOPED = true
// 导出到小程序插件
process.env.UNI_MP_PLUGIN_EXPORT = JSON.stringify(Object.keys(platformOptions.plugins || {}).map(pluginName =>
platformOptions.plugins[pluginName].export))
const isH5 = !process.env.UNI_SUB_PLATFORM && process.env.UNI_PLATFORM === 'h5'
const isProduction = process.env.NODE_ENV === 'production'
// uniCloud
if (!process.env.UNI_CLOUD_PROVIDER && process.env.UNI_CLOUD_SPACES) {
process.env.UNI_CLOUD_PROVIDER = JSON.stringify([])
try {
const spaces = JSON.parse(process.env.UNI_CLOUD_SPACES)
if (Array.isArray(spaces)) {
const hasUniCloudSpace = spaces.length > 0
if (spaces.length === 1) {
const space = spaces[0]
console.log(uniI18n.__('pluginUni.currentProjectDefaultSpaceId', {
0: space.id
}))
}
if (
hasUniCloudSpace &&
isH5 &&
isProduction
) {
console.warn(uniI18n.__('pluginUni.unicloudReleaseH5', {
0: 'https://uniapp.dcloud.net.cn/uniCloud/publish.html#useinh5'
}))
} else if (
hasUniCloudSpace &&
isH5 &&
!isProduction
) {
console.warn(uniI18n.__('pluginUni.unicloudShowedRunByHBuilderX', {
0: 'https://uniapp.dcloud.net.cn/uniCloud/publish.html#useinh5'
}))
}
process.env.UNI_CLOUD_PROVIDER = JSON.stringify(spaces.map(space => {
if (space.provider === 'tcb') {
space.provider = 'tencent'
}
if (!space.provider && space.clientSecret) {
space.provider = 'aliyun'
}
switch (space.provider) {
case 'aliyun':
case 'dcloud':
return {
provider: space.provider || 'aliyun',
spaceName: space.name,
spaceId: space.id,
clientSecret: space.clientSecret,
endpoint: space.apiEndpoint
}
case 'alipay': {
return {
provider: space.provider,
spaceName: space.name,
spaceId: space.id,
spaceAppId: space.spaceAppId,
accessKey: space.accessKey,
secretKey: space.secretKey
}
}
case 'tencent':
default: {
return {
provider: space.provider,
spaceName: space.name,
spaceId: space.id
}
}
}
}))
}
} catch (e) {}
}
// 安全网络
process.env.UNI_SECURE_NETWORK_ENABLE = isEnableSecureNetwork(manifestJsonObj, process.env.UNI_PLATFORM)
// 初始化环境变量
process.env.UNI_CLI_CONTEXT = require('@dcloudio/uni-cli-shared/lib/util').getCLIContext()
const defaultOutputDir = './dist/' +
(process.env.NODE_ENV === 'production' ? 'build' : 'dev') + '/' +
(process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM)
process.env.UNI_OUTPUT_DEFAULT_DIR = path.resolve(process.env.UNI_CLI_CONTEXT, defaultOutputDir)
if (process.env.UNI_OUTPUT_DIR && process.env.UNI_OUTPUT_DIR.indexOf('./') === 0) {
process.env.UNI_OUTPUT_DIR = path.resolve(process.cwd(), process.env.UNI_OUTPUT_DIR)
}
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
process.env.VUE_APP_PLATFORM = process.env.UNI_PLATFORM
process.env.UNI_OUTPUT_DIR = process.env.UNI_OUTPUT_DIR || process.env.UNI_OUTPUT_DEFAULT_DIR
process.env.UNI_APP_X_TSC = 'true'
// if (manifestJsonObj['app-plus']?.['utsCompilerVersion'] === 'v1') {
// process.env.UNI_APP_X_TSC = 'false'
// }
const baseOutDir = path.basename(process.env.UNI_OUTPUT_DIR)
process.env.UNI_APP_X_CACHE_DIR =
process.env.UNI_APP_X_CACHE_DIR ||
path.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + baseOutDir)
process.env.UNI_APP_X_TSC_DIR = path.resolve(
process.env.UNI_OUTPUT_DIR,
'../.tsc'
)
process.env.UNI_APP_X_UVUE_DIR = path.resolve(
process.env.UNI_OUTPUT_DIR,
'../.uvue'
)
process.env.UNI_APP_X_TSC_CACHE_DIR = path.resolve(
process.env.UNI_APP_X_CACHE_DIR,
'tsc'
)
initUtsPlatform()
function initUtsPlatform () {
if (process.env.UNI_APP_PLATFORM === 'android') {
process.env.UNI_UTS_PLATFORM = 'app-android'
}
if (process.env.UNI_APP_PLATFORM === 'ios') {
process.env.UNI_UTS_PLATFORM = 'app-ios'
}
if (process.env.UNI_PLATFORM === 'h5') {
process.env.UNI_UTS_PLATFORM = 'web'
} else {
if (!process.env.UNI_UTS_PLATFORM) {
process.env.UNI_UTS_PLATFORM = process.env.UNI_PLATFORM
}
}
process.env.UNI_UTS_TARGET_LANGUAGE = 'javascript'
if (process.env.UNI_UTS_PLATFORM === 'app-android') {
process.env.UNI_UTS_TARGET_LANGUAGE = 'kotlin'
} else if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
process.env.UNI_UTS_TARGET_LANGUAGE = 'swift'
}
}
if (process.env.UNI_PLATFORM === 'app-plus') {
process.env.UNI_OUTPUT_TMP_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, '../.tmp/app-plus')
}
process.UNI_LIBRARIES = process.UNI_LIBRARIES || ['@dcloudio/uni-ui']
if (process.env.NODE_ENV === 'production') { // 发行模式,不启用 cache
delete process.env.UNI_USING_CACHE
}
process.env.BROWSERSLIST_CONFIG = [
path.resolve(process.env.UNI_INPUT_DIR, '.browserslistrc'),
path.resolve(process.env.UNI_CLI_CONTEXT, 'package.json'),
path.resolve(process.cwd(), 'package.json')
].find(file => fs.existsSync(file))
const {
normalizePath,
isSupportSubPackages,
runByHBuilderX,
getPagesJson
} = require('@dcloudio/uni-cli-shared')
process.env.RUN_BY_HBUILDERX = JSON.stringify(runByHBuilderX)
const {
initUniModules
} = require('@dcloudio/uni-cli-shared/lib/uni_modules')
initUniModules()
const pagesJsonObj = getPagesJson()
// 读取分包
process.UNI_SUBPACKAGES = {}
if (Array.isArray(pagesJsonObj.subPackages)) {
pagesJsonObj.subPackages.forEach(subPackage => {
if (subPackage && subPackage.root) {
const {
name,
root,
independent
} = subPackage
process.UNI_SUBPACKAGES[root] = {
name,
root,
independent
}
}
})
}
process.UNI_PAGES = pagesJsonObj
if (manifestJsonObj.debug) {
process.env.VUE_APP_DEBUG = true
}
process.UNI_STAT_CONFIG = {
appid: manifestJsonObj.appid
}
// 默认启用 自定义组件模式
// if (isInHBuilderXAlpha) {
let usingComponentsAbsent = false
if (!hasOwn(platformOptions, 'usingComponents')) {
usingComponentsAbsent = true
}
platformOptions.usingComponents = true
// }
if (process.env.UNI_PLATFORM === 'h5') {
const optimization = platformOptions.optimization
if (optimization) {
// 发行模式且主动启用优化
const treeShaking = optimization.treeShaking
if (
treeShaking &&
treeShaking.enable &&
process.env.NODE_ENV === 'production'
) {
process.env.UNI_OPT_TREESHAKINGNG = true
process.UNI_USER_APIS = new Set()
if (Array.isArray(treeShaking.modules) && treeShaking.modules.length) {
const {
parseUserApis
} = require('@dcloudio/uni-cli-shared/lib/api')
try {
const modules = require('@dcloudio/uni-h5/lib/modules.json')
process.UNI_USER_APIS = parseUserApis(treeShaking.modules || [], modules)
} catch (e) {}
}
}
if (optimization.prefetch) {
process.env.UNI_OPT_PREFETCH = true
}
if (optimization.preload) {
process.env.UNI_OPT_PRELOAD = true
}
}
const indexCssBuffer = fs.readFileSync(require.resolve('@dcloudio/uni-h5/dist/index.css'))
process.env.VUE_APP_INDEX_CSS_HASH = loaderUtils.getHashDigest(indexCssBuffer, 'md5', 'hex', 8)
let indexDarkCssBuffer = ''
try {
indexDarkCssBuffer = fs.readFileSync(require.resolve('@dcloudio/uni-h5/dist/index.dark.css'))
process.env.VUE_APP_INDEX_DARK_CSS_HASH = loaderUtils.getHashDigest(indexDarkCssBuffer, 'md5', 'hex', 8)
} catch (error) {
process.env.VUE_APP_INDEX_DARK_CSS_HASH = ''
}
}
if (process.env.UNI_PLATFORM === 'mp-qq') { // QQ小程序 强制自定义组件模式
platformOptions.usingComponents = true
}
let isNVueCompiler = true
if (process.env.UNI_PLATFORM === 'app-plus') {
if (platformOptions.nvueCompiler === 'weex') {
isNVueCompiler = false
}
delete process.env.UNI_USING_CACHE
if (platformOptions.renderer === 'native') {
process.env.UNI_USING_V3_NATIVE = true
} else {
process.env.UNI_USING_V3 = true
platformOptions.usingComponents = true
}
process.env.UNI_OUTPUT_TMP_DIR = ''
// isNVueCompiler = true // v3 目前仅支持 uni-app 模式
// v3 支持指定 js 混淆(仅发行模式)
if (
process.env.NODE_ENV === 'production' &&
process.env.UNI_USING_V3
) {
const resources = platformOptions.confusion &&
platformOptions.confusion.resources
const resourcesKeys = resources &&
Object.keys(resources).filter(filepath => path.extname(filepath) === '.js')
if (resourcesKeys && resourcesKeys.length) {
process.UNI_CONFUSION = resourcesKeys.map(filepath =>
normalizePath(path.resolve(process.env.UNI_INPUT_DIR, filepath))
)
}
}
} else { // 其他平台,待确认配置方案
if (
manifestJsonObj['app-plus'] &&
manifestJsonObj['app-plus'].nvueCompiler === 'weex'
) {
isNVueCompiler = false
}
}
if (isNVueCompiler) {
process.env.UNI_USING_NVUE_COMPILER = true
}
if (platformOptions.nvueStyleCompiler === 'uni-app') {
process.env.UNI_USING_NVUE_STYLE_COMPILER = true
} else {
platformOptions.nvueStyleCompiler = 'weex'
}
if (platformOptions.usingComponents === true) {
if (process.env.UNI_PLATFORM !== 'h5') {
process.env.UNI_USING_COMPONENTS = true
}
if (process.env.UNI_PLATFORM === 'app-plus') {
process.env.UNI_USING_V8 = true
}
}
// 兼容历史配置 betterScopedSlots
const modes = ['legacy', 'auto', 'augmented']
const scopedSlotsCompiler = !platformOptions.scopedSlotsCompiler && platformOptions.betterScopedSlots ? modes[2]
: platformOptions.scopedSlotsCompiler
process.env.SCOPED_SLOTS_COMPILER = modes.includes(scopedSlotsCompiler) ? scopedSlotsCompiler : modes[1]
// 快手小程序、小红书小程序 抽象组件编译报错,如未指定 legacy 固定为 augmented 模式
if ((process.env.UNI_PLATFORM === 'mp-kuaishou' || process.env.UNI_PLATFORM === 'mp-xhs') && process.env
.SCOPED_SLOTS_COMPILER !== modes[0]) {
process.env.SCOPED_SLOTS_COMPILER = modes[2]
}
const slotMultipleInstance = !!platformOptions.slotMultipleInstance
// 配置 slotMultipleInstance 时,切换 scopedSlotsCompiler 的值 auto 为 augmented 模式
if (slotMultipleInstance && process.env.SCOPED_SLOTS_COMPILER === modes[1]) {
process.env.SCOPED_SLOTS_COMPILER = modes[2]
}
process.env.SLOT_MULTIPLE_INSTANCE = (slotMultipleInstance).toString()
process.env.MERGE_VIRTUAL_HOST_ATTRIBUTES = (!!platformOptions.mergeVirtualHostAttributes).toString()
process.env.UNI_STATISTICS_CONFIG = '""'
process.env.UNI_STAT_UNI_CLOUD = '""'
process.env.UNI_STAT_DEBUG = '""'
if (
process.env.UNI_USING_COMPONENTS ||
process.env.UNI_PLATFORM === 'h5'
) { // 自定义组件模式或 h5 平台
const uniStatistics = Object.assign(
manifestJsonObj.uniStatistics || {},
platformOptions.uniStatistics || {}
)
if (uniStatistics.enable === true) {
const uniStatLog = (text) => {
console.log()
console.warn(text)
console.log()
}
const version = Number(uniStatistics.version) === 2 ? '2' : '1'
process.env.UNI_USING_STAT = version
// 获取服务空间配置信息
const uniCloudConfig = uniStatistics.uniCloud || {}
process.env.UNI_STATISTICS_CONFIG = JSON.stringify(uniStatistics)
process.env.UNI_STAT_UNI_CLOUD = JSON.stringify(uniCloudConfig)
process.env.UNI_STAT_DEBUG = uniStatistics.debug === true ? 'true' : 'false'
if (process.env.NODE_ENV === 'production') {
if (!process.UNI_STAT_CONFIG.appid) {
uniStatLog(uniI18n.__('pluginUni.uniStatisticsNoAppid', {
0: 'https://ask.dcloud.net.cn/article/36303'
}))
} else {
if (!uniStatistics.version) {
uniStatLog(uniI18n.__('pluginUni.uniStatisticsNoVersion', {
0: 'https://uniapp.dcloud.io/uni-stat-v2.html'
}))
} else {
uniStatLog(`已开启 uni统计${uniStatistics.version}.0 版本`)
if (version === '2') {
uniStatLog(
'【重要】因 HBuilderX 3.4.9 版本起,uni统计2.0 调整了安卓端 deviceId 获取方式,导致 uni统计2.0 App-Android平台部分统计数据不准确。如使用了HBuilderX 3.4.9 - 3.6.4版本且开通了uni统计2.0的应用,需要使用HBuilderX3.6.7及以上版本重新发布应用并升级 uniAdmin 云函数解决,详见:https://ask.dcloud.net.cn/article/40097'
)
}
}
}
} else {
if (!uniStatistics.version) {
uniStatLog(uniI18n.__('pluginUni.uniStatisticsNoVersion', {
0: 'https://uniapp.dcloud.io/uni-stat-v2.html'
}))
} else {
uniStatLog(`已开启 uni统计${uniStatistics.version}.0 版本`)
if (version === '2') {
uniStatLog(
'【重要】因 HBuilderX 3.4.9 版本起,uni统计2.0 调整了安卓端 deviceId 获取方式,导致 uni统计2.0 App-Android平台部分统计数据不准确。如使用了HBuilderX 3.4.9 - 3.6.4版本且开通了uni统计2.0的应用,需要使用HBuilderX3.6.7及以上版本重新发布应用并升级 uniAdmin 云函数解决,详见:https://ask.dcloud.net.cn/article/40097'
)
}
}
}
}
}
if (process.env.UNI_USING_COMPONENTS) { // 是否启用分包优化
if (platformOptions.optimization) {
if (
isSupportSubPackages() &&
platformOptions.optimization.subPackages &&
Object.keys(process.UNI_SUBPACKAGES).length
) {
process.env.UNI_OPT_SUBPACKAGES = true
}
}
}
const warningMsg =
usingComponentsAbsent
? '该应用之前可能是非自定义组件模式,目前以自定义组件模式运行。非自定义组件已于2019年11月1日起停止支持。详见:https://ask.dcloud.net.cn/article/36385'
: 'uni-app已于2019年11月1日起停止支持非自定义组件模式 [详情](https://ask.dcloud.net.cn/article/36385)'
const needWarning = !platformOptions.usingComponents || usingComponentsAbsent
let hasNVue = false
const compileModeUrl = 'https://ask.dcloud.net.cn/article/36074'
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
const compileMode = (process.env.UNI_USING_V3_NATIVE ? 'v3' : '') + '' + (isNVueCompiler ? 'uni-app' : 'weex')
console.log(uniI18n.__('pluginUni.nvueCompileModeForDetail', {
0: compileMode,
1: compileModeUrl
}))
} else if (process.env.UNI_PLATFORM !== 'h5' && process.env.UNI_PLATFORM !== 'quickapp-native') {
try {
const info = process.env.UNI_COMPILER_VERSION
if (process.env.UNI_PLATFORM === 'app-plus') {
if (process.env.UNI_USING_V3) {
console.log(info)
} else {
const glob = require('glob')
hasNVue = !!glob.sync('pages/**/*.nvue', {
cwd: process.env.UNI_INPUT_DIR
}).length
if (hasNVue) {
console.log(info)
if (needWarning) {
console.log(warningMsg)
}
console.log(uniI18n.__('pluginUni.nvueCompileModeForDetail', {
0: (isNVueCompiler ? 'uni-app' : 'weex'),
1: compileModeUrl
}))
} else {
console.log(info)
if (needWarning) {
console.log(warningMsg)
}
}
}
} else {
if (needWarning) {
console.log(warningMsg)
}
}
} catch (e) {}
}
if (process.env.NODE_ENV !== 'production') { // 运行模式性能提示
let perfMsg = uniI18n.__('pluginUni.runDebugMode')
if (hasNVue) { // app-nvue
perfMsg = perfMsg + uniI18n.__('pluginUni.runDebugModeNvue')
} else if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) { // 小程序
perfMsg = perfMsg + uniI18n.__('pluginUni.runDebugModeMP')
}
console.log(perfMsg)
}
// 将 template-compiler 指向修订后的版本
moduleAlias.addAlias('vue-template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/vue-template-compiler')
moduleAlias.addAlias('@megalo/template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/@megalo/template-compiler')
moduleAlias.addAlias('mpvue-template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/mpvue-template-compiler')
// vue-loader
moduleAlias.addAlias('vue-loader', '@dcloudio/vue-cli-plugin-uni/packages/vue-loader')
// sass-loader
moduleAlias.addAlias('sass-loader', '@dcloudio/vue-cli-plugin-uni/packages/sass-loader')
if (process.env.UNI_USING_V3 && process.env.UNI_PLATFORM === 'app-plus') {
moduleAlias.addAlias('./runtime/getUrl.js', '@dcloudio/vue-cli-plugin-uni/lib/app-plus/getUrl.js')
moduleAlias.addAlias('../runtime/getUrl.js', '@dcloudio/vue-cli-plugin-uni/lib/app-plus/getUrl.js')
moduleAlias.addAlias('vue-style-loader', '@dcloudio/vue-cli-plugin-uni/packages/app-vue-style-loader')
}
if (process.env.UNI_PLATFORM === 'h5') {
moduleAlias.addAlias('vue-style-loader', '@dcloudio/vue-cli-plugin-uni/packages/h5-vue-style-loader')
}
if (process.env.UNI_PLATFORM === 'mp-toutiao' || process.env.UNI_PLATFORM === 'mp-lark') {
// !important 始终带有一个空格
moduleAlias.addAlias(
'postcss-normalize-whitespace',
'@dcloudio/vue-cli-plugin-uni/packages/postcss-normalize-whitespace'
)
}
if (runByHBuilderX) {
const oldError = console.error
console.error = function (msg) {
if (typeof msg === 'string' && msg.includes(
'[BABEL] Note: The code generator has deoptimised the styling of')) {
const filePath = msg.replace('[BABEL] Note: The code generator has deoptimised the styling of ', '').split(
' as ')[0]
console.log('[' + uniI18n.__('warning') + '] `' + path.relative(process.env.UNI_INPUT_DIR, filePath) +
'` 文件体积超过 500KB,已跳过压缩以及 ES6 转 ES5 的处理,手机端使用过大的js库影响性能。')
} else {
oldError.apply(console, arguments)
// TODO 如果是首次运行遇到错误直接退出
}
}
}
if (
process.env.UNI_USING_CACHE &&
process.env.UNI_PLATFORM !== 'h5' &&
!process.env.UNI_USING_V3 &&
!process.env.UNI_USING_NATIVE &&
!process.env.UNI_USING_V3_NATIVE
) { // 使用 cache, 拷贝 cache 的 json
const cacheJsonDir = path.resolve(
process.env.UNI_CLI_CONTEXT,
'node_modules/.cache/uni-pages-loader/' + process.env.UNI_PLATFORM
)
if (!fs.existsSync(cacheJsonDir)) { // 创建 cache 目录
mkdirp(cacheJsonDir)
} else {
require('@dcloudio/uni-cli-shared/lib/cache').restore()
}
}
const {
initAutoImportComponents,
initAutoImportScanComponents
} = require('@dcloudio/uni-cli-shared/lib/pages')
process.UNI_AUTO_SCAN_COMPONENTS = !(pagesJsonObj.easycom && pagesJsonObj.easycom.autoscan === false)
initAutoImportComponents(pagesJsonObj.easycom)
if (process.UNI_AUTO_SCAN_COMPONENTS) {
initAutoImportScanComponents()
}
global.uniPlugin.configureEnv.forEach(configureEnv => {
configureEnv()
})
if (
process.env.UNI_PLATFORM === 'h5' ||
(
process.env.UNI_PLATFORM === 'app-plus' &&
process.env.UNI_USING_V3
)
) {
const migrate = require('@dcloudio/uni-migration')
const wxcomponentDirs = [path.resolve(process.env.UNI_INPUT_DIR, 'wxcomponents')]
global.uniModules.forEach(module => {
wxcomponentDirs.push(path.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', module, 'wxcomponents'))
})
wxcomponentDirs.forEach(wxcomponentsDir => {
if (fs.existsSync(wxcomponentsDir)) { // 转换 mp-weixin 小程序组件
try {
migrate(wxcomponentsDir, false, {
silent: true // 不输出日志
})
} catch (err) {
console.warn(err)
}
}
})
}
if (process.env.UNI_PLATFORM.startsWith('mp-')) {
console.log(uniI18n.__('pluginUni.mpBrowserKernelDifference', {
0: 'https://uniapp.dcloud.io/matter?id=mp'
}))
}
runByHBuilderX && console.log(uniI18n.__('compiling'))
module.exports = {
manifestPlatformOptions: platformOptions
}
+162
View File
@@ -0,0 +1,162 @@
const {
pathToRegexp,
isInHBuilderX
} = require('@dcloudio/uni-cli-shared/lib/util')
const plp = require('@dcloudio/webpack-uni-pages-loader/package.json')
class ErrorReport {
static get instance () {
if (this._instance == null) {
this._instance = new ErrorReport()
}
return this._instance
}
constructor () {
this._instance = null
this._os = null
this._https = null
this._crypto = null
this._cacheList = []
this._UNI_INPUT_DIR_REG = pathToRegexp(process.env.UNI_INPUT_DIR, { global: true })
this._UNI_CLI_CONTEXT_REG = pathToRegexp(process.env.UNI_CLI_CONTEXT, { global: true })
}
get os () {
if (this._os == null) {
this._os = require('os')
}
return this._os
}
get https () {
if (this._https == null) {
this._https = require('https')
}
return this._https
}
report (type, err = '') {
if (!this._shouldReport(err)) {
return
}
if (typeof err === 'object') {
try {
err = err.toString()
} catch (e) {}
}
err = err.replace(this._UNI_INPUT_DIR_REG, 'UNI_INPUT_DIR')
err = err.replace(this._UNI_CLI_CONTEXT_REG, 'UNI_CLI_CONTEXT')
const data = JSON.stringify({
di: this._getMD5(this._getMac()),
np: process.platform,
nv: process.version,
cp: process.env.UNI_PLATFORM,
cv: plp['uni-app'].compilerVersion,
hx: isInHBuilderX ? 1 : 0,
et: type,
em: err
})
var hash = this._getMD5(data)
if (this._cacheList.includes(hash)) {
return
}
this._cacheList.push(hash)
setTimeout(() => {
this._doReport(data)
}, 10)
}
_doReport (data) {
const req = this.https.request({
hostname: this.HOST,
port: 443,
path: this.PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
})
req.write(data)
req.end()
}
_shouldReport (err = '') {
try {
const errMsg = err.toString()
const errorIndex = this.EXCLUDE_ERROR_LIST.findIndex(item => errMsg.includes(item))
if (errorIndex >= 0) {
return false
}
// 目前简单的上报逻辑为:错误信息中包含@dcloudio包名
if (
errMsg.includes('@dcloudio') &&
!errMsg.includes('Errors compiling template')
) {
return true
}
} catch (e) {}
return false
}
_getMD5 (str) {
return this.crypto.createHash('md5').update(str).digest('hex')
}
_getMac () {
let mac
const network = this.os.networkInterfaces()
for (const key in network) {
const array = network[key]
for (let i = 0; i < array.length; i++) {
const item = array[i]
if (!item.family || (item.mac && item.mac === '00:00:00:00:00:00')) {
continue
}
if (item.family === 'IPv4' || item.family === 'IPv6') {
mac = item.mac
break
}
}
}
return mac
}
get crypto () {
if (this._crypto == null) {
this._crypto = require('crypto')
}
return this._crypto
}
}
Object.assign(ErrorReport.prototype, {
HOST: '96f0e031-f37a-48ef-84c7-2023f6360c0a.bspapp.com',
PATH: '/http/uni-app-compiler',
EXCLUDE_ERROR_LIST: ['uni-app-compiler', 'Error: ENOENT: no such file or directory']
})
function report (type, err) {
// ErrorReport.instance.report(type, err)
}
global.__error_reporting__ = report
process
.on('unhandledRejection', (reason, p) => {
console.log(reason)
// global.__error_reporting__ && global.__error_reporting__('unhandledRejection', reason)
})
.on('uncaughtException', err => {
console.log(err)
// global.__error_reporting__ && global.__error_reporting__('uncaughtException', err.stack)
})
+80
View File
@@ -0,0 +1,80 @@
function typof (v) {
var s = Object.prototype.toString.call(v)
return s.substring(8, s.length - 1)
}
function isDebugMode () {
/* eslint-disable no-undef */
return typeof __channelId__ === 'string' && __channelId__
}
function jsonStringifyReplacer (k, p) {
switch (typof(p)) {
case 'Function':
return 'function() { [native code] }'
default :
return p
}
}
export function log (type) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key]
}
console[type].apply(console, args)
}
export default function formatLog () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key]
}
var type = args.shift()
if (isDebugMode()) {
args.push(args.pop().replace('at ', 'uni-app:///'))
return console[type].apply(console, args)
}
var msgs = args.map(function (v) {
var type = Object.prototype.toString.call(v).toLowerCase()
if (type === '[object object]' || type === '[object array]') {
try {
v = '---BEGIN:JSON---' + JSON.stringify(v, jsonStringifyReplacer) + '---END:JSON---'
} catch (e) {
v = type
}
} else {
if (v === null) {
v = '---NULL---'
} else if (v === undefined) {
v = '---UNDEFINED---'
} else {
var vType = typof(v).toUpperCase()
if (vType === 'NUMBER' || vType === 'BOOLEAN') {
v = '---BEGIN:' + vType + '---' + v + '---END:' + vType + '---'
} else {
v = String(v)
}
}
}
return v
})
var msg = ''
if (msgs.length > 1) {
var lastMsg = msgs.pop()
msg = msgs.join('---COMMA---')
if (lastMsg.indexOf(' at ') === 0) {
msg += lastMsg
} else {
msg += '---COMMA---' + lastMsg
}
} else {
msg = msgs[0]
}
console[type](msg)
}
+188
View File
@@ -0,0 +1,188 @@
var validDivisionCharRE = /[\w).+\-_$\]]/
function parseFilters (exp) {
var inSingle = false
var inDouble = false
var inTemplateString = false
var inRegex = false
var curly = 0
var square = 0
var paren = 0
var lastFilterIndex = 0
var c, prev, i, expression, filters
for (i = 0; i < exp.length; i++) {
prev = c
c = exp.charCodeAt(i)
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) {
inSingle = false
}
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) {
inDouble = false
}
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) {
inTemplateString = false
}
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) {
inRegex = false
}
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1
expression = exp.slice(0, i).trim()
} else {
pushFilter()
}
} else {
switch (c) {
case 0x22:
inDouble = true
break // "
case 0x27:
inSingle = true
break // '
case 0x60:
inTemplateString = true
break // `
case 0x28:
paren++
break // (
case 0x29:
paren--
break // )
case 0x5B:
square++
break // [
case 0x5D:
square--
break // ]
case 0x7B:
curly++
break // {
case 0x7D:
curly--
break // }
}
if (c === 0x2f) { // /
var j = i - 1
/* eslint-disable no-void */
var p = (void 0)
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j)
if (p !== ' ') {
break
}
}
if (!p || !validDivisionCharRE.test(p)) {
inRegex = true
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim()
} else if (lastFilterIndex !== 0) {
pushFilter()
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim())
lastFilterIndex = i + 1
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i])
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(')
if (i < 0) {
// _f: resolveFilter
return ('_f("' + filter + '")(' + exp + ')')
} else {
var name = filter.slice(0, i)
var args = filter.slice(i + 1)
return ('_f("' + name + '")(' + exp + (args !== ')' ? ',' + args : args))
}
}
const defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g
function parseText (
text
) {
const tokens = []
const rawTokens = []
let lastIndex = defaultTagRE.lastIndex = 0
let match, index, tokenValue
while ((match = defaultTagRE.exec(text))) {
index = match.index
// push text token
if (index > lastIndex) {
rawTokens.push(tokenValue = text.slice(lastIndex, index))
tokens.push(JSON.stringify(tokenValue))
}
// tag token
var exp = parseFilters(match[1].trim())
tokens.push(('_s(' + exp + ')'))
rawTokens.push({
'@binding': exp
})
lastIndex = index + match[0].length
}
if (lastIndex < text.length) {
rawTokens.push(tokenValue = text.slice(lastIndex))
tokens.push(JSON.stringify(tokenValue))
}
return {
expression: tokens.join('+'),
tokens: rawTokens
}
}
module.exports = {
postTransformNode (el) { // 重新格式化 text 节点,应该使用postTransformNode,但 mpvue 使用的 template-compiler 较老,导致 postTransformNode 时机不对
const children = el.children
if (children && children.length) {
children.forEach(childEl => {
if (childEl.text) {
const text = childEl.text.trim()
if (childEl.type === 2) {
try {
const {
expression,
tokens
} = parseText(text)
childEl.expression = expression
childEl.tokens = tokens
childEl.text = text
} catch (e) {
console.log(e)
}
} else {
childEl.text = text
}
}
})
}
return ''
}
}
+9
View File
@@ -0,0 +1,9 @@
(function () {
var userAgent = navigator.userAgent
window.addEventListener('resize', function () {
if (navigator.userAgent !== userAgent) {
/* eslint-disable no-undef */
location.reload()
}
})
})()
+119
View File
@@ -0,0 +1,119 @@
const {
tags
} = require('@dcloudio/uni-cli-shared')
const parser = require('@babel/parser')
const t = require('@babel/types')
const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/
function isFunction (expr) {
try {
const body = parser.parse(`(${expr})`).program.body[0]
const expression = body.expression
return t.isFunctionDeclaration(body) || t.isArrowFunctionExpression(expression) || t.isFunctionExpression(
expression)
} catch (error) {}
}
function processEvent (expr, filterModules) {
const isMethodPath = simplePathRE.test(expr)
if (isMethodPath || isFunction(expr)) {
if (filterModules.find(name => expr.indexOf(name + '.') === 0)) {
return `
$event = $handleWxsEvent($event);
(${expr})($event, $getComponentDescriptor())
`
} else {
expr = `(${expr})(...arguments)`
}
}
return `
arguments[0] = $event = $handleEvent($event);
${expr}
`
}
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
const deprecated = {
events: {
tap: 'click',
longtap: 'longpress'
}
}
function addTag (tag) {
if (!process.UNI_TAGS) {
process.UNI_TAGS = new Set()
}
process.UNI_TAGS.add(tag)
}
module.exports = {
h5: true,
modules: [require('../format-text'), {
preTransformNode (el, options) {
if (el.tag.indexOf('v-uni-') === 0) {
addTag(el.tag.replace('v-uni-', ''))
} else if (hasOwn(tags, el.tag)) {
addTag(el.tag)
el.tag = 'v-uni-' + el.tag
}
},
postTransformNode (el, {
warn,
filterModules
}) {
if (el.tag === 'block') {
el.tag = 'template'
const vForKey = el.key
if (vForKey) {
delete el.key
el.children.forEach((childEl, index) => {
const childVForKey = childEl.key
if (childVForKey) {
childEl.key = `${childVForKey}+'_'+${vForKey}+'_${index}'`
} else {
childEl.key = `${vForKey}+'_${index}'`
}
})
}
}
if (el.events || el.nativeEvents) {
filterModules = filterModules || []
const {
events: eventsMap
} = deprecated
// const warnLogs = new Set()
normalizeEvent(el.events, eventsMap, filterModules)
normalizeEvent(el.nativeEvents, eventsMap, filterModules)
}
}
}]
}
function normalizeEvent (events, eventsMap, filterModules) {
if (!events) {
return
}
Object.keys(events).forEach(name => {
// 过时事件类型转换
if (eventsMap[name]) {
events[eventsMap[name]] = events[name]
delete events[name]
// warnLogs.add(`警告:事件${name}已过时,推荐使用${eventsMap[name]}代替`)
name = eventsMap[name]
}
const handlers = events[name]
if (Array.isArray(handlers)) {
handlers.forEach(handler => {
handler.value = processEvent(handler.value, filterModules)
})
} else {
handlers.value = processEvent(handlers.value, filterModules)
}
})
}
+61
View File
@@ -0,0 +1,61 @@
const {
getPlatformCssnano
} = require('@dcloudio/uni-cli-shared')
const webpack = require('webpack')
module.exports = function initCssnanoOptions (webpackConfig) {
const module = webpackConfig.module
// TODO 临时 hack calc:false 看看 vue cli 后续是否开放 cssnano 的配置
const cssnanoOptions = {
sourceMap: false
}
const plugins = [require('cssnano')({
preset: ['default', getPlatformCssnano()]
})]
// TODO postcss-loader version > 4
if (webpack.version[0] > 4) {
cssnanoOptions.postcssOptions = { plugins }
} else {
cssnanoOptions.plugins = plugins
}
module.rule('css').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('css').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('css').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('css').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('postcss').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('postcss').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('postcss').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('postcss').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('scss').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('scss').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('scss').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('scss').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('sass').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('sass').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('sass').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('sass').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('less').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('less').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('less').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('less').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('stylus').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('stylus').oneOf('vue').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
module.rule('stylus').oneOf('normal-modules').use('cssnano').loader('postcss-loader').options(
cssnanoOptions)
module.rule('stylus').oneOf('normal').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
}
+198
View File
@@ -0,0 +1,198 @@
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const {
getMainEntry,
getH5Options,
getPlatformStat,
getPlatformPush,
getPlatformUniCloud,
getDevUniConsoleCode
} = require('@dcloudio/uni-cli-shared')
const {
getGlobalUsingComponentsCode
} = require('@dcloudio/uni-cli-shared/lib/pages')
const modifyVueLoader = require('../vue-loader')
const WebpackHtmlAppendPlugin = require('../../packages/webpack-html-append-plugin')
const WebpackUniAppPlugin = require('../../packages/webpack-uni-app-loader/plugin/index')
function resolve (dir) {
return path.resolve(__dirname, '../../', dir)
}
const {
title,
publicPath,
template,
devServer
} = getH5Options()
const runtimePath = '@dcloudio/uni-mp-weixin/dist/mp.js'
const wxsPath = '@dcloudio/uni-mp-weixin/dist/wxs.js'
const uniCloudPath = path.resolve(__dirname, '../../packages/uni-cloud/dist/index.js')
function getProvides () {
return {
__f__: [path.resolve(__dirname, '../format-log.js'), 'log'],
uniCloud: [uniCloudPath, 'uniCloud'],
'wx.nextTick': [runtimePath, 'nextTick'],
Page: [runtimePath, 'Page'],
Component: [runtimePath, 'Component'],
Behavior: [runtimePath, 'Behavior'],
getDate: [wxsPath, 'getDate'],
getRegExp: [wxsPath, 'getRegExp']
}
}
const plugins = [
new WebpackUniAppPlugin(),
new webpack.ProvidePlugin(getProvides())
]
if (process.env.NODE_ENV !== 'production') {
plugins.push(new WebpackHtmlAppendPlugin(
`
<script>
${fs.readFileSync(path.resolve(__dirname, './auto-reload.js'), 'utf8')}
</script>
`
))
}
const vueConfig = {
parallel: false, // 因为传入了自定义 compiler,避免参数丢失,禁用parallel
publicPath,
pages: {
index: {
// page 的入口
entry: path.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
// 模板来源
template,
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title,
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ['chunk-vendors', 'chunk-common', 'index'],
baseUrl: publicPath
}
}
}
if (devServer && Object.keys(devServer).length) {
vueConfig.devServer = devServer
}
module.exports = {
vueConfig,
webpackConfig (webpackConfig) {
let useBuiltIns = 'usage'
const statCode = getPlatformStat()
const pushCode = getPlatformPush()
const uniCloudCode = getPlatformUniCloud()
try {
const babelConfig = require(path.resolve(process.env.UNI_CLI_CONTEXT, 'babel.config.js'))
useBuiltIns = babelConfig.presets[0][1].useBuiltIns
} catch (e) {}
const beforeCode = (useBuiltIns === 'entry' ? 'import \'@babel/polyfill\';' : '') +
getDevUniConsoleCode() + `import 'uni-pages';import 'uni-${process.env.UNI_PLATFORM}';`
return {
resolve: {
extensions: ['.uts', '.nvue'],
alias: {
'vue-router': resolve('packages/h5-vue-router'),
'uni-h5': require.resolve('@dcloudio/uni-h5')
}
},
module: {
rules: [{
test: path.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
use: [{
loader: path.resolve(__dirname, '../../packages/wrap-loader'),
options: {
before: [
beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode +
getGlobalUsingComponentsCode()
]
}
}]
}, {
test: /App\.vue$/,
use: {
loader: path.resolve(__dirname, '../../packages/wrap-loader'),
options: {
before: ['<template><App :keepAliveInclude="keepAliveInclude"/></template>']
}
}
}, { // 解析组件,css 等
resourceQuery: /vue&type=script/,
use: [{
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/using-components')
}]
}, {
resourceQuery: /vue&type=template/,
use: [{
loader: resolve('packages/webpack-uni-app-loader/filter-modules-template.js')
}, {
loader: '@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta'
}]
}, {
resourceQuery: [/lang=wxs/, /blockType=wxs/],
use: [{
loader: resolve('packages/webpack-uni-filter-loader')
}]
}]
},
resolveLoader: {
alias: {
'vue-style-loader': resolve('packages/h5-vue-style-loader')
}
},
plugins,
optimization: {
moduleIds: webpack.version[0] > 4 ? 'deterministic' : 'hashed'
},
devServer: webpack.version[0] > 4 ? {
watchFiles: {
options: require('../util').getWatchOptions()
}
} : {
watchOptions: require('../util').getWatchOptions()
}
}
},
chainWebpack (webpackConfig, vueOptions, api) {
webpackConfig.plugins.delete('copy')
if (!process.env.UNI_OPT_PREFETCH) {
webpackConfig.plugins.delete('prefetch-index')
}
if (!process.env.UNI_OPT_PRELOAD) {
webpackConfig.plugins.delete('preload-index')
}
const compilerOptions = require('./compiler-options')
if (publicPath === './') {
compilerOptions.publicPath = publicPath
}
modifyVueLoader(webpackConfig, {
isH5: true,
hotReload: true
}, compilerOptions, api)
if (process.env.NODE_ENV === 'production') {
require('./cssnano-options')(webpackConfig)
}
}
}
+55
View File
@@ -0,0 +1,55 @@
const {
camelize,
convertStaticStyle
} = require('@dcloudio/uni-cli-shared')
module.exports = {
modules: [require('./format-text'), {
preTransformNode (el, {
warn
}) {
if (el.attrsMap) {
if (el.attrsMap.style) {
el.attrsMap.style = convertStaticStyle(el.attrsMap.style)
}
if (process.env.UNI_PLATFORM === 'mp-baidu') { // fixed data-index => dataIndex
Object.keys(el.attrsMap).forEach(attr => {
if (attr.indexOf(':data-') === 0) {
el.attrsMap[camelize(attr)] = el.attrsMap[attr]
delete el.attrsMap[attr]
}
})
}
}
if (el.attrsList && el.attrsList.length) {
el.attrsList.forEach(attr => {
if (attr.name === 'style' && attr.value) {
attr.value = convertStaticStyle(attr.value)
}
if (process.env.UNI_PLATFORM === 'mp-baidu') { // fixed data-index => dataIndex
if (attr.name.indexOf(':data-') === 0) {
attr.name = camelize(attr.name)
}
}
})
}
},
postTransformNode (el) {
if (process.env.UNI_PLATFORM === 'mp-alipay') {
if (el.tag === 'slot') {
if (!el.children.length) {
el.children.push({
type: 1,
tag: 'view',
attrsList: [],
attrsMap: {},
parent: el,
children: [],
plain: true
})
}
}
}
}
}]
}
+386
View File
@@ -0,0 +1,386 @@
const path = require('path')
const webpack = require('webpack')
const {
parseEntry,
getMainEntry,
normalizePath,
getPlatformExts,
getPlatformCssnano,
getPlatformStat,
getPlatformPush,
getPlatformUniCloud,
createSource,
deleteAsset,
getDevUniConsoleCode
} = require('@dcloudio/uni-cli-shared')
const WebpackUniAppPlugin = require('../../packages/webpack-uni-app-loader/plugin/index')
const modifyVueLoader = require('../vue-loader')
const {
createTemplateCacheLoader
} = require('../cache-loader')
function createUniMPPlugin () {
const WebpackUniMPPlugin = require('@dcloudio/webpack-uni-mp-loader/lib/plugin/index-new')
return new WebpackUniMPPlugin()
}
const createWxMpIndependentPlugins = require('@dcloudio/uni-mp-weixin/lib/createIndependentPlugin')
const UniTips = require('./tips')
function getProvides () {
const uniPath = require('@dcloudio/uni-cli-shared/lib/platform').getMPRuntimePath()
const uniCloudPath = path.resolve(__dirname, '../../packages/uni-cloud/dist/index.js')
const provides = {
uni: [uniPath, 'default'],
uniCloud: [uniCloudPath, 'uniCloud']
}
if (process.env.UNI_USING_VUE3) {
provides.uni = ['@dcloudio/uni-' + process.env.UNI_PLATFORM + '/dist/uni.api.esm.js', 'default']
provides.createMiniProgramApp = [uniPath, 'createApp']
}
if (process.env.UNI_USING_COMPONENTS) {
if (process.env.UNI_SUBPACKGE) {
provides.createApp = [uniPath, 'createSubpackageApp']
} else if (process.env.UNI_MP_PLUGIN) {
provides.createApp = [uniPath, 'createPlugin']
} else {
provides.createApp = [uniPath, 'createApp']
}
provides.createPage = [uniPath, 'createPage']
provides.createComponent = [uniPath, 'createComponent']
}
if (
process.env.UNI_PLATFORM === 'app-plus' &&
process.env.UNI_USING_V8
) {
provides.__f__ = [path.resolve(__dirname, '../format-log.js'), 'default']
const cryptoProvide = [path.resolve(__dirname, '../crypto.js'), 'default']
provides.crypto = cryptoProvide
provides['window.crypto'] = cryptoProvide
provides['global.crypto'] = cryptoProvide
}
// TODO 目前依赖库 megalo 通过判断 wx 对象是否存在来识别平台做不同处理
if (
process.env.UNI_PLATFORM !== 'mp-qq' &&
process.env.UNI_PLATFORM !== 'mp-weixin' &&
process.env.UNI_PLATFORM !== 'app-plus'
) { // 非微信小程序,自动注入 wx 对象
provides.wx = provides.uni
}
if (process.env.UNI_PLATFORM === 'mp-weixin') {
provides.wx = [path.resolve(uniPath, '../wx.js'), 'default']
}
return provides
}
function processWxss (compilation, name, assets) {
const dirname = path.dirname(name)
const mainWxssCode = `@import "${normalizePath(path.relative(dirname, 'common/main.wxss'))}";`
const code = `${mainWxssCode}` + assets[name].source().toString()
compilation.updateAsset(name, createSource(code))
}
const parseRequirePath = path => path.startsWith('common') ? `./${path}` : path
function procssJs (compilation, name, assets, hasVendor) {
const dirname = path.dirname(name)
const runtimeJsCode = `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/runtime.js')))}');`
const vendorJsCode = hasVendor
? `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/vendor.js')))}');` : ''
const mainJsCode = `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/main.js')))}');`
const code = `${runtimeJsCode}${vendorJsCode}${mainJsCode}` + assets[name].source().toString()
compilation.updateAsset(name, createSource(code))
}
function processAssets (compilation) {
const assets = compilation.assets
const hasMainWxss = assets['common/main.wxss']
const hasVendor = assets['common/vendor.js']
Object.keys(assets).forEach(name => {
if (name.startsWith('common')) {
return
}
const extname = path.extname(name)
if (extname === '.wxss' && hasMainWxss && process.UNI_ENTRY[name.replace(extname, '')]) {
processWxss(compilation, name, assets)
} else if (extname === '.js') {
procssJs(compilation, name, assets, hasVendor)
}
})
// delete assets['common/main.js']
deleteAsset(compilation, 'app.js')
deleteAsset(compilation, 'app.json')
deleteAsset(compilation, 'app.wxss')
deleteAsset(compilation, 'project.config.json')
}
class PreprocessAssetsPlugin {
apply (compiler) {
if (webpack.version[0] > 4) {
compiler.hooks.compilation.tap('PreprocessAssetsPlugin', compilation => {
compilation.hooks.processAssets.tap({
name: 'PreprocessAssetsPlugin',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
}, (_) => {
processAssets(compilation)
})
})
} else {
compiler.hooks.emit.tap('PreprocessAssetsPlugin', (compilation) => processAssets(compilation))
}
}
}
function initSubpackageConfig (webpackConfig, vueOptions) {
if (process.env.UNI_OUTPUT_DEFAULT_DIR === process.env.UNI_OUTPUT_DIR) { // 未自定义output
process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, (process.env.UNI_SUBPACKGE || process.env
.UNI_MP_PLUGIN))
}
vueOptions.outputDir = process.env.UNI_OUTPUT_DIR
webpackConfig.output.path(process.env.UNI_OUTPUT_DIR)
webpackConfig.output.set(webpack.version[0] > 4 ? 'chunkLoadingGlobal' : 'jsonpFunction', 'webpackJsonp_' + (process
.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN))
}
function addToUniEntry (fileName) {
fileName && (process.UNI_ENTRY[fileName.split('.')[0]] = path.resolve(process.env.UNI_INPUT_DIR, fileName))
}
module.exports = {
vueConfig: {
parallel: false
},
webpackConfig (webpackConfig, vueOptions, api) {
if (!webpackConfig.optimization) {
webpackConfig.optimization = {}
}
// disable noEmitOnErrors
if (webpack.version[0] > 4) {
webpackConfig.optimization.emitOnErrors = true
} else {
webpackConfig.optimization.noEmitOnErrors = false
}
webpackConfig.optimization.runtimeChunk = {
name: 'common/runtime'
}
webpackConfig.optimization.splitChunks = require('../split-chunks')()
if (webpack.version[0] > 4) {
webpackConfig.optimization.chunkIds = 'named'
}
parseEntry()
const statCode = getPlatformStat()
const pushCode = getPlatformPush()
const uniCloudCode = getPlatformUniCloud()
let beforeCode = getDevUniConsoleCode() + 'import \'uni-pages\';'
const plugins = [
new WebpackUniAppPlugin(),
createUniMPPlugin(),
new webpack.ProvidePlugin(getProvides()),
...createWxMpIndependentPlugins()
]
if ((process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) && process.env.UNI_SUBPACKGE !== 'main') {
plugins.push(new PreprocessAssetsPlugin())
}
{
const globalEnv = process.env.UNI_PLATFORM === 'mp-alipay' ? 'my' : 'wx';
[].concat(
process.env.UNI_MP_PLUGIN
? process.env.UNI_MP_PLUGIN_MAIN
: JSON.parse(process.env.UNI_MP_PLUGIN_EXPORT)
).forEach(fileName => addToUniEntry(fileName))
beforeCode += `
// @ts-ignore
${globalEnv}.__webpack_require_UNI_MP_PLUGIN__ = __webpack_require__;`
}
const alias = { // 仅 mp-weixin
'mpvue-page-factory': require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
}
if (process.env.UNI_USING_VUE3) {
alias.vuex = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex')
alias['@vue/devtools-api'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/devtools-api')
alias['vue-i18n'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n')
alias['@dcloudio/uni-app'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-app')
}
// 使用外层依赖的版本
alias['regenerator-runtime'] = require.resolve('regenerator-runtime')
const output = {
pathinfo: true,
filename: '[name].js',
chunkFilename: '[id].js',
globalObject: process.env.UNI_PLATFORM === 'mp-alipay' ? 'my' : 'global'
// sourceMapFilename: '../.sourcemap/' + process.env.UNI_PLATFORM + '/[name].js.map'
}
if (process.env.NODE_ENV === 'production' || process.env.UNI_MINIMIZE === 'true') {
output.pathinfo = false
}
if (process.env.UNI_PLATFORM === 'mp-weixin' && process.env.NODE_ENV === 'production') {
plugins.push(new UniTips())
}
return {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
entry () {
return process.UNI_ENTRY
},
output,
performance: {
hints: false
},
resolve: {
extensions: ['.uts', '.nvue'],
alias
},
module: {
rules: [{
test: path.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
use: [{
loader: path.resolve(__dirname, '../../packages/wrap-loader'),
options: {
before: [
beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode
]
}
}, {
loader: '@dcloudio/webpack-uni-mp-loader/lib/main'
}]
}, {
resourceQuery: /vue&type=script/,
use: [{
loader: '@dcloudio/webpack-uni-mp-loader/lib/script'
}]
}, {
resourceQuery: /vue&type=template/,
use: [{
loader: '@dcloudio/webpack-uni-mp-loader/lib/template'
}, {
loader: '@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta'
}]
}, createTemplateCacheLoader(api), {
resourceQuery: [
/lang=wxs/,
/lang=filter/,
/lang=sjs/,
/blockType=wxs/,
/blockType=filter/,
/blockType=sjs/
],
use: [{
loader: require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-filter-loader')
}]
}]
},
plugins
}
},
chainWebpack (webpackConfig, vueOptions, api) {
if (process.env.UNI_PLATFORM === 'mp-baidu') {
webpackConfig.module
.rule('js')
.exclude
.add(/\.filter\.js$/)
}
const compilerOptions = process.env.UNI_USING_COMPONENTS ? {} : require('../mp-compiler-options')
modifyVueLoader(webpackConfig, {}, compilerOptions, api)
const styleExt = getPlatformExts().style
webpackConfig.plugin('extract-css')
.init((Plugin, args) => new Plugin({
filename: '[name]' + styleExt,
// mini-css-extract-plugin 2.3.0 版本以上可用
// https://github.com/webpack-contrib/mini-css-extract-plugin/releases/tag/v2.3.0
runtime: false
}))
// 去除 mini-css-extract-plugin 2.3.0 以下版本的 css runtime
// https://github.com/webpack-contrib/mini-css-extract-plugin/blob/e200b083e5a437026d6021262d4ac56088b39e65/src/index.js#L273
if (require('semver').lt(require('mini-css-extract-plugin/package.json').version, '2.3.0')) {
const pluginName = 'skip-mini-css-extract-runtime'
webpackConfig.plugin(pluginName).use(
class SkipMiniCssExtractRuntimePlugin {
apply (compiler) {
compiler.hooks.thisCompilation.tap(pluginName, compilation => {
const { mainTemplate } = compilation
const reg = /\/\/ mini-css-extract-plugin CSS loading[\s\S]*installedCssChunks\[chunkId\] = 0;\s*\}\)\);\s*\}/
mainTemplate.hooks.requireEnsure.tap(pluginName, (source, chunk) => {
return reg.test(source) ? source.replace(reg, '') : source
})
})
}
}
)
}
if (
process.env.NODE_ENV === 'production' &&
process.env.UNI_PLATFORM !== 'app-plus'
) {
// webpack5 不再使用 OptimizeCssnanoPlugin,改用 CssMinimizerPlugin
if (webpack.version[0] > 4) {
webpackConfig.optimization.minimizer('css').tap(args => {
args[0].test = new RegExp(`\\${styleExt}$`)
return args
})
} else {
const OptimizeCssnanoPlugin = require('../../packages/@intervolga/optimize-cssnano-plugin/index.js')
webpackConfig.plugin('optimize-css')
.init((Plugin, args) => new OptimizeCssnanoPlugin({
sourceMap: false,
filter (assetName) {
return path.extname(assetName) === styleExt
},
cssnanoOptions: {
preset: [
'default',
Object.assign({}, getPlatformCssnano(), {
discardComments: true
})
]
}
}))
}
}
if (process.env.NODE_ENV === 'production' && webpack.version[0] > 4) {
// 暂时禁用,否则导致 provide 被压缩和裁剪
webpackConfig.optimization.usedExports(false)
}
if (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) {
initSubpackageConfig(webpackConfig, vueOptions)
}
webpackConfig.plugins.delete('hmr')
webpackConfig.plugins.delete('html')
webpackConfig.plugins.delete('copy')
webpackConfig.plugins.delete('preload')
webpackConfig.plugins.delete('prefetch')
}
}
+67
View File
@@ -0,0 +1,67 @@
const fs = require('fs')
const path = require('path')
const {
isInHBuilderX
} = require('@dcloudio/uni-cli-shared')
class UniTips {
apply (compiler) {
compiler.hooks.emit.tap('PreprocessAssetsPlugin', compilation => {
const assets = compilation.assets
let hasAd = false
try {
Object.keys(assets).forEach(name => {
if (hasAd) {
return
}
if (!name.startsWith('common') && !name.startsWith('pages')) {
return
}
const extname = path.extname(name)
if (extname !== '.js') {
return
}
if (!hasAd && !process.env.USE_UNI_AD) {
hasAd = assets[name]._value.match(/createRewardedVideoAd|createInterstitialAd/)
}
})
setTimeout(() => {
if (hasAd) {
console.log(
'推荐使用uni-ad微信小程序版广告,无开通门槛、提前结算、插件丰富,助力广告变现。详情: https://uniapp.dcloud.net.cn/component/ad-weixin.html'
)
}
let projectRoot = ''
if (isInHBuilderX) {
projectRoot = process.env.UNI_INPUT_DIR
} else {
projectRoot = process.env.UNI_CLI_CONTEXT
}
const paths = fs.readdirSync(projectRoot)
const useUniCloud = paths.find((name) => {
return name.includes('uniCloud-')
})
if (!useUniCloud && assets['project.config.json']) {
const pcjString = assets['project.config.json'].source()
const pcjJson = JSON.parse(pcjString)
if (typeof pcjJson.cloudfunctionRoot === 'string' && pcjJson.cloudfunctionRoot.length > 0) {
console.log(
'欢迎使用uniCloud,价格更便宜、开发更方便、生态更丰富的云开发。详情: https://uniapp.dcloud.net.cn/uniCloud/wx2unicloud.html'
)
}
}
}, 100)
} catch (e) {}
})
}
}
module.exports = UniTips
+107
View File
@@ -0,0 +1,107 @@
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const {
pathToRegexp
} = require('@dcloudio/uni-cli-shared/lib/util')
module.exports = function initOptions (options) {
const {
getPlatformScss,
getPlatformSass
} = require('@dcloudio/uni-cli-shared')
if (!options.transpileDependencies) {
options.transpileDependencies = []
}
// 增加 src/node_modules 解析
options.transpileDependencies.push(pathToRegexp(path.resolve(process.env.UNI_INPUT_DIR, 'node_modules'), {
start: true
}))
options.transpileDependencies.push('@dcloudio/uni-' + process.env.UNI_PLATFORM)
options.transpileDependencies.push('@dcloudio/uni-i18n')
options.transpileDependencies.push('@dcloudio/uni-stat')
options.transpileDependencies.push('@dcloudio/uni-push')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-app')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-stat')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-push')
if (process.env.UNI_PLATFORM !== 'mp-weixin') { // mp runtime
options.transpileDependencies.push('@dcloudio/uni-mp-weixin')
}
if (process.env.UNI_PLATFORM === 'h5') { // h5 dev 用到了这两个,需要 babel
options.transpileDependencies.push('ansi-regex')
options.transpileDependencies.push('strip-ansi')
}
if (!options.css) {
options.css = {}
}
if (process.env.UNI_PLATFORM === 'h5' || process.env.UNI_USING_V3) {
options.css.extract = false
} else {
options.css.extract = true
}
if (!options.css.loaderOptions) {
options.css.loaderOptions = {}
}
if (!options.css.loaderOptions.postcss) {
options.css.loaderOptions.postcss = {}
}
if (!options.css.loaderOptions.sass) {
options.css.loaderOptions.sass = {}
}
if (webpack.version[0] > 4) {
if (!options.css.loaderOptions.postcss.postcssOptions) {
options.css.loaderOptions.postcss.postcssOptions = {}
}
} else {
if (!options.css.loaderOptions.postcss.config) {
options.css.loaderOptions.postcss.config = {}
}
}
// sass 全局变量
const isSass = fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'uni.sass'))
const isScss = fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'uni.scss'))
let sassData = isSass ? getPlatformSass() : getPlatformScss()
if (process.env.UNI_SASS_IMPLEMENTATION_NAME === 'dart-sass') {
if (isSass) {
sassData = '@use "@/uni.sass" as *'
} else if (isScss) {
sassData = '@use "@/uni.scss" as *;'
}
} else {
if (isSass) {
sassData = '@import "@/uni.sass"'
} else if (isScss) {
sassData = `${sassData}
@import "@/uni.scss";`
}
}
if (!options.css.loaderOptions.sass.sassOptions) {
options.css.loaderOptions.sass.sassOptions = {}
}
// 指定 outputStyle, 否则 production 模式下会被默认成 compressed
const outputStyle = options.css.loaderOptions.sass.sassOptions.outputStyle
if (!outputStyle || outputStyle === 'compressed') {
options.css.loaderOptions.sass.sassOptions.outputStyle = 'expanded'
}
options.css.loaderOptions.sass.prependData = sassData
const userPostcssConfigPath = path.resolve(process.env.UNI_INPUT_DIR, 'postcss.config.js')
const configPath = fs.existsSync(userPostcssConfigPath) ? userPostcssConfigPath : path.resolve(process.env
.UNI_CLI_CONTEXT, 'postcss.config.js')
if (webpack.version[0] > 4) {
options.css.loaderOptions.postcss.postcssOptions.config = configPath
} else {
options.css.loaderOptions.postcss.config.path = configPath
}
}
+257
View File
@@ -0,0 +1,257 @@
const path = require('path')
const {
normalizePath
} = require('@dcloudio/uni-cli-shared')
const subPkgsInfo = Object.values(process.UNI_SUBPACKAGES)
const normalFilter = ({
independent
}) => !independent
const independentFilter = ({
independent
}) => independent
const map2Root = ({
root
}) => root + '/'
const normalSubPackageRoots = subPkgsInfo.filter(normalFilter).map(map2Root)
const independentSubpackageRoots = subPkgsInfo.filter(independentFilter).map(map2Root)
function createCacheGroups () {
const cacheGroups = {}
if (process.UNI_CONFUSION) { // 加密
cacheGroups.confusion = {
enforce: true,
test: function (module) {
if (!module.resource) {
return false
}
if (process.UNI_CONFUSION.includes(normalizePath(module.resource))) {
return true
}
return false
},
name: 'app-confusion',
chunks: 'all'
}
}
process.env.UNI_OPT_SUBPACKAGES && Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
cacheGroups[root] = {
enforce: true,
test: function (module) {
if (!module.resource) {
return false
}
if (normalizePath(module.resource).includes(root + '/')) {
return true
}
return false
},
name: root + '/app-sub-service',
chunks: 'all'
}
})
return cacheGroups
}
module.exports = function getSplitChunks () {
const {
normalizePath
} = require('@dcloudio/uni-cli-shared')
if (process.env.UNI_USING_V3) {
return {
cacheGroups: createCacheGroups()
}
}
if (!process.env.UNI_USING_COMPONENTS) {
return {
cacheGroups: {
commons: {
minChunks: 2,
name: 'common/vendor',
chunks: 'all'
}
}
}
}
const mainPath = normalizePath(path.resolve(process.env.UNI_INPUT_DIR, 'main.'))
if (!process.env.UNI_OPT_SUBPACKAGES) {
return {
chunks (chunk) { // 防止 node_modules 内 vue 组件被 split
return (chunk.name || '').indexOf('node-modules') !== 0
},
cacheGroups: {
default: false,
vendors: false,
commons: {
test (module) {
if (module.type === 'css/mini-extract') {
return false
}
if (module.resource && (
module.resource.indexOf('.vue') !== -1 ||
module.resource.indexOf('.nvue') !== -1 ||
normalizePath(module.resource).indexOf(mainPath) === 0 // main.js
)) {
return false
}
return true
},
minChunks: 1,
name: 'common/vendor',
chunks: 'all'
}
}
}
}
function baseTest (module) {
if (module.type === 'css/mini-extract') {
return false
}
if (module.resource) {
const resource = normalizePath(module.resource)
if (
resource.indexOf('.vue') !== -1 ||
resource.indexOf('.nvue') !== -1 ||
resource.indexOf(mainPath) === 0 // main.js
) {
return false
}
}
return true
}
function getModuleChunks (module, chunks) {
// webpack5
if ('chunkGraph' in chunks) {
chunks = chunks.chunkGraph.getModuleChunks(module)
}
return chunks
}
// TODO 独立分包
const cacheGroups = {
default: false,
vendors: false,
commons: {
test (module, chunks) {
if (!baseTest(module)) {
return false
}
chunks = getModuleChunks(module, chunks)
const matchSubPackages = findSubPackages(chunks)
const matchSubPackagesCount = matchSubPackages.size
const isMainPackage = ( // 非分包 或 两个及以上分包 或 主包内有使用
matchSubPackagesCount === 0 ||
matchSubPackagesCount > 1 ||
(
matchSubPackagesCount === 1 &&
hasMainPackage(chunks)
) ||
(
matchSubPackagesCount === 1 &&
hasMainPackageComponent(module, matchSubPackages.values().next().value)
)
)
if (isMainPackage && process.env.UNI_OPT_TRACE) {
console.log('main', module.resource, chunks.map(chunk => chunk.name))
}
return isMainPackage
},
minSize: 0,
minChunks: 1,
name: 'common/vendor',
chunks: 'all'
}
}
const findSubPackages = function (chunks) {
return chunks.reduce((pkgs, item) => {
const name = normalizePath(item.name)
const pkgRoot = normalSubPackageRoots.find(root => name.indexOf(root) === 0)
pkgRoot && pkgs.add(pkgRoot)
return pkgs
}, new Set())
}
const hasMainPackage = function (chunks) {
return chunks.find(item => !subPackageRoots.find(root => item.name.indexOf(root) === 0))
}
const hasMainPackageComponent = function (module, subPackageRoot) {
if (module.resource && module.reasons) {
for (let index = 0; index < module.reasons.length; index++) {
const m = module.reasons[index]
if (m.module && m.module.resource) {
const resource = normalizePath(m.module.resource)
if (
resource.indexOf('.vue') !== -1 ||
resource.indexOf('.nvue') !== -1
) {
if (resource.indexOf(subPackageRoot) === -1) {
if (process.env.UNI_OPT_TRACE) {
console.log('move module to main chunk:', module.resource,
'from', subPackageRoot, 'for component in main package:', resource)
}
// 独立分包除外
const independentRoot = independentSubpackageRoots.find(root => resource.indexOf(root) >= 0)
if (!independentRoot) {
return true
}
}
} else {
return hasMainPackageComponent(m.module, subPackageRoot)
}
}
}
}
return false
}
const subPackageRoots = Object.keys(process.UNI_SUBPACKAGES).map(root => root + '/')
Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
(function (root) {
cacheGroups[root + '/commons'] = {
test (module, chunks) {
if (!baseTest(module)) {
return false
}
chunks = getModuleChunks(module, chunks)
const matchSubPackages = findSubPackages(chunks)
if (
matchSubPackages.size === 1 &&
matchSubPackages.has(root + '/') &&
!hasMainPackage(chunks) &&
!hasMainPackageComponent(module, matchSubPackages.values().next().value)
) {
if (process.env.UNI_OPT_TRACE) {
console.log(root, module.resource, chunks.map(chunk => chunk.name))
}
return true
}
},
minSize: 0,
minChunks: 1,
name: normalizePath(path.join(root, 'common/vendor')),
chunks: 'all'
}
})(root)
})
return {
chunks (chunk) { // 防止 node_modules 内 vue 组件被 split
return chunk.name.indexOf('node-modules') !== 0
},
cacheGroups
}
}
+119
View File
@@ -0,0 +1,119 @@
const fs = require('fs')
const path = require('path')
const {
pathToGlob
} = require('@dcloudio/uni-cli-shared/lib/util')
let partialIdentifier = false
module.exports = {
getPartialIdentifier () {
if (!partialIdentifier) {
partialIdentifier = {
UNI_COMPILER_VERSION: require('../package.json').version
}
Object.keys(process.env).forEach(name => {
if (name.indexOf('UNI_') === 0) {
partialIdentifier[name] = process.env[name]
}
})
}
return partialIdentifier
},
getAutomatorCode () {
const automator = `@dcloudio/uni-${process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM}/dist/automator`
return process.env.UNI_AUTOMATOR_WS_ENDPOINT ? `import '${automator}';` : ''
},
getWatchOptions () {
return {
ignored: [
pathToGlob(path.resolve(process.env.UNI_INPUT_DIR), '*.md'),
path.resolve(process.env.UNI_INPUT_DIR, '.hbuilderx'),
path.resolve(process.env.UNI_INPUT_DIR, '.editorconfig'),
path.resolve(process.env.UNI_INPUT_DIR, '.gitignore'),
path.resolve(process.env.UNI_INPUT_DIR, 'LICENSE'),
path.resolve(process.env.UNI_INPUT_DIR, 'unpackage'),
path.resolve(process.env.UNI_INPUT_DIR, 'uniCloud-aliyun'),
path.resolve(process.env.UNI_INPUT_DIR, 'uniCloud-tcb'),
path.resolve(process.env.UNI_INPUT_DIR, 'uniCloud-alipay'),
path.resolve(process.env.UNI_INPUT_DIR, 'uniCloud-dcloud'),
path.resolve(process.env.UNI_INPUT_DIR, 'cloudfunctions-aliyun'),
path.resolve(process.env.UNI_INPUT_DIR, 'cloudfunctions-tcb')
]
}
},
getTsLoadOptions () {
const {
isInHBuilderX // 在 HBuilderX 的插件中
} = require('@dcloudio/uni-cli-shared')
const userTsConfigJson = path.resolve(process.env.UNI_INPUT_DIR, 'tsconfig.json')
const defaultTsConfigJson = path.resolve(process.env.UNI_CLI_CONTEXT, 'tsconfig.json')
const tsConfigJsonFile = fs.existsSync(userTsConfigJson) ? userTsConfigJson : defaultTsConfigJson
const context = isInHBuilderX ? process.env.UNI_INPUT_DIR : process.env.UNI_CLI_CONTEXT
function resolveModule (dir) {
return path.resolve(process.env.UNI_CLI_CONTEXT, './node_modules', dir)
}
return {
context,
configFile: tsConfigJsonFile,
compilerOptions: {
baseUrl: context,
typeRoots: [
resolveModule('@dcloudio/types'),
resolveModule('@types'),
path.resolve(process.env.UNI_CLI_CONTEXT, 'types')
],
types: [
'uni-app',
'uni-app-vue2',
'webpack-env'
],
paths: {
'@/*': [
path.join(process.env.UNI_INPUT_DIR, '*')
],
vue: [
resolveModule('vue')
],
vuex: [
resolveModule('vuex')
],
'vue-class-component': [
resolveModule('vue-class-component')
],
'vue-property-decorator': [
resolveModule('vue-property-decorator')
],
tslib: [
resolveModule('tslib')
],
'mpvue-page-factory': [
resolveModule('@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
],
'@vue/composition-api': [
resolveModule('@dcloudio/vue-cli-plugin-uni/packages/@vue/composition-api')
],
'@dcloudio/uni-app': [
resolveModule('@dcloudio/uni-app')
]
}
},
errorFormatter (error, colors) {
const messageColor = error.severity === 'warning' ? colors.bold.yellow : colors.bold.red
const filePath = path.relative(process.env.UNI_INPUT_DIR, error.file).replace('.vue.ts', '.vue')
if (error.code === 2307 && error.content.includes('.vue')) {
error.content = error.content.replace('Cannot find module ', '') +
' script 节点必须使用 lang="ts",文档参考地址:https://uniapp.dcloud.io/frame?id=vue-ts'
}
return messageColor(
`[tsl] ERROR at ${filePath}:${error.line}
TS${error.code}:${error.content}`
)
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
const vueLoader = require('@dcloudio/uni-cli-shared/lib/vue-loader')
const {
getPartialIdentifier
} = require('./util')
module.exports = function modifyVueLoader (webpackConfig, loaderOptions, compilerOptions, api) {
// vue-loader options
const cacheConfig = {
cacheDirectory: false,
cacheIdentifier: false
}
if (process.env.UNI_USING_CACHE) {
Object.assign(cacheConfig, api.genCacheConfig(
'vue-template-compiler/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
))
}
webpackConfig.module
.rule('vue')
.test(vueLoader.test)
.use('vue-loader')
.loader(vueLoader.loader)
.tap(options => Object.assign(options, vueLoader.options(loaderOptions, compilerOptions), cacheConfig))
.end()
// 强制使用vue2,vue3时会使用vue-loader-v16
webpackConfig.plugin('vue-loader').use(require(vueLoader.loader).VueLoaderPlugin)
// h5 框架需要使用 scoped 样式,其他平台编译时识别是否 nvue 文件且注入 flex 相关样式
if (process.env.UNI_PLATFORM === 'h5') {
webpackConfig.module
.rule('vue')
.use('uniapp-h5-style-scoped')
.loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/webpack-scoped-loader'))
} else {
webpackConfig.module
.rule('vue')
.use('uniapp-nvue-style-loader')
.loader(require.resolve('@dcloudio/webpack-uni-mp-loader/lib/style.js'))
}
// 是否启用 cache
if (process.env.UNI_USING_CACHE) {
webpackConfig.module
.rule('vue')
.use('cache-loader')
.tap(options => Object.assign(options, api.genCacheConfig(
'vue-loader/' + process.env.UNI_PLATFORM,
getPartialIdentifier()
)))
} else {
webpackConfig.module
.rule('vue')
.uses
.delete('cache-loader')
}
}
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cross-env/dist/bin/cross-env.js" "$@"
else
exec node "$basedir/../cross-env/dist/bin/cross-env.js" "$@"
fi
@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cross-env/dist/bin/cross-env-shell.js" "$@"
else
exec node "$basedir/../cross-env/dist/bin/cross-env-shell.js" "$@"
fi
@@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\cross-env\dist\bin\cross-env-shell.js" %*
@@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
} else {
& "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
} else {
& "node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret
@@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\cross-env\dist\bin\cross-env.js" %*
@@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
} else {
& "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
} else {
& "node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cssesc/bin/cssesc" "$@"
else
exec node "$basedir/../cssesc/bin/cssesc" "$@"
fi
+17
View File
@@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\cssesc\bin\cssesc" %*
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args
} else {
& "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cssesc/bin/cssesc" $args
} else {
& "node$exe" "$basedir/../cssesc/bin/cssesc" $args
}
$ret=$LASTEXITCODE
}
exit $ret
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver" "$@"
else
exec node "$basedir/../semver/bin/semver" "$@"
fi
+17
View File
@@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver" %*
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver" $args
}
$ret=$LASTEXITCODE
}
exit $ret
@@ -0,0 +1,4 @@
# CHANGELOG
The changelog is automatically updated using [semantic-release](https://github.com/semantic-release/semantic-release).
You can see it on the [releases page](../../releases).
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2017 Kent C. Dodds
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,219 @@
<div align="center">
<h1>cross-env 🔀</h1>
Run scripts that set and use environment variables across platforms
</div>
<hr />
[![Travis Build Status][build-badge]][build]
[![AppVeyor Build Status][win-build-badge]][win-build]
[![Code Coverage][coverage-badge]][coverage]
[![Dependencies][dependencyci-badge]][dependencyci]
[![version][version-badge]][package]
[![node-version][node-version-badge]][node]
[![downloads][downloads-badge]][npm-stat]
[![MIT License][license-badge]][LICENSE]
[![All Contributors](https://img.shields.io/badge/all_contributors-19-orange.svg?style=flat-square)](#contributors)
[![PRs Welcome][prs-badge]][prs]
[![Donate][donate-badge]][donate]
[![Code of Conduct][coc-badge]][coc]
[![Roadmap][roadmap-badge]][roadmap]
[![Examples][examples-badge]][examples]
[![Watch on GitHub][github-watch-badge]][github-watch]
[![Star on GitHub][github-star-badge]][github-star]
[![Tweet][twitter-badge]][twitter]
## The problem
Most Windows command prompts will choke when you set environment variables with
`NODE_ENV=production` like that. (The exception is [Bash on Windows][win-bash],
which uses native Bash.) Similarly, there's a difference in how windows and
POSIX commands utilize environment variables. With POSIX, you use: `$ENV_VAR`
and on windows you use `%ENV_VAR%`.
## This solution
`cross-env` makes it so you can have a single command without worrying about
setting or using the environment variable properly for the platform. Just set it
like you would if it's running on a POSIX system, and `cross-env` will take care
of setting it properly.
## Installation
This module is distributed via [npm][npm] which is bundled with [node][node] and
should be installed as one of your project's `devDependencies`:
```
npm install --save-dev cross-env
```
> WARNING! Make sure that when you're installing packages that you spell things
> correctly to avoid [mistakenly installing malware][malware]
## Usage
I use this in my npm scripts:
```json
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
}
}
```
Ultimately, the command that is executed (using [`cross-spawn`][cross-spawn])
is:
```
webpack --config build/webpack.config.js
```
The `NODE_ENV` environment variable will be set by `cross-env`
You can also split a command into several ones, or separate the environment
variables declaration from the actual command execution. You can do it this way:
```json
{
"scripts": {
"parentScript": "cross-env GREET=\"Joe\" npm run childScript",
"childScript": "cross-env-shell \"echo Hello $GREET\""
}
}
```
Where `childScript` holds the actual command to execute and `parentScript` sets
the environment variables to use. Then instead of run the childScript you run
the parent. This is quite useful for launching the same command with different
env variables or when the environment variables are too long to have everything
in one line. It also means that you can use `$GREET` env var syntax even on
Windows which would usually require it to be `%GREET%`.
If you precede a dollar sign with an odd number of backslashes the expression statement will not be replaced. Note that this means backslashes after the JSON string escaping took place. `"FOO=\\$BAR"` will not be replaced. `"FOO=\\\\$BAR"` will be replaced though.
Lastly, if you want to pass a JSON string (e.g., when using [ts-loader]), you can do as follows:
```json
{
"scripts": {
"test": "cross-env TS_NODE_COMPILER_OPTIONS={\\\"module\\\":\\\"commonjs\\\"} node some_file.test.ts"
}
}
```
Pay special attention to the **triple backslash** `(\\\)` **before** the **double quotes** `(")` and the **absence** of **single quotes** `(')`.
Both of these conditions have to be met in order to work both on Windows and UNIX.
## `cross-env` vs `cross-env-shell`
The `cross-env` module exposes two bins: `cross-env` and `cross-env-shell`. The
first one executes commands using [`cross-spawn`][cross-spawn], while the
second one uses the `shell` option from Node's `spawn`.
The main use case for `cross-env-shell` is when you need an environment
variable to be set across an entire inline shell script, rather than just one
command.
For example, if you want to have the environment variable apply to several
commands in series then you will need to wrap those in quotes and use
`cross-env-shell` instead of `cross-env`.
```json
{
"scripts": {
"greet": "cross-env-shell GREETING=Hi NAME=Joe \"echo $GREETING && echo $NAME\""
}
}
```
The rule of thumb is: if you want to pass to `cross-env` a command that
contains special shell characters *that you want interpreted*, then use
`cross-env-shell`. Otherwise stick to `cross-env`.
On Windows you need to use `cross-env-shell`, if you want to handle [signal events](https://nodejs.org/api/process.html#process_signal_events) inside of your program. A common case for that is when you want to capture a `SIGINT` event invoked by pressing `Ctrl + C` on the command-line interface.
## Windows Issues
Please note that `npm` uses `cmd` by default and that doesn't support command
substitution, so if you want to leaverage that, then you need to update your
`.npmrc` to set the `script-shell` to powershell.
[Learn more here](https://github.com/kentcdodds/cross-env/issues/192#issuecomment-513341729).
## Inspiration
I originally created this to solve a problem I was having with my npm scripts in
[angular-formly][angular-formly]. This made contributing to the project
much easier for Windows users.
## Other Solutions
- [`env-cmd`](https://github.com/toddbluhm/env-cmd) - Reads environment variables from a file instead
- [`@naholyr/cross-env`](https://www.npmjs.com/package/@naholyr/cross-env) - `cross-env` with support for setting default values
## Contributors
Thanks goes to these people ([emoji key][emojis]):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
| [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/cross-env/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=kentcdodds "Tests") | [<img src="https://avatars1.githubusercontent.com/u/499038?v=3" width="100px;"/><br /><sub><b>Ya Zhuang </b></sub>](https://zhuangya.me)<br />[🔌](#plugin-zhuangya "Plugin/utility libraries") [📖](https://github.com/kentcdodds/cross-env/commits?author=zhuangya "Documentation") | [<img src="https://avatars3.githubusercontent.com/u/3440094?v=3" width="100px;"/><br /><sub><b>James Harris</b></sub>](https://wopian.me)<br />[📖](https://github.com/kentcdodds/cross-env/commits?author=wopian "Documentation") | [<img src="https://avatars1.githubusercontent.com/u/8941730?v=3" width="100px;"/><br /><sub><b>compumike08</b></sub>](https://github.com/compumike08)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Acompumike08 "Bug reports") [📖](https://github.com/kentcdodds/cross-env/commits?author=compumike08 "Documentation") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=compumike08 "Tests") | [<img src="https://avatars1.githubusercontent.com/u/2270425?v=3" width="100px;"/><br /><sub><b>Daniel Rodríguez Rivero</b></sub>](https://github.com/danielo515)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Adanielo515 "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=danielo515 "Code") [📖](https://github.com/kentcdodds/cross-env/commits?author=danielo515 "Documentation") | [<img src="https://avatars2.githubusercontent.com/u/1508477?v=3" width="100px;"/><br /><sub><b>Jonas Keinholz</b></sub>](https://github.com/inyono)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Ainyono "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=inyono "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=inyono "Tests") | [<img src="https://avatars3.githubusercontent.com/u/1656170?v=3" width="100px;"/><br /><sub><b>Hugo Wood</b></sub>](https://github.com/hgwood)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Ahgwood "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=hgwood "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=hgwood "Tests") |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| [<img src="https://avatars0.githubusercontent.com/u/3715715?v=3" width="100px;"/><br /><sub><b>Thiebaud Thomas</b></sub>](https://github.com/thomasthiebaud)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Athomasthiebaud "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=thomasthiebaud "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=thomasthiebaud "Tests") | [<img src="https://avatars1.githubusercontent.com/u/1715800?v=3" width="100px;"/><br /><sub><b>Daniel Rey López</b></sub>](https://daniel.blog)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=DanReyLop "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=DanReyLop "Tests") | [<img src="https://avatars2.githubusercontent.com/u/6374832?v=3" width="100px;"/><br /><sub><b>Amila Welihinda</b></sub>](http://amilajack.com)<br />[🚇](#infra-amilajack "Infrastructure (Hosting, Build-Tools, etc)") | [<img src="https://avatars1.githubusercontent.com/u/1396?v=3" width="100px;"/><br /><sub><b>Paul Betts</b></sub>](https://twitter.com/paulcbetts)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Apaulcbetts "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=paulcbetts "Code") | [<img src="https://avatars1.githubusercontent.com/u/6371670?v=3" width="100px;"/><br /><sub><b>Turner Hayes</b></sub>](https://github.com/turnerhayes)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Aturnerhayes "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=turnerhayes "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=turnerhayes "Tests") | [<img src="https://avatars2.githubusercontent.com/u/22251956?v=4" width="100px;"/><br /><sub><b>Suhas Karanth</b></sub>](https://github.com/sudo-suhas)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=sudo-suhas "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=sudo-suhas "Tests") | [<img src="https://avatars3.githubusercontent.com/u/512692?v=4" width="100px;"/><br /><sub><b>Sven</b></sub>](https://github.com/sventschui)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=sventschui "Code") [📖](https://github.com/kentcdodds/cross-env/commits?author=sventschui "Documentation") [💡](#example-sventschui "Examples") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=sventschui "Tests") |
| [<img src="https://avatars0.githubusercontent.com/u/5522668?v=4" width="100px;"/><br /><sub><b>D. Nicolás Lopez Zelaya</b></sub>](https://github.com/NicoZelaya)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=NicoZelaya "Code") | [<img src="https://avatars3.githubusercontent.com/u/219289?v=4" width="100px;"/><br /><sub><b>Johan Hernandez</b></sub>](http://bithavoc.io)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=bithavoc "Code") | [<img src="https://avatars3.githubusercontent.com/u/13559161?v=4" width="100px;"/><br /><sub><b>Jordan Nielson</b></sub>](https://github.com/jnielson94)<br />[🐛](https://github.com/kentcdodds/cross-env/issues?q=author%3Ajnielson94 "Bug reports") [💻](https://github.com/kentcdodds/cross-env/commits?author=jnielson94 "Code") [⚠️](https://github.com/kentcdodds/cross-env/commits?author=jnielson94 "Tests") | [<img src="https://avatars0.githubusercontent.com/u/5185660?v=4" width="100px;"/><br /><sub><b>Jason Cooke</b></sub>](https://nz.linkedin.com/in/jsonc11)<br />[📖](https://github.com/kentcdodds/cross-env/commits?author=Jason-Cooke "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/17709887?v=4" width="100px;"/><br /><sub><b>bibo5088</b></sub>](https://github.com/bibo5088)<br />[💻](https://github.com/kentcdodds/cross-env/commits?author=bibo5088 "Code") |
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors][all-contributors] specification. Contributions of any kind welcome!
> Note: this was added late into the project. If you've contributed to this
> project in any way, please make a pull request to add yourself to the list
> by following the instructions in the `CONTRIBUTING.md`
## LICENSE
MIT
[npm]: https://www.npmjs.com/
[node]: https://nodejs.org
[build-badge]: https://img.shields.io/travis/kentcdodds/cross-env.svg?style=flat-square
[build]: https://travis-ci.org/kentcdodds/cross-env
[win-build-badge]: https://img.shields.io/appveyor/ci/kentcdodds/cross-env.svg?style=flat-square
[win-build]: https://ci.appveyor.com/project/kentcdodds/cross-env
[coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/cross-env.svg?style=flat-square
[coverage]: https://codecov.io/github/kentcdodds/cross-env
[dependencyci-badge]: https://dependencyci.com/github/kentcdodds/cross-env/badge?style=flat-square
[dependencyci]: https://dependencyci.com/github/kentcdodds/cross-env
[version-badge]: https://img.shields.io/npm/v/cross-env.svg?style=flat-square
[package]: https://www.npmjs.com/package/cross-env
[node-version-badge]: https://img.shields.io/badge/node-%3E%3D%204.0-orange.svg?style=flat-square
[downloads-badge]: https://img.shields.io/npm/dm/cross-env.svg?style=flat-square
[npm-stat]: http://npm-stat.com/charts.html?package=cross-env&from=2016-04-01
[license-badge]: https://img.shields.io/npm/l/cross-env.svg?style=flat-square
[license]: https://github.com/kentcdodds/cross-env/blob/master/other/LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[donate-badge]: https://img.shields.io/badge/$-support-green.svg?style=flat-square
[donate]: http://kcd.im/donate
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: https://github.com/kentcdodds/cross-env/blob/master/other/CODE_OF_CONDUCT.md
[roadmap-badge]: https://img.shields.io/badge/%F0%9F%93%94-roadmap-CD9523.svg?style=flat-square
[roadmap]: https://github.com/kentcdodds/cross-env/blob/master/other/ROADMAP.md
[examples-badge]: https://img.shields.io/badge/%F0%9F%92%A1-examples-8C8E93.svg?style=flat-square
[examples]: https://github.com/kentcdodds/cross-env/blob/master/other/EXAMPLES.md
[github-watch-badge]: https://img.shields.io/github/watchers/kentcdodds/cross-env.svg?style=social
[github-watch]: https://github.com/kentcdodds/cross-env/watchers
[github-star-badge]: https://img.shields.io/github/stars/kentcdodds/cross-env.svg?style=social
[github-star]: https://github.com/kentcdodds/cross-env/stargazers
[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20cross-env!%20https://github.com/kentcdodds/cross-env%20%F0%9F%91%8D
[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/kentcdodds/cross-env.svg?style=social
[emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
[all-contributors]: https://github.com/kentcdodds/all-contributors
[win-bash]: https://msdn.microsoft.com/en-us/commandline/wsl/about
[angular-formly]: https://github.com/formly-js/angular-formly
[cross-spawn]: https://www.npmjs.com/package/cross-spawn
[ts-loader]: https://www.npmjs.com/package/ts-loader
[malware]: http://blog.npmjs.org/post/163723642530/crossenv-malware-on-the-npm-registry
@@ -0,0 +1,6 @@
#!/usr/bin/env node
'use strict';
var crossEnv = require('..');
crossEnv(process.argv.slice(2), { shell: true });
@@ -0,0 +1,6 @@
#!/usr/bin/env node
'use strict';
var crossEnv = require('..');
crossEnv(process.argv.slice(2));
@@ -0,0 +1,48 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _isWindows = require('./is-windows');
var _isWindows2 = _interopRequireDefault(_isWindows);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = commandConvert;
/**
* Converts an environment variable usage to be appropriate for the current OS
* @param {String} command Command to convert
* @param {Object} env Map of the current environment variable names and their values
* @param {boolean} normalize If the command should be normalized using `path`
* after converting
* @returns {String} Converted command
*/
function commandConvert(command, env) {
var normalize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!(0, _isWindows2.default)()) {
return command;
}
var envUnixRegex = /\$(\w+)|\${(\w+)}/g; // $my_var or ${my_var}
var convertedCmd = command.replace(envUnixRegex, function (match, $1, $2) {
var varName = $1 || $2;
// In Windows, non-existent variables are not replaced by the shell,
// so for example "echo %FOO%" will literally print the string "%FOO%", as
// opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145
// If the env variable isn't defined at runtime, just strip it from the command entirely
return env[varName] ? `%${varName}%` : '';
});
// Normalization is required for commands with relative paths
// For example, `./cmd.bat`. See kentcdodds/cross-env#127
// However, it should not be done for command arguments.
// See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970
return normalize === true ? _path2.default.normalize(convertedCmd) : convertedCmd;
}
@@ -0,0 +1,121 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _crossSpawn = require('cross-spawn');
var _command = require('./command');
var _command2 = _interopRequireDefault(_command);
var _variable = require('./variable');
var _variable2 = _interopRequireDefault(_variable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = crossEnv;
var envSetterRegex = /(\w+)=('(.*)'|"(.*)"|(.*))/;
function crossEnv(args) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _parseCommand = parseCommand(args),
_parseCommand2 = _slicedToArray(_parseCommand, 3),
envSetters = _parseCommand2[0],
command = _parseCommand2[1],
commandArgs = _parseCommand2[2];
var env = getEnvVars(envSetters);
if (command) {
var proc = (0, _crossSpawn.spawn)(
// run `path.normalize` for command(on windows)
(0, _command2.default)(command, env, true),
// by default normalize is `false`, so not run for cmd args
commandArgs.map(function (arg) {
return (0, _command2.default)(arg, env);
}), {
stdio: 'inherit',
shell: options.shell,
env
});
process.on('SIGTERM', function () {
return proc.kill('SIGTERM');
});
process.on('SIGINT', function () {
return proc.kill('SIGINT');
});
process.on('SIGBREAK', function () {
return proc.kill('SIGBREAK');
});
process.on('SIGHUP', function () {
return proc.kill('SIGHUP');
});
proc.on('exit', function (code, signal) {
var crossEnvExitCode = code;
// exit code could be null when OS kills the process(out of memory, etc) or due to node handling it
// but if the signal is SIGINT the user exited the process so we want exit code 0
if (crossEnvExitCode === null) {
crossEnvExitCode = signal === 'SIGINT' ? 0 : 1;
}
process.exit(crossEnvExitCode); //eslint-disable-line no-process-exit
});
return proc;
}
return null;
}
function parseCommand(args) {
var envSetters = {};
var command = null;
var commandArgs = [];
for (var i = 0; i < args.length; i++) {
var match = envSetterRegex.exec(args[i]);
if (match) {
var value = void 0;
if (typeof match[3] !== 'undefined') {
value = match[3];
} else if (typeof match[4] === 'undefined') {
value = match[5];
} else {
value = match[4];
}
envSetters[match[1]] = value;
} else {
// No more env setters, the rest of the line must be the command and args
var cStart = [];
cStart = args.slice(i)
// Regex:
// match "\'" or "'"
// or match "\" if followed by [$"\] (lookahead)
.map(function (a) {
var re = /\\\\|(\\)?'|([\\])(?=[$"\\])/g;
// Eliminate all matches except for "\'" => "'"
return a.replace(re, function (m) {
if (m === '\\\\') return '\\';
if (m === "\\'") return "'";
return '';
});
});
command = cStart[0];
commandArgs = cStart.slice(1);
break;
}
}
return [envSetters, command, commandArgs];
}
function getEnvVars(envSetters) {
var envVars = Object.assign({}, process.env);
if (process.env.APPDATA) {
envVars.APPDATA = process.env.APPDATA;
}
Object.keys(envSetters).forEach(function (varName) {
envVars[varName] = (0, _variable2.default)(envSetters[varName], varName);
});
return envVars;
}
@@ -0,0 +1,9 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
return process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE);
};
@@ -0,0 +1,74 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = varValueConvert;
var _isWindows = require('./is-windows');
var _isWindows2 = _interopRequireDefault(_isWindows);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pathLikeEnvVarWhitelist = new Set(['PATH', 'NODE_PATH']);
/**
* This will transform UNIX-style list values to Windows-style.
* For example, the value of the $PATH variable "/usr/bin:/usr/local/bin:."
* will become "/usr/bin;/usr/local/bin;." on Windows.
* @param {String} varValue Original value of the env variable
* @param {String} varName Original name of the env variable
* @returns {String} Converted value
*/
function replaceListDelimiters(varValue) {
var varName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var targetSeparator = (0, _isWindows2.default)() ? ';' : ':';
if (!pathLikeEnvVarWhitelist.has(varName)) {
return varValue;
}
return varValue.replace(/(\\*):/g, function (match, backslashes) {
if (backslashes.length % 2) {
// Odd number of backslashes preceding it means it's escaped,
// remove 1 backslash and return the rest as-is
return match.substr(1);
}
return backslashes + targetSeparator;
});
}
/**
* This will attempt to resolve the value of any env variables that are inside
* this string. For example, it will transform this:
* cross-env FOO=$NODE_ENV BAR=\\$NODE_ENV echo $FOO $BAR
* Into this:
* FOO=development BAR=$NODE_ENV echo $FOO
* (Or whatever value the variable NODE_ENV has)
* Note that this function is only called with the right-side portion of the
* env var assignment, so in that example, this function would transform
* the string "$NODE_ENV" into "development"
* @param {String} varValue Original value of the env variable
* @returns {String} Converted value
*/
function resolveEnvVars(varValue) {
var envUnixRegex = /(\\*)(\$(\w+)|\${(\w+)})/g; // $my_var or ${my_var} or \$my_var
return varValue.replace(envUnixRegex, function (_, escapeChars, varNameWithDollarSign, varName, altVarName) {
// do not replace things preceded by a odd number of \
if (escapeChars.length % 2 === 1) {
return varNameWithDollarSign;
}
return escapeChars.substr(0, escapeChars.length / 2) + (process.env[varName || altVarName] || '');
});
}
/**
* Converts an environment variable value to be appropriate for the current OS.
* @param {String} originalValue Original value of the env variable
* @param {String} originalName Original name of the env variable
* @returns {String} Converted value
*/
function varValueConvert(originalValue, originalName) {
return resolveEnvVars(replaceListDelimiters(originalValue, originalName));
}
@@ -0,0 +1,54 @@
{
"name": "cross-env",
"version": "5.2.1",
"description": "Run scripts that set and use environment variables across platforms",
"main": "dist/index.js",
"bin": {
"cross-env": "dist/bin/cross-env.js",
"cross-env-shell": "dist/bin/cross-env-shell.js"
},
"engines": {
"node": ">=4.0"
},
"scripts": {
"add-contributor": "kcd-scripts contributors add",
"build": "kcd-scripts build",
"lint": "kcd-scripts lint",
"test": "kcd-scripts test",
"test:update": "npm test -- --updateSnapshot --coverage",
"validate": "kcd-scripts validate",
"precommit": "kcd-scripts precommit"
},
"files": [
"dist"
],
"keywords": [
"cross-environment",
"environment variable",
"windows"
],
"author": "Kent C. Dodds <kent@doddsfamily.us> (http://kentcdodds.com/)",
"license": "MIT",
"dependencies": {
"cross-spawn": "^6.0.5"
},
"devDependencies": {
"kcd-scripts": "^0.3.4"
},
"eslintConfig": {
"extends": "./node_modules/kcd-scripts/eslint.js"
},
"eslintIgnore": [
"node_modules",
"coverage",
"dist"
],
"repository": {
"type": "git",
"url": "https://github.com/kentcdodds/cross-env.git"
},
"bugs": {
"url": "https://github.com/kentcdodds/cross-env/issues"
},
"homepage": "https://github.com/kentcdodds/cross-env#readme"
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,94 @@
# cross-spawn
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [![Greenkeeper badge][greenkeeper-image]][greenkeeper-url]
[npm-url]:https://npmjs.org/package/cross-spawn
[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg
[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn
[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn
[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg
[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn
[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg
[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev
[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg
[greenkeeper-image]:https://badges.greenkeeper.io/moxystudio/node-cross-spawn.svg
[greenkeeper-url]:https://greenkeeper.io/
A cross platform solution to node's spawn and spawnSync.
## Installation
`$ npm install cross-spawn`
## Why
Node has issues when using spawn on Windows:
- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix))
- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367)
- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`)
- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149)
- No `options.shell` support on node `<v4.8`
All these issues are handled correctly by `cross-spawn`.
There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments.
## Usage
Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement.
```js
const spawn = require('cross-spawn');
// Spawn NPM asynchronously
const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
// Spawn NPM synchronously
const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```
## Caveats
### Using `options.shell` as an alternative to `cross-spawn`
Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves
the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but:
- It's not supported in node `<v4.8`
- You must manually escape the command and arguments which is very error prone, specially when passing user input
- There are a lot of other unresolved issues from the [Why](#why) section that you must take into account
If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned.
### `options.shell` support
While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled.
This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
### Shebangs support
While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
If you would like to have the shebang support improved, feel free to contribute via a pull-request.
Remember to always test your code on Windows!
## Tests
`$ npm test`
`$ npm test -- --watch` during development
## License
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
@@ -0,0 +1,39 @@
'use strict';
const cp = require('child_process');
const parse = require('./lib/parse');
const enoent = require('./lib/enoent');
function spawn(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
// Hook into child process "exit" event to emit an error if the command
// does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
// Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
module.exports = spawn;
module.exports.spawn = spawn;
module.exports.sync = spawnSync;
module.exports._parse = parse;
module.exports._enoent = enoent;
@@ -0,0 +1,59 @@
'use strict';
const isWin = process.platform === 'win32';
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: 'ENOENT',
errno: 'ENOENT',
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args,
});
}
function hookChildProcess(cp, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp.emit;
cp.emit = function (name, arg1) {
// If emitting "exit" event and exit code is 1, we need to check if
// the command exists and emit an "error" instead
// See https://github.com/IndigoUnited/node-cross-spawn/issues/16
if (name === 'exit') {
const err = verifyENOENT(arg1, parsed, 'spawn');
if (err) {
return originalEmit.call(cp, 'error', err);
}
}
return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
};
}
function verifyENOENT(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawn');
}
return null;
}
function verifyENOENTSync(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawnSync');
}
return null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError,
};
@@ -0,0 +1,125 @@
'use strict';
const path = require('path');
const niceTry = require('nice-try');
const resolveCommand = require('./util/resolveCommand');
const escape = require('./util/escape');
const readShebang = require('./util/readShebang');
const semver = require('semver');
const isWin = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0
const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
// Detect & add support for shebangs
const commandFile = detectShebang(parsed);
// We don't need a shell if the command filename is an executable
const needsShell = !isExecutableRegExp.test(commandFile);
// If a shell is required, use cmd.exe and take care of escaping everything correctly
// Note that `forceShell` is an hidden option used only in tests
if (parsed.options.forceShell || needsShell) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
parsed.command = path.normalize(parsed.command);
// Escape command & arguments
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(' ');
parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.command = process.env.comspec || 'cmd.exe';
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
}
return parsed;
}
function parseShell(parsed) {
// If node supports the shell option, there's no need to mimic its behavior
if (supportsShellOption) {
return parsed;
}
// Mimic node shell option
// See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335
const shellCommand = [parsed.command].concat(parsed.args).join(' ');
if (isWin) {
parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe';
parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
} else {
if (typeof parsed.options.shell === 'string') {
parsed.command = parsed.options.shell;
} else if (process.platform === 'android') {
parsed.command = '/system/bin/sh';
} else {
parsed.command = '/bin/sh';
}
parsed.args = ['-c', shellCommand];
}
return parsed;
}
function parse(command, args, options) {
// Normalize arguments, similar to nodejs
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : []; // Clone array to avoid changing the original
options = Object.assign({}, options); // Clone object to avoid changing the original
// Build our parsed object
const parsed = {
command,
args,
options,
file: undefined,
original: {
command,
args,
},
};
// Delegate further parsing to shell or non-shell
return options.shell ? parseShell(parsed) : parseNonShell(parsed);
}
module.exports = parse;
@@ -0,0 +1,47 @@
'use strict';
// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
// Convert to string
arg = `${arg}`;
// Algorithm below is based on https://qntm.org/cmd
// It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
// Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information
// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
// All other backslashes occur literally
// Quote the whole thing:
arg = `"${arg}"`;
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
// Double escape meta chars if necessary
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}
return arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
@@ -0,0 +1,32 @@
'use strict';
const fs = require('fs');
const shebangCommand = require('shebang-command');
function readShebang(command) {
// Read the first 150 bytes from the file
const size = 150;
let buffer;
if (Buffer.alloc) {
// Node.js v4.5+ / v5.10+
buffer = Buffer.alloc(size);
} else {
// Old Node.js API
buffer = new Buffer(size);
buffer.fill(0); // zero-fill
}
let fd;
try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }
// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
@@ -0,0 +1,51 @@
'use strict';
const path = require('path');
const which = require('which');
const pathKey = require('path-key')();
function resolveCommandAttempt(parsed, withoutPathExt) {
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: (parsed.options.env || process.env)[pathKey],
pathExt: withoutPathExt ? path.delimiter : undefined,
});
} catch (e) {
/* Empty */
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;
@@ -0,0 +1,75 @@
{
"name": "cross-spawn",
"version": "6.0.6",
"description": "Cross platform child_process#spawn and child_process#spawnSync",
"keywords": [
"spawn",
"spawnSync",
"windows",
"cross-platform",
"path-ext",
"shebang",
"cmd",
"execute"
],
"author": "André Cruz <andre@moxy.studio>",
"homepage": "https://github.com/moxystudio/node-cross-spawn",
"repository": {
"type": "git",
"url": "git@github.com:moxystudio/node-cross-spawn.git"
},
"license": "MIT",
"main": "index.js",
"files": [
"lib"
],
"scripts": {
"lint": "eslint .",
"test": "jest --env node --coverage",
"release": "standard-version",
"precommit": "lint-staged",
"commitmsg": "commitlint -e $GIT_PARAMS"
},
"standard-version": {
"scripts": {
"posttag": "git push --follow-tags origin v6"
}
},
"lint-staged": {
"*.js": [
"eslint --fix",
"git add"
]
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"dependencies": {
"nice-try": "^1.0.4",
"path-key": "^2.0.1",
"semver": "^5.5.0",
"shebang-command": "^1.2.0",
"which": "^1.2.9"
},
"devDependencies": {
"@commitlint/cli": "^6.0.0",
"@commitlint/config-conventional": "^6.0.2",
"babel-core": "^6.26.0",
"babel-jest": "^22.1.0",
"babel-preset-moxy": "^2.2.1",
"eslint": "^4.3.0",
"eslint-config-moxy": "^5.0.0",
"husky": "^0.14.3",
"jest": "^22.0.0",
"lint-staged": "^7.0.0",
"mkdirp": "^0.5.1",
"regenerator-runtime": "^0.11.1",
"rimraf": "^2.6.2",
"standard-version": "^4.2.0"
},
"engines": {
"node": ">=4.8"
}
}
@@ -0,0 +1,20 @@
Copyright Mathias Bynens <https://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+201
View File
@@ -0,0 +1,201 @@
# cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc)
A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.
This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Heres an online demo.](https://mothereff.in/css-escapes)
[A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.)
Feel free to fork if you see possible improvements!
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install cssesc
```
In a browser:
```html
<script src="cssesc.js"></script>
```
In [Node.js](https://nodejs.org/):
```js
const cssesc = require('cssesc');
```
In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc):
```bash
gem install ruby-cssesc
```
```ruby
require 'ruby-cssesc'
CSSEsc.escape('I ♥ Ruby', is_identifier: true)
```
In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape):
```bash
gem install sassy-escape
```
```scss
body {
content: escape('I ♥ Sass', $is-identifier: true);
}
```
## API
### `cssesc(value, options)`
This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes).
```js
cssesc('Ich ♥ Bücher');
// → 'Ich \\2665 B\\FC cher'
cssesc('foo 𝌆 bar');
// → 'foo \\1D306 bar'
```
By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below).
The optional `options` argument accepts an object with the following options:
#### `isIdentifier`
The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`.
```js
cssesc('123a2b');
// → '123a2b'
cssesc('123a2b', {
'isIdentifier': true
});
// → '\\31 23a2b'
```
#### `quotes`
The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.');
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single'
});
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
```
If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double'
});
// → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.'
// → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc."
```
#### `wrap`
The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single',
'wrap': true
});
// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double',
'wrap': true
});
// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
```
#### `escapeEverything`
The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols.
```js
cssesc('lolwat"foo\'bar', {
'escapeEverything': true
});
// → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72'
// → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72"
```
#### Overriding the default options globally
The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting.
```js
// Read the global default setting for `escapeEverything`:
cssesc.options.escapeEverything;
// → `false` by default
// Override the global default setting for `escapeEverything`:
cssesc.options.escapeEverything = true;
// Using the global default setting for `escapeEverything`, which is now `true`:
cssesc('foo © bar ≠ baz 𝌆 qux');
// → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78'
```
### `cssesc.version`
A string representing the semantic version number.
### Using the `cssesc` binary
To use the `cssesc` binary in your shell, simply install cssesc globally using npm:
```bash
npm install -g cssesc
```
After that you will be able to escape text for use in CSS strings or identifiers from the command line:
```bash
$ cssesc 'föo ♥ bår 𝌆 baz'
f\F6o \2665 b\E5r \1D306 baz
```
If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option:
```bash
$ cssesc --identifier 'föo ♥ bår 𝌆 baz'
f\F6o\ \2665\ b\E5r\ \1D306\ baz
```
See `cssesc --help` for the full list of options.
## Support
This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0).
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
This library is available under the [MIT](https://mths.be/mit) license.
@@ -0,0 +1,116 @@
#!/usr/bin/env node
const fs = require('fs');
const cssesc = require('../cssesc.js');
const strings = process.argv.splice(2);
const stdin = process.stdin;
const options = {};
const log = console.log;
const main = function() {
const option = strings[0];
if (/^(?:-h|--help|undefined)$/.test(option)) {
log(
'cssesc v%s - https://mths.be/cssesc',
cssesc.version
);
log([
'\nUsage:\n',
'\tcssesc [string]',
'\tcssesc [-i | --identifier] [string]',
'\tcssesc [-s | --single-quotes] [string]',
'\tcssesc [-d | --double-quotes] [string]',
'\tcssesc [-w | --wrap] [string]',
'\tcssesc [-e | --escape-everything] [string]',
'\tcssesc [-v | --version]',
'\tcssesc [-h | --help]',
'\nExamples:\n',
'\tcssesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --identifier \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | cssesc'
].join('\n'));
return process.exit(1);
}
if (/^(?:-v|--version)$/.test(option)) {
log('v%s', cssesc.version);
return process.exit(1);
}
strings.forEach(function(string) {
// Process options
if (/^(?:-i|--identifier)$/.test(string)) {
options.isIdentifier = true;
return;
}
if (/^(?:-s|--single-quotes)$/.test(string)) {
options.quotes = 'single';
return;
}
if (/^(?:-d|--double-quotes)$/.test(string)) {
options.quotes = 'double';
return;
}
if (/^(?:-w|--wrap)$/.test(string)) {
options.wrap = true;
return;
}
if (/^(?:-e|--escape-everything)$/.test(string)) {
options.escapeEverything = true;
return;
}
// Process string(s)
let result;
try {
result = cssesc(string, options);
log(result);
} catch (exception) {
log(exception.message + '\n');
log('Error: failed to escape.');
log('If you think this is a bug in cssesc, please report it:');
log('https://github.com/mathiasbynens/cssesc/issues/new');
log(
'\nStack trace using cssesc@%s:\n',
cssesc.version
);
log(exception.stack);
return process.exit(1);
}
});
// Return with exit status 0 outside of the `forEach` loop, in case
// multiple strings were passed in.
return process.exit(0);
};
if (stdin.isTTY) {
// handle shell arguments
main();
} else {
let timeout;
// Either the script is called from within a non-TTY context, or `stdin`
// content is being piped in.
if (!process.stdout.isTTY) {
// The script was called from a non-TTY context. This is a rather uncommon
// use case we dont actively support. However, we dont want the script
// to wait forever in such cases, so…
timeout = setTimeout(function() {
// …if no piped data arrived after a whole minute, handle shell
// arguments instead.
main();
}, 60000);
}
let data = '';
stdin.on('data', function(chunk) {
clearTimeout(timeout);
data += chunk;
});
stdin.on('end', function() {
strings.push(data.trim());
main();
});
stdin.resume();
}
+119
View File
@@ -0,0 +1,119 @@
/*! https://mths.be/cssesc v1.0.1 by @mathias */
'use strict';
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var merge = function merge(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
for (var key in defaults) {
// `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
// only recognized option names are used.
result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
}
return result;
};
var regexAnySingleEscape = /[ -,\.\/;-@\[-\^`\{-~]/;
var regexSingleEscape = /[ -,\.\/;-@\[\]\^`\{-~]/;
var regexAlwaysEscape = /['"\\]/;
var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
// https://mathiasbynens.be/notes/css-escapes#css
var cssesc = function cssesc(string, options) {
options = merge(options, cssesc.options);
if (options.quotes != 'single' && options.quotes != 'double') {
options.quotes = 'single';
}
var quote = options.quotes == 'double' ? '"' : '\'';
var isIdentifier = options.isIdentifier;
var firstChar = string.charAt(0);
var output = '';
var counter = 0;
var length = string.length;
while (counter < length) {
var character = string.charAt(counter++);
var codePoint = character.charCodeAt();
var value = void 0;
// If its not a printable ASCII character…
if (codePoint < 0x20 || codePoint > 0x7E) {
if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
// Its a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// next character is low surrogate
codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
} else {
// Its an unmatched surrogate; only append this code unit, in case
// the next code unit is the high surrogate of a surrogate pair.
counter--;
}
}
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
} else {
if (options.escapeEverything) {
if (regexAnySingleEscape.test(character)) {
value = '\\' + character;
} else {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
}
// Note: `:` could be escaped as `\:`, but that fails in IE < 8.
} else if (/[\t\n\f\r\x0B:]/.test(character)) {
if (!isIdentifier && character == ':') {
value = character;
} else {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
}
} else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
value = '\\' + character;
} else {
value = character;
}
}
output += value;
}
if (isIdentifier) {
if (/^_/.test(output)) {
// Prevent IE6 from ignoring the rule altogether (in case this is for an
// identifier used as a selector)
output = '\\_' + output.slice(1);
} else if (/^-[-\d]/.test(output)) {
output = '\\-' + output.slice(1);
} else if (/\d/.test(firstChar)) {
output = '\\3' + firstChar + ' ' + output.slice(1);
}
}
// Remove spaces after `\HEX` escapes that are not followed by a hex digit,
// since theyre redundant. Note that this is only possible if the escape
// sequence isnt preceded by an odd number of backslashes.
output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
if ($1 && $1.length % 2) {
// Its not safe to remove the space, so dont.
return $0;
}
// Strip the space.
return ($1 || '') + $2;
});
if (!isIdentifier && options.wrap) {
return quote + output + quote;
}
return output;
};
// Expose default options (so they can be overridden globally).
cssesc.options = {
'escapeEverything': false,
'isIdentifier': false,
'quotes': 'single',
'wrap': false
};
cssesc.version = '1.0.1';
module.exports = cssesc;
@@ -0,0 +1,70 @@
.Dd August 9, 2013
.Dt cssesc 1
.Sh NAME
.Nm cssesc
.Nd escape text for use in CSS string literals or identifiers
.Sh SYNOPSIS
.Nm
.Op Fl i | -identifier Ar string
.br
.Op Fl s | -single-quotes Ar string
.br
.Op Fl d | -double-quotes Ar string
.br
.Op Fl w | -wrap Ar string
.br
.Op Fl e | -escape-everything Ar string
.br
.Op Fl v | -version
.br
.Op Fl h | -help
.Sh DESCRIPTION
.Nm
escapes strings for use in CSS string literals or identifiers while generating the shortest possible valid ASCII-only output.
.Sh OPTIONS
.Bl -ohang -offset
.It Sy "-s, --single-quotes"
Escape any occurences of ' in the input string as \\', so that the output can be used in a CSS string literal wrapped in single quotes.
.It Sy "-d, --double-quotes"
Escape any occurences of " in the input string as \\", so that the output can be used in a CSS string literal wrapped in double quotes.
.It Sy "-w, --wrap"
Make sure the output is a valid CSS string literal wrapped in quotes. The type of quotes can be specified using the
.Ar -s | --single-quotes
or
.Ar -d | --double-quotes
settings.
.It Sy "-e, --escape-everything"
Escape all the symbols in the output, even printable ASCII symbols.
.It Sy "-v, --version"
Print cssesc's version.
.It Sy "-h, --help"
Show the help screen.
.El
.Sh EXIT STATUS
The
.Nm cssesc
utility exits with one of the following values:
.Pp
.Bl -tag -width flag -compact
.It Li 0
.Nm
successfully escaped the given text and printed the result.
.It Li 1
.Nm
wasn't instructed to escape anything (for example, the
.Ar --help
flag was set); or, an error occurred.
.El
.Sh EXAMPLES
.Bl -ohang -offset
.It Sy "cssesc 'foo bar baz'"
Print an escaped version of the given text.
.It Sy echo\ 'foo bar baz'\ |\ cssesc
Print an escaped version of the text that gets piped in.
.El
.Sh BUGS
cssesc's bug tracker is located at <https://github.com/mathiasbynens/cssesc/issues>.
.Sh AUTHOR
Mathias Bynens <https://mathiasbynens.be/>
.Sh WWW
<https://mths.be/cssesc>
@@ -0,0 +1,51 @@
{
"name": "cssesc",
"version": "2.0.0",
"description": "A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.",
"homepage": "https://mths.be/cssesc",
"engines": {
"node": ">=4"
},
"main": "cssesc.js",
"bin": "bin/cssesc",
"man": "man/cssesc.1",
"keywords": [
"css",
"escape",
"identifier",
"string",
"tool"
],
"license": "MIT",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"repository": {
"type": "git",
"url": "https://github.com/mathiasbynens/cssesc.git"
},
"bugs": "https://github.com/mathiasbynens/cssesc/issues",
"files": [
"LICENSE-MIT.txt",
"cssesc.js",
"bin/",
"man/"
],
"scripts": {
"build": "grunt template && babel cssesc.js -o cssesc.js",
"test": "mocha tests",
"cover": "istanbul cover --report html node_modules/.bin/_mocha tests -- -u exports -R spec"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"codecov": "^1.0.1",
"grunt": "^1.0.1",
"grunt-template": "^1.0.0",
"istanbul": "^0.4.4",
"mocha": "^2.5.3",
"regenerate": "^1.2.1",
"requirejs": "^2.1.16"
}
}
@@ -0,0 +1,13 @@
'use strict';
module.exports = opts => {
opts = opts || {};
const env = opts.env || process.env;
const platform = opts.platform || process.platform;
if (platform !== 'win32') {
return 'PATH';
}
return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path';
};
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,39 @@
{
"name": "path-key",
"version": "2.0.1",
"description": "Get the PATH environment variable key cross-platform",
"license": "MIT",
"repository": "sindresorhus/path-key",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"path",
"key",
"environment",
"env",
"variable",
"var",
"get",
"cross-platform",
"windows"
],
"devDependencies": {
"ava": "*",
"xo": "*"
},
"xo": {
"esnext": true
}
}
@@ -0,0 +1,51 @@
# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key)
> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform
It's usually `PATH`, but on Windows it can be any casing like `Path`...
## Install
```
$ npm install --save path-key
```
## Usage
```js
const pathKey = require('path-key');
const key = pathKey();
//=> 'PATH'
const PATH = process.env[key];
//=> '/usr/local/bin:/usr/bin:/bin'
```
## API
### pathKey([options])
#### options
##### env
Type: `Object`<br>
Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env)
Use a custom environment variables object.
#### platform
Type: `string`<br>
Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform)
Get the PATH key for a specific platform.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
@@ -0,0 +1,873 @@
# API Documentation
*Please use only this documented API when working with the parser. Methods
not documented here are subject to change at any point.*
## `parser` function
This is the module's main entry point.
```js
const parser = require('postcss-selector-parser');
```
### `parser([transform], [options])`
Creates a new `processor` instance
```js
const processor = parser();
```
Or, with optional transform function
```js
const transform = selectors => {
selectors.walkUniversals(selector => {
selector.remove();
});
};
const processor = parser(transform)
// Example
const result = processor.processSync('*.class');
// => .class
```
[See processor documentation](#processor)
Arguments:
* `transform (function)`: Provide a function to work with the parsed AST.
* `options (object)`: Provide default options for all calls on the returned `Processor`.
### `parser.attribute([props])`
Creates a new attribute selector.
```js
parser.attribute({attribute: 'href'});
// => [href]
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.className([props])`
Creates a new class selector.
```js
parser.className({value: 'button'});
// => .button
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.combinator([props])`
Creates a new selector combinator.
```js
parser.combinator({value: '+'});
// => +
```
Arguments:
* `props (object)`: The new node's properties.
Notes:
* **Descendant Combinators** The value of descendant combinators created by the
parser always just a single space (`" "`). For descendant selectors with no
comments, additional space is now stored in `node.spaces.before`. Depending
on the location of comments, additional spaces may be stored in
`node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`.
* **Named Combinators** Although, nonstandard and unlikely to ever become a standard,
named combinators like `/deep/` and `/for/` are parsed as combinators. The
`node.value` is name after being unescaped and normalized as lowercase. The
original value for the combinator name is stored in `node.raws.value`.
### `parser.comment([props])`
Creates a new comment.
```js
parser.comment({value: '/* Affirmative, Dave. I read you. */'});
// => /* Affirmative, Dave. I read you. */
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.id([props])`
Creates a new id selector.
```js
parser.id({value: 'search'});
// => #search
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.nesting([props])`
Creates a new nesting selector.
```js
parser.nesting();
// => &
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.pseudo([props])`
Creates a new pseudo selector.
```js
parser.pseudo({value: '::before'});
// => ::before
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.root([props])`
Creates a new root node.
```js
parser.root();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.selector([props])`
Creates a new selector node.
```js
parser.selector();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.string([props])`
Creates a new string node.
```js
parser.string();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.tag([props])`
Creates a new tag selector.
```js
parser.tag({value: 'button'});
// => button
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.universal([props])`
Creates a new universal selector.
```js
parser.universal();
// => *
```
Arguments:
* `props (object)`: The new node's properties.
## Node types
### `node.type`
A string representation of the selector type. It can be one of the following;
`attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`,
`root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience,
these constants are exposed on the main `parser` as uppercased keys. So for
example you can get `id` by querying `parser.ID`.
```js
parser.attribute({attribute: 'href'}).type;
// => 'attribute'
```
### `node.parent`
Returns the parent node.
```js
root.nodes[0].parent === root;
```
### `node.toString()`, `String(node)`, or `'' + node`
Returns a string representation of the node.
```js
const id = parser.id({value: 'search'});
console.log(String(id));
// => #search
```
### `node.next()` & `node.prev()`
Returns the next/previous child of the parent node.
```js
const next = id.next();
if (next && next.type !== 'combinator') {
throw new Error('Qualified IDs are not allowed!');
}
```
### `node.replaceWith(node)`
Replace a node with another.
```js
const attr = selectors.first.first;
const className = parser.className({value: 'test'});
attr.replaceWith(className);
```
Arguments:
* `node`: The node to substitute the original with.
### `node.remove()`
Removes the node from its parent node.
```js
if (node.type === 'id') {
node.remove();
}
```
### `node.clone()`
Returns a copy of a node, detached from any parent containers that the
original might have had.
```js
const cloned = parser.id({value: 'search'});
String(cloned);
// => #search
```
### `node.isAtPosition(line, column)`
Return a `boolean` indicating whether this node includes the character at the
position of the given line and column. Returns `undefined` if the nodes lack
sufficient source metadata to determine the position.
Arguments:
* `line`: 1-index based line number relative to the start of the selector.
* `column`: 1-index based column number relative to the start of the selector.
### `node.spaces`
Extra whitespaces around the node will be moved into `node.spaces.before` and
`node.spaces.after`. So for example, these spaces will be moved as they have
no semantic meaning:
```css
h1 , h2 {}
```
For descendent selectors, the value is always a single space.
```css
h1 h2 {}
```
Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source.
### `node.source`
An object describing the node's start/end, line/column source position.
Within the following CSS, the `.bar` class node ...
```css
.foo,
.bar {}
```
... will contain the following `source` object.
```js
source: {
start: {
line: 2,
column: 3
},
end: {
line: 2,
column: 6
}
}
```
### `node.sourceIndex`
The zero-based index of the node within the original source string.
Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`.
```css
.foo, .bar, .baz {}
```
## Container types
The `root`, `selector`, and `pseudo` nodes have some helper methods for working
with their children.
### `container.nodes`
An array of the container's children.
```js
// Input: h1 h2
selectors.at(0).nodes.length // => 3
selectors.at(0).nodes[0].value // => 'h1'
selectors.at(0).nodes[1].value // => ' '
```
### `container.first` & `container.last`
The first/last child of the container.
```js
selector.first === selector.nodes[0];
selector.last === selector.nodes[selector.nodes.length - 1];
```
### `container.at(index)`
Returns the node at position `index`.
```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```
Arguments:
* `index`: The index of the node to return.
### `container.atPosition(line, column)`
Returns the node at the source position `index`.
```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```
Arguments:
* `index`: The index of the node to return.
### `container.index(node)`
Return the index of the node within its container.
```js
selector.index(selector.nodes[2]) // => 2
```
Arguments:
* `node`: A node within the current container.
### `container.length`
Proxy to the length of the container's nodes.
```js
container.length === container.nodes.length
```
### `container` Array iterators
The container class provides proxies to certain Array methods; these are:
* `container.map === container.nodes.map`
* `container.reduce === container.nodes.reduce`
* `container.every === container.nodes.every`
* `container.some === container.nodes.some`
* `container.filter === container.nodes.filter`
* `container.sort === container.nodes.sort`
Note that these methods only work on a container's immediate children; recursive
iteration is provided by `container.walk`.
### `container.each(callback)`
Iterate the container's immediate children, calling `callback` for each child.
You may return `false` within the callback to break the iteration.
```js
let className;
selectors.each((selector, index) => {
if (selector.type === 'class') {
className = selector.value;
return false;
}
});
```
Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding
or removing nodes from the container.
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
and `index` arguments.
### `container.walk(callback)`
Like `container#each`, but will also iterate child nodes as long as they are
`container` types.
```js
selectors.walk((selector, index) => {
// all nodes
});
```
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
and `index` arguments.
This iterator is safe to use whilst mutating `container.nodes`,
like `container#each`.
### `container.walk` proxies
The container class provides proxy methods for iterating over types of nodes,
so that it is easier to write modules that target specific selectors. Those
methods are:
* `container.walkAttributes`
* `container.walkClasses`
* `container.walkCombinators`
* `container.walkComments`
* `container.walkIds`
* `container.walkNesting`
* `container.walkPseudos`
* `container.walkTags`
* `container.walkUniversals`
### `container.split(callback)`
This method allows you to split a group of nodes by returning `true` from
a callback. It returns an array of arrays, where each inner array corresponds
to the groups that you created via the callback.
```js
// (input) => h1 h2>>h3
const list = selectors.first.split(selector => {
return selector.type === 'combinator';
});
// (node values) => [['h1', ' '], ['h2', '>>'], ['h3']]
```
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
as an argument.
### `container.prepend(node)` & `container.append(node)`
Add a node to the start/end of the container. Note that doing so will set
the parent property of the node to this container.
```js
const id = parser.id({value: 'search'});
selector.append(id);
```
Arguments:
* `node`: The node to add.
### `container.insertBefore(old, new)` & `container.insertAfter(old, new)`
Add a node before or after an existing node in a container:
```js
selectors.walk(selector => {
if (selector.type !== 'class') {
const className = parser.className({value: 'theme-name'});
selector.parent.insertAfter(selector, className);
}
});
```
Arguments:
* `old`: The existing node in the container.
* `new`: The new node to add before/after the existing node.
### `container.removeChild(node)`
Remove the node from the container. Note that you can also use
`node.remove()` if you would like to remove just a single node.
```js
selector.length // => 2
selector.remove(id)
selector.length // => 1;
id.parent // undefined
```
Arguments:
* `node`: The node to remove.
### `container.removeAll()` or `container.empty()`
Remove all children from the container.
```js
selector.removeAll();
selector.length // => 0
```
## Root nodes
A root node represents a comma separated list of selectors. Indeed, all
a root's `toString()` method does is join its selector children with a ','.
Other than this, it has no special functionality and acts like a container.
### `root.trailingComma`
This will be set to `true` if the input has a trailing comma, in order to
support parsing of legacy CSS hacks.
## Selector nodes
A selector node represents a single complex selector. For example, this
selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes.
It has no special functionality of its own.
## Pseudo nodes
A pseudo selector extends a container node; if it has any parameters of its
own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo
`value` will always contain the colons preceding the pseudo identifier. This
is so that both `:before` and `::before` are properly represented in the AST.
## Attribute nodes
### `attribute.quoted`
Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not.
Remains `undefined` if there is no attribute value.
```css
[href=foo] /* false */
[href='foo'] /* true */
[href="foo"] /* true */
[href] /* undefined */
```
### `attribute.qualifiedAttribute`
Returns the attribute name qualified with the namespace if one is given.
### `attribute.offsetOf(part)`
Returns the offset of the attribute part specified relative to the
start of the node of the output string. This is useful in raising
error messages about a specific part of the attribute, especially
in combination with `attribute.sourceIndex`.
Returns `-1` if the name is invalid or the value doesn't exist in this
attribute.
The legal values for `part` are:
* `"ns"` - alias for "namespace"
* `"namespace"` - the namespace if it exists.
* `"attribute"` - the attribute name
* `"attributeNS"` - the start of the attribute or its namespace
* `"operator"` - the match operator of the attribute
* `"value"` - The value (string or identifier)
* `"insensitive"` - the case insensitivity flag
### `attribute.raws.unquoted`
Returns the unquoted content of the attribute's value.
Remains `undefined` if there is no attribute value.
```css
[href=foo] /* foo */
[href='foo'] /* foo */
[href="foo"] /* foo */
[href] /* undefined */
```
### `attribute.spaces`
Like `node.spaces` with the `before` and `after` values containing the spaces
around the element, the parts of the attribute can also have spaces before
and after them. The for each of `attribute`, `operator`, `value` and
`insensitive` there is corresponding property of the same nam in
`node.spaces` that has an optional `before` or `after` string containing only
whitespace.
Note that corresponding values in `attributes.raws.spaces` contain values
including any comments. If set, these values will override the
`attribute.spaces` value. Take care to remove them if changing
`attribute.spaces`.
### `attribute.raws`
The raws object stores comments and other information necessary to re-render
the node exactly as it was in the source.
If a comment is embedded within the identifiers for the `namespace`, `attribute`
or `value` then a property is placed in the raws for that value containing the full source of the propery including comments.
If a comment is embedded within the space between parts of the attribute
then the raw for that space is set accordingly.
Setting an attribute's property `raws` value to be deleted.
For now, changing the spaces required also updating or removing any of the
raws values that override them.
Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as:
```js
{
attribute: "href",
operatator: "=",
value: "test",
spaces: {
before: '',
after: '',
attribute: { before: ' ', after: ' ' },
operator: { after: ' ' },
value: { after: ' ' },
insensitive: { after: ' ' }
},
raws: {
spaces: {
attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' },
operator: { after: ' /* after-operator */ ' },
value: { after: '/* wow */ /*omg*/' },
insensitive: { after: '/*bbq*/ /*whodoesthis*/' }
},
unquoted: 'test',
value: 'te/*inside-value*/st'
}
}
```
## `Processor`
### `ProcessorOptions`
* `lossless` - When `true`, whitespace is preserved. Defaults to `true`.
* `updateSelector` - When `true`, if any processor methods are passed a postcss
`Rule` node instead of a string, then that Rule's selector is updated
with the results of the processing. Defaults to `true`.
### `process|processSync(selectors, [options])`
Processes the `selectors`, returning a string from the result of processing.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
**Example:**
```js
const parser = require("postcss-selector-parser");
const processor = parser();
let result = processor.processSync(' .class');
console.log(result);
// => .class
// Asynchronous operation
let promise = processor.process(' .class').then(result => {
console.log(result)
// => .class
});
// To have the parser normalize whitespace values, utilize the options
result = processor.processSync(' .class ', {lossless: false});
console.log(result);
// => .class
// For better syntax errors, pass a PostCSS Rule node.
const postcss = require('postcss');
rule = postcss.rule({selector: ' #foo > a, .class '});
processor.process(rule, {lossless: false, updateSelector: true}).then(result => {
console.log(result);
// => #foo>a,.class
console.log("rule:", rule.selector);
// => rule: #foo>a,.class
})
```
Arguments:
* `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule
node.
* `[options] (object)`: Process options
### `ast|astSync(selectors, [options])`
Like `process()` and `processSync()` but after
processing the `selectors` these methods return the `Root` node of the result
instead of a string.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
### `transform|transformSync(selectors, [options])`
Like `process()` and `processSync()` but after
processing the `selectors` these methods return the value returned by the
processor callback.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
### Error Handling Within Selector Processors
The root node passed to the selector processor callback
has a method `error(message, options)` that returns an
error object. This method should always be used to raise
errors relating to the syntax of selectors. The options
to this method are passed to postcss's error constructor
([documentation](http://api.postcss.org/Container.html#error)).
#### Async Error Example
```js
let processor = (root) => {
return new Promise((resolve, reject) => {
root.walkClasses((classNode) => {
if (/^(.*)[-_]/.test(classNode.value)) {
let msg = "classes may not have underscores or dashes in them";
reject(root.error(msg, {
index: classNode.sourceIndex + RegExp.$1.length + 1,
word: classNode.value
}));
}
});
resolve();
});
};
const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
return (root) => {
let promises = [];
root.walkRules(rule => {
promises.push(selectorProcessor.process(rule));
});
return Promise.all(promises);
};
});
postcss(plugin()).process(`
.foo-bar {
color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
// | ^
// 2 | color: red;
// 3 | }
```
#### Synchronous Error Example
```js
let processor = (root) => {
root.walkClasses((classNode) => {
if (/.*[-_]/.test(classNode.value)) {
let msg = "classes may not have underscores or dashes in them";
throw root.error(msg, {
index: classNode.sourceIndex,
word: classNode.value
});
}
});
};
const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
return (root) => {
root.walkRules(rule => {
selectorProcessor.processSync(rule);
});
};
});
postcss(plugin()).process(`
.foo-bar {
color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
// | ^
// 2 | color: red;
// 3 | }
```
@@ -0,0 +1,466 @@
# 5.0.0
- Allow escaped dot within class name.
- Update PostCSS to 7.0.7 (patch)
# 5.0.0-rc.4
- Fixed and issue where comments immediately after an insensitive
(in attribute) were not parsed correctly.
- Updated `cssesc` to 2.0.0 (major).
- Removed outdated integration tests.
- Added tests for custom selectors, tags with attributes, the universal
selector with pseudos, and tokens after combinators.
# 5.0.0-rc.1
To ease adoption of the v5.0 release, we have relaxed the node version
check performed by npm at installation time to allow for node 4, which
remains officially unsupported, but likely to continue working for the
time being.
# 5.0.0-rc.0
This release has **BREAKING CHANGES** that were required to fix regressions
in 4.0.0 and to make the Combinator Node API consistent for all combinator
types. Please read carefully.
## Summary of Changes
* The way a descendent combinator that isn't a single space character (E.g. `.a .b`) is stored in the AST has changed.
* Named Combinators (E.g. `.a /for/ .b`) are now properly parsed as a combinator.
* It is now possible to look up a node based on the source location of a character in that node and to query nodes if they contain some character.
* Several bug fixes that caused the parser to hang and run out of memory when a `/` was encountered have been fixed.
* The minimum supported version of Node is now `v6.0.0`.
### Changes to the Descendent Combinator
In prior releases, the value of a descendant combinator with multiple spaces included all the spaces.
* `.a .b`: Extra spaces are now stored as space before.
- Old & Busted:
- `combinator.value === " "`
- New hotness:
- `combinator.value === " " && combinator.spaces.before === " "`
* `.a /*comment*/.b`: A comment at the end of the combinator causes extra space to become after space.
- Old & Busted:
- `combinator.value === " "`
- `combinator.raws.value === " /*comment/"`
- New hotness:
- `combinator.value === " "`
- `combinator.spaces.after === " "`
- `combinator.raws.spaces.after === " /*comment*/"`
* `.a<newline>.b`: whitespace that doesn't start or end with a single space character is stored as a raw value.
- Old & Busted:
- `combinator.value === "\n"`
- `combinator.raws.value === undefined`
- New hotness:
- `combinator.value === " "`
- `combinator.raws.value === "\n"`
### Support for "Named Combinators"
Although, nonstandard and unlikely to ever become a standard, combinators like `/deep/` and `/for/` are now properly supported.
Because they've been taken off the standardization track, there is no spec-official name for combinators of the form `/<ident>/`. However, I talked to [Tab Atkins](https://twitter.com/tabatkins) and we agreed to call them "named combinators" so now they are called that.
Before this release such named combinators were parsed without intention and generated three nodes of type `"tag"` where the first and last nodes had a value of `"/"`.
* `.a /for/ .b` is parsed as a combinator.
- Old & Busted:
- `root.nodes[0].nodes[1].type === "tag"`
- `root.nodes[0].nodes[1].value === "/"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
* `.a /F\6fR/ .b` escapes are handled and uppercase is normalized.
- Old & Busted:
- `root.nodes[0].nodes[2].type === "tag"`
- `root.nodes[0].nodes[2].value === "F\\6fR"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
- `root.nodes[0].nodes[1].raws.value === "/F\\6fR/"`
### Source position checks and lookups
A new API was added to look up a node based on the source location.
```js
const selectorParser = require("postcss-selector-parser");
// You can find the most specific node for any given character
let combinator = selectorParser.astSync(".a > .b").atPosition(1,4);
combinator.toString() === " > ";
// You can check if a node includes a specific character
// Whitespace surrounding the node that is owned by that node
// is included in the check.
[2,3,4,5,6].map(column => combinator.isAtPosition(1, column));
// => [false, true, true, true, false]
```
# 4.0.0
This release has **BREAKING CHANGES** that were required to fix bugs regarding values with escape sequences. Please read carefully.
* **Identifiers with escapes** - CSS escape sequences are now hidden from the public API by default.
The normal value of a node like a class name or ID, or an aspect of a node such as attribute
selector's value, is unescaped. Escapes representing Non-ascii characters are unescaped into
unicode characters. For example: `bu\tton, .\31 00, #i\2764\FE0Fu, [attr="value is \"quoted\""]`
will parse respectively to the values `button`, `100`, `i❤️u`, `value is "quoted"`.
The original escape sequences for these values can be found in the corresponding property name
in `node.raws`. Where possible, deprecation warnings were added, but the nature
of escape handling makes it impossible to detect what is escaped or not. Our expectation is
that most users are neither expecting nor handling escape sequences in their use of this library,
and so for them, this is a bug fix. Users who are taking care to handle escapes correctly can
now update their code to remove the escape handling and let us do it for them.
* **Mutating values with escapes** - When you make an update to a node property that has escape handling
The value is assumed to be unescaped, and any special characters are escaped automatically and
the corresponding `raws` value is immediately updated. This can result in changes to the original
escape format. Where the exact value of the escape sequence is important there are methods that
allow both values to be set in conjunction. There are a number of new convenience methods for
manipulating values that involve escapes, especially for attributes values where the quote mark
is involved. See https://github.com/postcss/postcss-selector-parser/pull/133 for an extensive
write-up on these changes.
**Upgrade/API Example**
In `3.x` there was no unescape handling and internal consistency of several properties was the caller's job to maintain. It was very easy for the developer
to create a CSS file that did not parse correctly when some types of values
were in use.
```js
const selectorParser = require("postcss-selector-parser");
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value"});
attr.value; // => "a-value"
attr.toString(); // => [id=a-value]
// Add quotes to an attribute's value.
// All these values have to be set by the caller to be consistent:
// no internal consistency is maintained.
attr.raws.unquoted = attr.value
attr.value = "'" + attr.value + "'";
attr.value; // => "'a-value'"
attr.quoted = true;
attr.toString(); // => "[id='a-value']"
```
In `4.0` there is a convenient API for setting and mutating values
that may need escaping. Especially for attributes.
```js
const selectorParser = require("postcss-selector-parser");
// The constructor requires you specify the exact escape sequence
let className = selectorParser.className({value: "illegal class name", raws: {value: "illegal\\ class\\ name"}});
className.toString(); // => '.illegal\\ class\\ name'
// So it's better to set the value as a property
className = selectorParser.className();
// Most properties that deal with identifiers work like this
className.value = "escape for me";
className.value; // => 'escape for me'
className.toString(); // => '.escape\\ for\\ me'
// emoji and all non-ascii are escaped to ensure it works in every css file.
className.value = "😱🦄😍";
className.value; // => '😱🦄😍'
className.toString(); // => '.\\1F631\\1F984\\1F60D'
// you can control the escape sequence if you want, or do bad bad things
className.setPropertyAndEscape('value', 'xxxx', 'yyyy');
className.value; // => "xxxx"
className.toString(); // => ".yyyy"
// Pass a value directly through to the css output without escaping it.
className.setPropertyWithoutEscape('value', '$REPLACE_ME$');
className.value; // => "$REPLACE_ME$"
className.toString(); // => ".$REPLACE_ME$"
// The biggest changes are to the Attribute class
// passing quoteMark explicitly is required to avoid a deprecation warning.
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value", quoteMark: null});
attr.toString(); // => "[id=a-value]"
// Get the value with quotes on it and any necessary escapes.
// This is the same as reading attr.value in 3.x.
attr.getQuotedValue(); // => "a-value";
attr.quoteMark; // => null
// Add quotes to an attribute's value.
attr.quoteMark = "'"; // This is all that's required.
attr.toString(); // => "[id='a-value']"
attr.quoted; // => true
// The value is still the same, only the quotes have changed.
attr.value; // => a-value
attr.getQuotedValue(); // => "'a-value'";
// deprecated assignment, no warning because there's no escapes
attr.value = "new-value";
// no quote mark is needed so it is removed
attr.getQuotedValue(); // => "new-value";
// deprecated assignment,
attr.value = "\"a 'single quoted' value\"";
// > (node:27859) DeprecationWarning: Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead.
attr.getQuotedValue(); // => '"a \'single quoted\' value"';
// quote mark inferred from first and last characters.
attr.quoteMark; // => '"'
// setValue takes options to make manipulating the value simple.
attr.setValue('foo', {smart: true});
// foo doesn't require any escapes or quotes.
attr.toString(); // => '[id=foo]'
attr.quoteMark; // => null
// An explicit quote mark can be specified
attr.setValue('foo', {quoteMark: '"'});
attr.toString(); // => '[id="foo"]'
// preserves quote mark by default
attr.setValue('bar');
attr.toString(); // => '[id="bar"]'
attr.quoteMark = null;
attr.toString(); // => '[id=bar]'
// with no arguments, it preserves quote mark even when it's not a great idea
attr.setValue('a value \n that should be quoted');
attr.toString(); // => '[id=a\\ value\\ \\A\\ that\\ should\\ be\\ quoted]'
// smart preservation with a specified default
attr.setValue('a value \n that should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a value \\A that should be quoted']"
attr.quoteMark = '"';
// => '[id="a value \\A that should be quoted"]'
// this keeps double quotes because it wants to quote the value and the existing value has double quotes.
attr.setValue('this should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => '[id="this should be quoted"]'
// picks single quotes because the value has double quotes
attr.setValue('a "double quoted" value', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a "double quoted" value']"
// setPropertyAndEscape lets you do anything you want. Even things that are a bad idea and illegal.
attr.setPropertyAndEscape('value', 'xxxx', 'the password is 42');
attr.value; // => "xxxx"
attr.toString(); // => "[id=the password is 42]"
// Pass a value directly through to the css output without escaping it.
attr.setPropertyWithoutEscape('value', '$REPLACEMENT$');
attr.value; // => "$REPLACEMENT$"
attr.toString(); // => "[id=$REPLACEMENT$]"
```
# 3.1.2
* Fix: Removed dot-prop dependency since it's no longer written in es5.
# 3.1.1
* Fix: typescript definitions weren't in the published package.
# 3.1.0
* Fixed numerous bugs in attribute nodes relating to the handling of comments
and whitespace. There's significant changes to `attrNode.spaces` and `attrNode.raws` since the `3.0.0` release.
* Added `Attribute#offsetOf(part)` to get the offset location of
attribute parts like `"operator"` and `"value"`. This is most
often added to `Attribute#sourceIndex` for error reporting.
# 3.0.0
## Breaking changes
* Some tweaks to the tokenizer/attribute selector parsing mean that whitespace
locations might be slightly different to the 2.x code.
* Better attribute selector parsing with more validation; postcss-selector-parser
no longer uses regular expressions to parse attribute selectors.
* Added an async API (thanks to @jacobp100); the default `process` API is now
async, and the sync API is now accessed through `processSync` instead.
* `process()` and `processSync()` now return a string instead of the Processor
instance.
* Tweaks handling of Less interpolation (thanks to @jwilsson).
* Removes support for Node 0.12.
## Other changes
* `ast()` and `astSync()` methods have been added to the `Processor`. These
return the `Root` node of the selectors after processing them.
* `transform()` and `transformSync()` methods have been added to the
`Processor`. These return the value returned by the processor callback
after processing the selectors.
* Set the parent when inserting a node (thanks to @chriseppstein).
* Correctly adjust indices when using insertBefore/insertAfter (thanks to @tivac).
* Fixes handling of namespaces with qualified tag selectors.
* `process`, `ast` and `transform` (and their sync variants) now accept a
`postcss` rule node. When provided, better errors are generated and selector
processing is automatically set back to the rule selector (unless the `updateSelector` option is set to `false`.)
* Now more memory efficient when tokenizing selectors.
### Upgrade hints
The pattern of:
`rule.selector = processor.process(rule.selector).result.toString();`
is now:
`processor.processSync(rule)`
# 2.2.3
* Resolves an issue where the parser would not reduce multiple spaces between an
ampersand and another simple selector in lossy mode (thanks to @adam-26).
# 2.2.2
* No longer hangs on an unescaped semicolon; instead the parser will throw
an exception for these cases.
# 2.2.1
* Allows a consumer to specify whitespace tokens when creating a new Node
(thanks to @Semigradsky).
# 2.2.0
* Added a new option to normalize whitespace when parsing the selector string
(thanks to @adam-26).
# 2.1.1
* Better unquoted value handling within attribute selectors
(thanks to @evilebottnawi).
# 2.1.0
* Added: Use string constants for all node types & expose them on the main
parser instance (thanks to @Aweary).
# 2.0.0
This release contains the following breaking changes:
* Renamed all `eachInside` iterators to `walk`. For example, `eachTag` is now
`walkTags`, and `eachInside` is now `walk`.
* Renamed `Node#removeSelf()` to `Node#remove()`.
* Renamed `Container#remove()` to `Container#removeChild()`.
* Renamed `Node#raw` to `Node#raws` (thanks to @davidtheclark).
* Now parses `&` as the *nesting* selector, rather than a *tag* selector.
* Fixes misinterpretation of Sass interpolation (e.g. `#{foo}`) as an
id selector (thanks to @davidtheclark).
and;
* Fixes parsing of attribute selectors with equals signs in them
(e.g. `[data-attr="foo=bar"]`) (thanks to @montmanu).
* Adds `quoted` and `raw.unquoted` properties to attribute nodes
(thanks to @davidtheclark).
# 1.3.3
* Fixes an infinite loop on `)` and `]` tokens when they had no opening pairs.
Now postcss-selector-parser will throw when it encounters these lone tokens.
# 1.3.2
* Now uses plain integers rather than `str.charCodeAt(0)` for compiled builds.
# 1.3.1
* Update flatten to v1.x (thanks to @shinnn).
# 1.3.0
* Adds a new node type, `String`, to fix a crash on selectors such as
`foo:bar("test")`.
# 1.2.1
* Fixes a crash when the parser encountered a trailing combinator.
# 1.2.0
* A more descriptive error is thrown when the parser expects to find a
pseudo-class/pseudo-element (thanks to @ashelley).
* Adds support for line/column locations for selector nodes, as well as a
`Node#sourceIndex` method (thanks to @davidtheclark).
# 1.1.4
* Fixes a crash when a selector started with a `>` combinator. The module will
now no longer throw if a selector has a leading/trailing combinator node.
# 1.1.3
* Fixes a crash on `@` tokens.
# 1.1.2
* Fixes an infinite loop caused by using parentheses in a non-pseudo element
context.
# 1.1.1
* Fixes a crash when a backslash ended a selector string.
# 1.1.0
* Adds support for replacing multiple nodes at once with `replaceWith`
(thanks to @jonathantneal).
* Parser no longer throws on sequential IDs and trailing commas, to support
parsing of selector hacks.
# 1.0.1
* Fixes using `insertAfter` and `insertBefore` during iteration.
# 1.0.0
* Adds `clone` and `replaceWith` methods to nodes.
* Adds `insertBefore` and `insertAfter` to containers.
* Stabilises API.
# 0.0.5
* Fixes crash on extra whitespace inside a pseudo selector's parentheses.
* Adds sort function to the container class.
* Enables the parser to pass its input through without transforming.
* Iteration-safe `each` and `eachInside`.
# 0.0.4
* Tidy up redundant duplication.
* Fixes a bug where the parser would loop infinitely on universal selectors
inside pseudo selectors.
* Adds `length` getter and `eachInside`, `map`, `reduce` to the container class.
* When a selector has been removed from the tree, the root node will no longer
cast it to a string.
* Adds node type iterators to the container class (e.g. `eachComment`).
* Adds filter function to the container class.
* Adds split function to the container class.
* Create new node types by doing `parser.id(opts)` etc.
* Adds support for pseudo classes anywhere in the selector.
# 0.0.3
* Adds `next` and `prev` to the node class.
* Adds `first` and `last` getters to the container class.
* Adds `every` and `some` iterators to the container class.
* Add `empty` alias for `removeAll`.
* Combinators are now types of node.
* Fixes the at method so that it is not an alias for `index`.
* Tidy up creation of new nodes in the parser.
* Refactors how namespaces are handled for consistency & less redundant code.
* Refactors AST to use `nodes` exclusively, and eliminates excessive nesting.
* Fixes nested pseudo parsing.
* Fixes whitespace parsing.
# 0.0.2
* Adds support for namespace selectors.
* Adds support for selectors joined by escaped spaces - such as `.\31\ 0`.
# 0.0.1
* Initial release.
@@ -0,0 +1,22 @@
Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,49 @@
# postcss-selector-parser [![Build Status](https://travis-ci.org/postcss/postcss-selector-parser.svg?branch=master)](https://travis-ci.org/postcss/postcss-selector-parser)
> Selector parser with built in methods for working with selector strings.
## Install
With [npm](https://npmjs.com/package/postcss-selector-parser) do:
```
npm install postcss-selector-parser
```
## Quick Start
```js
const parser = require('postcss-selector-parser');
const transform = selectors => {
selectors.walk(selector => {
// do something with the selector
console.log(String(selector))
});
};
const transformed = parser(transform).processSync('h1, h2, h3');
```
To normalize selector whitespace:
```js
const parser = require('postcss-selector-parser');
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
// -> h1,h2,h3
```
Async support is provided through `parser.process` and will resolve a Promise
with the resulting selector string.
## API
Please see [API.md](API.md).
## Credits
* Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped
accelerate this module's development.
## License
MIT
@@ -0,0 +1,26 @@
'use strict';
exports.__esModule = true;
var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
var _selectors = require('./selectors');
var selectors = _interopRequireWildcard(_selectors);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var parser = function parser(processor) {
return new _processor2.default(processor);
};
Object.assign(parser, selectors);
delete parser.__esModule;
exports.default = parser;
module.exports = exports['default'];
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,185 @@
"use strict";
exports.__esModule = true;
var _parser = require("./parser");
var _parser2 = _interopRequireDefault(_parser);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Processor = function () {
function Processor(func, options) {
_classCallCheck(this, Processor);
this.func = func || function noop() {};
this.funcRes = null;
this.options = options;
}
Processor.prototype._shouldUpdateSelector = function _shouldUpdateSelector(rule) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var merged = Object.assign({}, this.options, options);
if (merged.updateSelector === false) {
return false;
} else {
return typeof rule !== "string";
}
};
Processor.prototype._isLossy = function _isLossy() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var merged = Object.assign({}, this.options, options);
if (merged.lossless === false) {
return true;
} else {
return false;
}
};
Processor.prototype._root = function _root(rule) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var parser = new _parser2.default(rule, this._parseOptions(options));
return parser.root;
};
Processor.prototype._parseOptions = function _parseOptions(options) {
return {
lossy: this._isLossy(options)
};
};
Processor.prototype._run = function _run(rule) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new Promise(function (resolve, reject) {
try {
var root = _this._root(rule, options);
Promise.resolve(_this.func(root)).then(function (transform) {
var string = undefined;
if (_this._shouldUpdateSelector(rule, options)) {
string = root.toString();
rule.selector = string;
}
return { transform: transform, root: root, string: string };
}).then(resolve, reject);
} catch (e) {
reject(e);
return;
}
});
};
Processor.prototype._runSync = function _runSync(rule) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var root = this._root(rule, options);
var transform = this.func(root);
if (transform && typeof transform.then === "function") {
throw new Error("Selector processor returned a promise to a synchronous call.");
}
var string = undefined;
if (options.updateSelector && typeof rule !== "string") {
string = root.toString();
rule.selector = string;
}
return { transform: transform, root: root, string: string };
};
/**
* Process rule into a selector AST.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<parser.Root>} The AST of the selector after processing it.
*/
Processor.prototype.ast = function ast(rule, options) {
return this._run(rule, options).then(function (result) {
return result.root;
});
};
/**
* Process rule into a selector AST synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {parser.Root} The AST of the selector after processing it.
*/
Processor.prototype.astSync = function astSync(rule, options) {
return this._runSync(rule, options).root;
};
/**
* Process a selector into a transformed value asynchronously
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<any>} The value returned by the processor.
*/
Processor.prototype.transform = function transform(rule, options) {
return this._run(rule, options).then(function (result) {
return result.transform;
});
};
/**
* Process a selector into a transformed value synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {any} The value returned by the processor.
*/
Processor.prototype.transformSync = function transformSync(rule, options) {
return this._runSync(rule, options).transform;
};
/**
* Process a selector into a new selector string asynchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
Processor.prototype.process = function process(rule, options) {
return this._run(rule, options).then(function (result) {
return result.string || result.root.toString();
});
};
/**
* Process a selector into a new selector string synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
Processor.prototype.processSync = function processSync(rule, options) {
var result = this._runSync(rule, options);
return result.string || result.root.toString();
};
return Processor;
}();
exports.default = Processor;
module.exports = exports["default"];
@@ -0,0 +1,468 @@
"use strict";
exports.__esModule = true;
var _CSSESC_QUOTE_OPTIONS;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.unescapeValue = unescapeValue;
var _cssesc = require("cssesc");
var _cssesc2 = _interopRequireDefault(_cssesc);
var _unesc = require("../util/unesc");
var _unesc2 = _interopRequireDefault(_unesc);
var _namespace = require("./namespace");
var _namespace2 = _interopRequireDefault(_namespace);
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _require = require("util"),
deprecate = _require.deprecate;
var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/;
var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
function unescapeValue(value) {
var deprecatedUsage = false;
var quoteMark = null;
var unescaped = value;
var m = unescaped.match(WRAPPED_IN_QUOTES);
if (m) {
quoteMark = m[1];
unescaped = m[2];
}
unescaped = (0, _unesc2.default)(unescaped);
if (unescaped !== value) {
deprecatedUsage = true;
}
return {
deprecatedUsage: deprecatedUsage,
unescaped: unescaped,
quoteMark: quoteMark
};
}
function handleDeprecatedContructorOpts(opts) {
if (opts.quoteMark !== undefined) {
return opts;
}
if (opts.value === undefined) {
return opts;
}
warnOfDeprecatedConstructor();
var _unescapeValue = unescapeValue(opts.value),
quoteMark = _unescapeValue.quoteMark,
unescaped = _unescapeValue.unescaped;
if (!opts.raws) {
opts.raws = {};
}
if (opts.raws.value === undefined) {
opts.raws.value = opts.value;
}
opts.value = unescaped;
opts.quoteMark = quoteMark;
return opts;
}
var Attribute = function (_Namespace) {
_inherits(Attribute, _Namespace);
function Attribute() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Attribute);
var _this = _possibleConstructorReturn(this, _Namespace.call(this, handleDeprecatedContructorOpts(opts)));
_this.type = _types.ATTRIBUTE;
_this.raws = _this.raws || {};
Object.defineProperty(_this.raws, 'unquoted', {
get: deprecate(function () {
return _this.value;
}, "attr.raws.unquoted is deprecated. Call attr.value instead."),
set: deprecate(function () {
return _this.value;
}, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
});
_this._constructed = true;
return _this;
}
/**
* Returns the Attribute's value quoted such that it would be legal to use
* in the value of a css file. The original value's quotation setting
* used for stringification is left unchanged. See `setValue(value, options)`
* if you want to control the quote settings of a new value for the attribute.
*
* You can also change the quotation used for the current value by setting quoteMark.
*
* Options:
* * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
* option is not set, the original value for quoteMark will be used. If
* indeterminate, a double quote is used. The legal values are:
* * `null` - the value will be unquoted and characters will be escaped as necessary.
* * `'` - the value will be quoted with a single quote and single quotes are escaped.
* * `"` - the value will be quoted with a double quote and double quotes are escaped.
* * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
* over the quoteMark option value.
* * smart {boolean} - if true, will select a quote mark based on the value
* and the other options specified here. See the `smartQuoteMark()`
* method.
**/
Attribute.prototype.getQuotedValue = function getQuotedValue() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var quoteMark = this._determineQuoteMark(options);
var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
var escaped = (0, _cssesc2.default)(this._value, cssescopts);
return escaped;
};
Attribute.prototype._determineQuoteMark = function _determineQuoteMark(options) {
return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
};
/**
* Set the unescaped value with the specified quotation options. The value
* provided must not include any wrapping quote marks -- those quotes will
* be interpreted as part of the value and escaped accordingly.
*/
Attribute.prototype.setValue = function setValue(value) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this._value = value;
this._quoteMark = this._determineQuoteMark(options);
this._syncRawValue();
};
/**
* Intelligently select a quoteMark value based on the value's contents. If
* the value is a legal CSS ident, it will not be quoted. Otherwise a quote
* mark will be picked that minimizes the number of escapes.
*
* If there's no clear winner, the quote mark from these options is used,
* then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
* true). If the quoteMark is unspecified, a double quote is used.
*
* @param options This takes the quoteMark and preferCurrentQuoteMark options
* from the quoteValue method.
*/
Attribute.prototype.smartQuoteMark = function smartQuoteMark(options) {
var v = this.value;
var numSingleQuotes = v.replace(/[^']/g, '').length;
var numDoubleQuotes = v.replace(/[^"]/g, '').length;
if (numSingleQuotes + numDoubleQuotes === 0) {
var escaped = (0, _cssesc2.default)(v, { isIdentifier: true });
if (escaped === v) {
return Attribute.NO_QUOTE;
} else {
var pref = this.preferredQuoteMark(options);
if (pref === Attribute.NO_QUOTE) {
// pick a quote mark that isn't none and see if it's smaller
var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
var opts = CSSESC_QUOTE_OPTIONS[quote];
var quoteValue = (0, _cssesc2.default)(v, opts);
if (quoteValue.length < escaped.length) {
return quote;
}
}
return pref;
}
} else if (numDoubleQuotes === numSingleQuotes) {
return this.preferredQuoteMark(options);
} else if (numDoubleQuotes < numSingleQuotes) {
return Attribute.DOUBLE_QUOTE;
} else {
return Attribute.SINGLE_QUOTE;
}
};
/**
* Selects the preferred quote mark based on the options and the current quote mark value.
* If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
* instead.
*/
Attribute.prototype.preferredQuoteMark = function preferredQuoteMark(options) {
var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
if (quoteMark === undefined) {
quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
}
if (quoteMark === undefined) {
quoteMark = Attribute.DOUBLE_QUOTE;
}
return quoteMark;
};
Attribute.prototype._syncRawValue = function _syncRawValue() {
var rawValue = (0, _cssesc2.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
if (rawValue === this._value) {
if (this.raws) {
delete this.raws.value;
}
} else {
this.raws.value = rawValue;
}
};
Attribute.prototype._handleEscapes = function _handleEscapes(prop, value) {
if (this._constructed) {
var escaped = (0, _cssesc2.default)(value, { isIdentifier: true });
if (escaped !== value) {
this.raws[prop] = escaped;
} else {
delete this.raws[prop];
}
}
};
Attribute.prototype._spacesFor = function _spacesFor(name) {
var attrSpaces = { before: '', after: '' };
var spaces = this.spaces[name] || {};
var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
return Object.assign(attrSpaces, spaces, rawSpaces);
};
Attribute.prototype._stringFor = function _stringFor(name) {
var spaceName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : name;
var concat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultAttrConcat;
var attrSpaces = this._spacesFor(spaceName);
return concat(this.stringifyProperty(name), attrSpaces);
};
/**
* returns the offset of the attribute part specified relative to the
* start of the node of the output string.
*
* * "ns" - alias for "namespace"
* * "namespace" - the namespace if it exists.
* * "attribute" - the attribute name
* * "attributeNS" - the start of the attribute or its namespace
* * "operator" - the match operator of the attribute
* * "value" - The value (string or identifier)
* * "insensitive" - the case insensitivity flag;
* @param part One of the possible values inside an attribute.
* @returns -1 if the name is invalid or the value doesn't exist in this attribute.
*/
Attribute.prototype.offsetOf = function offsetOf(name) {
var count = 1;
var attributeSpaces = this._spacesFor("attribute");
count += attributeSpaces.before.length;
if (name === "namespace" || name === "ns") {
return this.namespace ? count : -1;
}
if (name === "attributeNS") {
return count;
}
count += this.namespaceString.length;
if (this.namespace) {
count += 1;
}
if (name === "attribute") {
return count;
}
count += this.stringifyProperty("attribute").length;
count += attributeSpaces.after.length;
var operatorSpaces = this._spacesFor("operator");
count += operatorSpaces.before.length;
var operator = this.stringifyProperty("operator");
if (name === "operator") {
return operator ? count : -1;
}
count += operator.length;
count += operatorSpaces.after.length;
var valueSpaces = this._spacesFor("value");
count += valueSpaces.before.length;
var value = this.stringifyProperty("value");
if (name === "value") {
return value ? count : -1;
}
count += value.length;
count += valueSpaces.after.length;
var insensitiveSpaces = this._spacesFor("insensitive");
count += insensitiveSpaces.before.length;
if (name === "insensitive") {
return this.insensitive ? count : -1;
}
return -1;
};
Attribute.prototype.toString = function toString() {
var _this2 = this;
var selector = [this.rawSpaceBefore, '['];
selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
if (this.operator && this.value) {
selector.push(this._stringFor('operator'));
selector.push(this._stringFor('value'));
selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
attrSpaces.before = " ";
}
return defaultAttrConcat(attrValue, attrSpaces);
}));
}
selector.push(']');
selector.push(this.rawSpaceAfter);
return selector.join('');
};
_createClass(Attribute, [{
key: "quoted",
get: function get() {
var qm = this.quoteMark;
return qm === "'" || qm === '"';
},
set: function set(value) {
warnOfDeprecatedQuotedAssignment();
}
/**
* returns a single (`'`) or double (`"`) quote character if the value is quoted.
* returns `null` if the value is not quoted.
* returns `undefined` if the quotation state is unknown (this can happen when
* the attribute is constructed without specifying a quote mark.)
*/
}, {
key: "quoteMark",
get: function get() {
return this._quoteMark;
}
/**
* Set the quote mark to be used by this attribute's value.
* If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
* value is updated accordingly.
*
* @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
*/
,
set: function set(quoteMark) {
if (!this._constructed) {
this._quoteMark = quoteMark;
return;
}
if (this._quoteMark !== quoteMark) {
this._quoteMark = quoteMark;
this._syncRawValue();
}
}
}, {
key: "qualifiedAttribute",
get: function get() {
return this.qualifiedName(this.raws.attribute || this.attribute);
}
}, {
key: "insensitiveFlag",
get: function get() {
return this.insensitive ? 'i' : '';
}
}, {
key: "value",
get: function get() {
return this._value;
}
/**
* Before 3.0, the value had to be set to an escaped value including any wrapped
* quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
* is unescaped during parsing and any quote marks are removed.
*
* Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
* a deprecation warning is raised when the new value contains any characters that would
* require escaping (including if it contains wrapped quotes).
*
* Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
* how the new value is quoted.
*/
,
set: function set(v) {
if (this._constructed) {
var _unescapeValue2 = unescapeValue(v),
deprecatedUsage = _unescapeValue2.deprecatedUsage,
unescaped = _unescapeValue2.unescaped,
quoteMark = _unescapeValue2.quoteMark;
if (deprecatedUsage) {
warnOfDeprecatedValueAssignment();
}
if (unescaped === this._value && quoteMark === this._quoteMark) {
return;
}
this._value = unescaped;
this._quoteMark = quoteMark;
this._syncRawValue();
} else {
this._value = v;
}
}
}, {
key: "attribute",
get: function get() {
return this._attribute;
},
set: function set(name) {
this._handleEscapes("attribute", name);
this._attribute = name;
}
}]);
return Attribute;
}(_namespace2.default);
Attribute.NO_QUOTE = null;
Attribute.SINGLE_QUOTE = "'";
Attribute.DOUBLE_QUOTE = '"';
exports.default = Attribute;
var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
"'": { quotes: 'single', wrap: true },
'"': { quotes: 'double', wrap: true }
}, _CSSESC_QUOTE_OPTIONS[null] = { isIdentifier: true }, _CSSESC_QUOTE_OPTIONS);
function defaultAttrConcat(attrValue, attrSpaces) {
return "" + attrSpaces.before + attrValue + attrSpaces.after;
}
@@ -0,0 +1,67 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _cssesc = require('cssesc');
var _cssesc2 = _interopRequireDefault(_cssesc);
var _util = require('../util');
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ClassName = function (_Node) {
_inherits(ClassName, _Node);
function ClassName(opts) {
_classCallCheck(this, ClassName);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.CLASS;
_this._constructed = true;
return _this;
}
ClassName.prototype.toString = function toString() {
return [this.rawSpaceBefore, String('.' + this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(ClassName, [{
key: 'value',
set: function set(v) {
if (this._constructed) {
var escaped = (0, _cssesc2.default)(v, { isIdentifier: true });
if (escaped !== v) {
(0, _util.ensureObject)(this, "raws");
this.raws.value = escaped;
} else if (this.raws) {
delete this.raws.value;
}
}
this._value = v;
},
get: function get() {
return this._value;
}
}]);
return ClassName;
}(_node2.default);
exports.default = ClassName;
module.exports = exports['default'];
@@ -0,0 +1,35 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Combinator = function (_Node) {
_inherits(Combinator, _Node);
function Combinator(opts) {
_classCallCheck(this, Combinator);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.COMBINATOR;
return _this;
}
return Combinator;
}(_node2.default);
exports.default = Combinator;
module.exports = exports['default'];
@@ -0,0 +1,35 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(opts) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.COMMENT;
return _this;
}
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
@@ -0,0 +1,91 @@
'use strict';
exports.__esModule = true;
exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = undefined;
var _attribute = require('./attribute');
var _attribute2 = _interopRequireDefault(_attribute);
var _className = require('./className');
var _className2 = _interopRequireDefault(_className);
var _combinator = require('./combinator');
var _combinator2 = _interopRequireDefault(_combinator);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _id = require('./id');
var _id2 = _interopRequireDefault(_id);
var _nesting = require('./nesting');
var _nesting2 = _interopRequireDefault(_nesting);
var _pseudo = require('./pseudo');
var _pseudo2 = _interopRequireDefault(_pseudo);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
var _selector = require('./selector');
var _selector2 = _interopRequireDefault(_selector);
var _string = require('./string');
var _string2 = _interopRequireDefault(_string);
var _tag = require('./tag');
var _tag2 = _interopRequireDefault(_tag);
var _universal = require('./universal');
var _universal2 = _interopRequireDefault(_universal);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var attribute = exports.attribute = function attribute(opts) {
return new _attribute2.default(opts);
};
var className = exports.className = function className(opts) {
return new _className2.default(opts);
};
var combinator = exports.combinator = function combinator(opts) {
return new _combinator2.default(opts);
};
var comment = exports.comment = function comment(opts) {
return new _comment2.default(opts);
};
var id = exports.id = function id(opts) {
return new _id2.default(opts);
};
var nesting = exports.nesting = function nesting(opts) {
return new _nesting2.default(opts);
};
var pseudo = exports.pseudo = function pseudo(opts) {
return new _pseudo2.default(opts);
};
var root = exports.root = function root(opts) {
return new _root2.default(opts);
};
var selector = exports.selector = function selector(opts) {
return new _selector2.default(opts);
};
var string = exports.string = function string(opts) {
return new _string2.default(opts);
};
var tag = exports.tag = function tag(opts) {
return new _tag2.default(opts);
};
var universal = exports.universal = function universal(opts) {
return new _universal2.default(opts);
};
@@ -0,0 +1,392 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
var types = _interopRequireWildcard(_types);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Container = function (_Node) {
_inherits(Container, _Node);
function Container(opts) {
_classCallCheck(this, Container);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
if (!_this.nodes) {
_this.nodes = [];
}
return _this;
}
Container.prototype.append = function append(selector) {
selector.parent = this;
this.nodes.push(selector);
return this;
};
Container.prototype.prepend = function prepend(selector) {
selector.parent = this;
this.nodes.unshift(selector);
return this;
};
Container.prototype.at = function at(index) {
return this.nodes[index];
};
Container.prototype.index = function index(child) {
if (typeof child === 'number') {
return child;
}
return this.nodes.indexOf(child);
};
Container.prototype.removeChild = function removeChild(child) {
child = this.index(child);
this.at(child).parent = undefined;
this.nodes.splice(child, 1);
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
Container.prototype.removeAll = function removeAll() {
for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
node.parent = undefined;
}
this.nodes = [];
return this;
};
Container.prototype.empty = function empty() {
return this.removeAll();
};
Container.prototype.insertAfter = function insertAfter(oldNode, newNode) {
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex + 1, 0, newNode);
newNode.parent = this;
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex <= index) {
this.indexes[id] = index + 1;
}
}
return this;
};
Container.prototype.insertBefore = function insertBefore(oldNode, newNode) {
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex, 0, newNode);
newNode.parent = this;
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index <= oldIndex) {
this.indexes[id] = index + 1;
}
}
return this;
};
Container.prototype._findChildAtPosition = function _findChildAtPosition(line, col) {
var found = undefined;
this.each(function (node) {
if (node.atPosition) {
var foundChild = node.atPosition(line, col);
if (foundChild) {
found = foundChild;
return false;
}
} else if (node.isAtPosition(line, col)) {
found = node;
return false;
}
});
return found;
};
/**
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
*
* If not found, returns undefined.
* @param {number} line The line number of the node to find. (1-based index)
* @param {number} col The column number of the node to find. (1-based index)
*/
Container.prototype.atPosition = function atPosition(line, col) {
if (this.isAtPosition(line, col)) {
return this._findChildAtPosition(line, col) || this;
} else {
return undefined;
}
};
Container.prototype._inferEndPosition = function _inferEndPosition() {
if (this.last && this.last.source && this.last.source.end) {
this.source = this.source || {};
this.source.end = this.source.end || {};
Object.assign(this.source.end, this.last.source.end);
}
};
Container.prototype.each = function each(callback) {
if (!this.lastEach) {
this.lastEach = 0;
}
if (!this.indexes) {
this.indexes = {};
}
this.lastEach++;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.length) {
return undefined;
}
var index = void 0,
result = void 0;
while (this.indexes[id] < this.length) {
index = this.indexes[id];
result = callback(this.at(index), index);
if (result === false) {
break;
}
this.indexes[id] += 1;
}
delete this.indexes[id];
if (result === false) {
return false;
}
};
Container.prototype.walk = function walk(callback) {
return this.each(function (node, i) {
var result = callback(node, i);
if (result !== false && node.length) {
result = node.walk(callback);
}
if (result === false) {
return false;
}
});
};
Container.prototype.walkAttributes = function walkAttributes(callback) {
var _this2 = this;
return this.walk(function (selector) {
if (selector.type === types.ATTRIBUTE) {
return callback.call(_this2, selector);
}
});
};
Container.prototype.walkClasses = function walkClasses(callback) {
var _this3 = this;
return this.walk(function (selector) {
if (selector.type === types.CLASS) {
return callback.call(_this3, selector);
}
});
};
Container.prototype.walkCombinators = function walkCombinators(callback) {
var _this4 = this;
return this.walk(function (selector) {
if (selector.type === types.COMBINATOR) {
return callback.call(_this4, selector);
}
});
};
Container.prototype.walkComments = function walkComments(callback) {
var _this5 = this;
return this.walk(function (selector) {
if (selector.type === types.COMMENT) {
return callback.call(_this5, selector);
}
});
};
Container.prototype.walkIds = function walkIds(callback) {
var _this6 = this;
return this.walk(function (selector) {
if (selector.type === types.ID) {
return callback.call(_this6, selector);
}
});
};
Container.prototype.walkNesting = function walkNesting(callback) {
var _this7 = this;
return this.walk(function (selector) {
if (selector.type === types.NESTING) {
return callback.call(_this7, selector);
}
});
};
Container.prototype.walkPseudos = function walkPseudos(callback) {
var _this8 = this;
return this.walk(function (selector) {
if (selector.type === types.PSEUDO) {
return callback.call(_this8, selector);
}
});
};
Container.prototype.walkTags = function walkTags(callback) {
var _this9 = this;
return this.walk(function (selector) {
if (selector.type === types.TAG) {
return callback.call(_this9, selector);
}
});
};
Container.prototype.walkUniversals = function walkUniversals(callback) {
var _this10 = this;
return this.walk(function (selector) {
if (selector.type === types.UNIVERSAL) {
return callback.call(_this10, selector);
}
});
};
Container.prototype.split = function split(callback) {
var _this11 = this;
var current = [];
return this.reduce(function (memo, node, index) {
var split = callback.call(_this11, node);
current.push(node);
if (split) {
memo.push(current);
current = [];
} else if (index === _this11.length - 1) {
memo.push(current);
}
return memo;
}, []);
};
Container.prototype.map = function map(callback) {
return this.nodes.map(callback);
};
Container.prototype.reduce = function reduce(callback, memo) {
return this.nodes.reduce(callback, memo);
};
Container.prototype.every = function every(callback) {
return this.nodes.every(callback);
};
Container.prototype.some = function some(callback) {
return this.nodes.some(callback);
};
Container.prototype.filter = function filter(callback) {
return this.nodes.filter(callback);
};
Container.prototype.sort = function sort(callback) {
return this.nodes.sort(callback);
};
Container.prototype.toString = function toString() {
return this.map(String).join('');
};
_createClass(Container, [{
key: 'first',
get: function get() {
return this.at(0);
}
}, {
key: 'last',
get: function get() {
return this.at(this.length - 1);
}
}, {
key: 'length',
get: function get() {
return this.nodes.length;
}
}]);
return Container;
}(_node2.default);
exports.default = Container;
module.exports = exports['default'];
@@ -0,0 +1,54 @@
"use strict";
exports.__esModule = true;
exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _IS_TYPE;
exports.isNode = isNode;
exports.isPseudoElement = isPseudoElement;
exports.isPseudoClass = isPseudoClass;
exports.isContainer = isContainer;
exports.isNamespace = isNamespace;
var _types = require("./types");
var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
function isNode(node) {
return (typeof node === "undefined" ? "undefined" : _typeof(node)) === "object" && IS_TYPE[node.type];
}
function isNodeType(type, node) {
return isNode(node) && node.type === type;
}
var isAttribute = exports.isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
var isClassName = exports.isClassName = isNodeType.bind(null, _types.CLASS);
var isCombinator = exports.isCombinator = isNodeType.bind(null, _types.COMBINATOR);
var isComment = exports.isComment = isNodeType.bind(null, _types.COMMENT);
var isIdentifier = exports.isIdentifier = isNodeType.bind(null, _types.ID);
var isNesting = exports.isNesting = isNodeType.bind(null, _types.NESTING);
var isPseudo = exports.isPseudo = isNodeType.bind(null, _types.PSEUDO);
var isRoot = exports.isRoot = isNodeType.bind(null, _types.ROOT);
var isSelector = exports.isSelector = isNodeType.bind(null, _types.SELECTOR);
var isString = exports.isString = isNodeType.bind(null, _types.STRING);
var isTag = exports.isTag = isNodeType.bind(null, _types.TAG);
var isUniversal = exports.isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
function isPseudoElement(node) {
return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value === ":before" || node.value === ":after");
}
function isPseudoClass(node) {
return isPseudo(node) && !isPseudoElement(node);
}
function isContainer(node) {
return !!(isNode(node) && node.walk);
}
function isNamespace(node) {
return isAttribute(node) || isTag(node);
}
@@ -0,0 +1,39 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ID = function (_Node) {
_inherits(ID, _Node);
function ID(opts) {
_classCallCheck(this, ID);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.ID;
return _this;
}
ID.prototype.toString = function toString() {
return [this.rawSpaceBefore, String('#' + this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
return ID;
}(_node2.default);
exports.default = ID;
module.exports = exports['default'];
@@ -0,0 +1,39 @@
"use strict";
exports.__esModule = true;
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _types[key];
}
});
});
var _constructors = require("./constructors");
Object.keys(_constructors).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _constructors[key];
}
});
});
var _guards = require("./guards");
Object.keys(_guards).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _guards[key];
}
});
});
@@ -0,0 +1,98 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _cssesc = require('cssesc');
var _cssesc2 = _interopRequireDefault(_cssesc);
var _util = require('../util');
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Namespace = function (_Node) {
_inherits(Namespace, _Node);
function Namespace() {
_classCallCheck(this, Namespace);
return _possibleConstructorReturn(this, _Node.apply(this, arguments));
}
Namespace.prototype.qualifiedName = function qualifiedName(value) {
if (this.namespace) {
return this.namespaceString + '|' + value;
} else {
return value;
}
};
Namespace.prototype.toString = function toString() {
return [this.rawSpaceBefore, this.qualifiedName(this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(Namespace, [{
key: 'namespace',
get: function get() {
return this._namespace;
},
set: function set(namespace) {
if (namespace === true || namespace === "*" || namespace === "&") {
this._namespace = namespace;
if (this.raws) {
delete this.raws.namespace;
}
return;
}
var escaped = (0, _cssesc2.default)(namespace, { isIdentifier: true });
this._namespace = namespace;
if (escaped !== namespace) {
(0, _util.ensureObject)(this, "raws");
this.raws.namespace = escaped;
} else if (this.raws) {
delete this.raws.namespace;
}
}
}, {
key: 'ns',
get: function get() {
return this._namespace;
},
set: function set(namespace) {
this.namespace = namespace;
}
}, {
key: 'namespaceString',
get: function get() {
if (this.namespace) {
var ns = this.stringifyProperty("namespace");
if (ns === true) {
return '';
} else {
return ns;
}
} else {
return '';
}
}
}]);
return Namespace;
}(_node2.default);
exports.default = Namespace;
;
module.exports = exports['default'];
@@ -0,0 +1,36 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Nesting = function (_Node) {
_inherits(Nesting, _Node);
function Nesting(opts) {
_classCallCheck(this, Nesting);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.NESTING;
_this.value = '&';
return _this;
}
return Nesting;
}(_node2.default);
exports.default = Nesting;
module.exports = exports['default'];
@@ -0,0 +1,216 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _util = require('../util');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var cloneNode = function cloneNode(obj, parent) {
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || obj === null) {
return obj;
}
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) {
continue;
}
var value = obj[i];
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (i === 'parent' && type === 'object') {
if (parent) {
cloned[i] = parent;
}
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else {
cloned[i] = cloneNode(value, cloned);
}
}
return cloned;
};
var Node = function () {
function Node() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Node);
Object.assign(this, opts);
this.spaces = this.spaces || {};
this.spaces.before = this.spaces.before || '';
this.spaces.after = this.spaces.after || '';
}
Node.prototype.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
Node.prototype.replaceWith = function replaceWith() {
if (this.parent) {
for (var index in arguments) {
this.parent.insertBefore(this, arguments[index]);
}
this.remove();
}
return this;
};
Node.prototype.next = function next() {
return this.parent.at(this.parent.index(this) + 1);
};
Node.prototype.prev = function prev() {
return this.parent.at(this.parent.index(this) - 1);
};
Node.prototype.clone = function clone() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows non standard syntax to be appended to an existing property
* by specifying the escaped value. By specifying the escaped value,
* illegal characters are allowed to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped optional. the escaped value of the property.
*/
Node.prototype.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
var originalValue = this[name];
var originalEscaped = this.raws[name];
this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
if (originalEscaped || valueEscaped !== value) {
this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
} else {
delete this.raws[name]; // delete any escaped value that was created by the setter.
}
};
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows the escaped value to be specified directly, allowing illegal
* characters to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped the escaped value of the property.
*/
Node.prototype.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
this.raws[name] = valueEscaped;
};
/**
* When you want a value to passed through to CSS directly. This method
* deletes the corresponding raw value causing the stringifier to fallback
* to the unescaped value.
* @param {string} name the property to set.
* @param {any} value The value that is both escaped and unescaped.
*/
Node.prototype.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
if (this.raws) {
delete this.raws[name];
}
};
/**
*
* @param {number} line The number (starting with 1)
* @param {number} column The column number (starting with 1)
*/
Node.prototype.isAtPosition = function isAtPosition(line, column) {
if (this.source && this.source.start && this.source.end) {
if (this.source.start.line > line) {
return false;
}
if (this.source.end.line < line) {
return false;
}
if (this.source.start.line === line && this.source.start.column > column) {
return false;
}
if (this.source.end.line === line && this.source.end.column < column) {
return false;
}
return true;
}
return undefined;
};
Node.prototype.stringifyProperty = function stringifyProperty(name) {
return this.raws && this.raws[name] || this[name];
};
Node.prototype.toString = function toString() {
return [this.rawSpaceBefore, String(this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(Node, [{
key: 'rawSpaceBefore',
get: function get() {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
if (rawSpace === undefined) {
rawSpace = this.spaces && this.spaces.before;
}
return rawSpace || "";
},
set: function set(raw) {
(0, _util.ensureObject)(this, "raws", "spaces");
this.raws.spaces.before = raw;
}
}, {
key: 'rawSpaceAfter',
get: function get() {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
if (rawSpace === undefined) {
rawSpace = this.spaces.after;
}
return rawSpace || "";
},
set: function set(raw) {
(0, _util.ensureObject)(this, "raws", "spaces");
this.raws.spaces.after = raw;
}
}]);
return Node;
}();
exports.default = Node;
module.exports = exports['default'];
@@ -0,0 +1,40 @@
'use strict';
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Pseudo = function (_Container) {
_inherits(Pseudo, _Container);
function Pseudo(opts) {
_classCallCheck(this, Pseudo);
var _this = _possibleConstructorReturn(this, _Container.call(this, opts));
_this.type = _types.PSEUDO;
return _this;
}
Pseudo.prototype.toString = function toString() {
var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
};
return Pseudo;
}(_container2.default);
exports.default = Pseudo;
module.exports = exports['default'];
@@ -0,0 +1,60 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Root = function (_Container) {
_inherits(Root, _Container);
function Root(opts) {
_classCallCheck(this, Root);
var _this = _possibleConstructorReturn(this, _Container.call(this, opts));
_this.type = _types.ROOT;
return _this;
}
Root.prototype.toString = function toString() {
var str = this.reduce(function (memo, selector) {
memo.push(String(selector));
return memo;
}, []).join(',');
return this.trailingComma ? str + ',' : str;
};
Root.prototype.error = function error(message, options) {
if (this._error) {
return this._error(message, options);
} else {
return new Error(message);
}
};
_createClass(Root, [{
key: 'errorGenerator',
set: function set(handler) {
this._error = handler;
}
}]);
return Root;
}(_container2.default);
exports.default = Root;
module.exports = exports['default'];
@@ -0,0 +1,35 @@
'use strict';
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Selector = function (_Container) {
_inherits(Selector, _Container);
function Selector(opts) {
_classCallCheck(this, Selector);
var _this = _possibleConstructorReturn(this, _Container.call(this, opts));
_this.type = _types.SELECTOR;
return _this;
}
return Selector;
}(_container2.default);
exports.default = Selector;
module.exports = exports['default'];
@@ -0,0 +1,35 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
var _types = require('./types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var String = function (_Node) {
_inherits(String, _Node);
function String(opts) {
_classCallCheck(this, String);
var _this = _possibleConstructorReturn(this, _Node.call(this, opts));
_this.type = _types.STRING;
return _this;
}
return String;
}(_node2.default);
exports.default = String;
module.exports = exports['default'];

Some files were not shown because too many files have changed in this diff Show More